Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions src/lib/omni-runner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1009,6 +1009,60 @@ describe('omni runner — Model A route-scoped run acks (⏳→✅/❌)', () =>
expect(published.length).toBe(1);
expect(content(published[0])).toBe('still replies');
});

test('the ✅ HTTP call is not dispatched until the ⏳ call settles, even when the run finishes first', async () => {
const db = freshDb();
const dispatched: string[] = []; // emojis in HTTP-dispatch order
let releasePending: (() => void) | undefined;
const runner = createOmniRunner({
db,
config: rt(),
publish: () => {},
// The run completes instantly — long before the ⏳ HTTP call lands.
spawnClaude: async () => ({ stdout: 'instant', exitCode: 0 }),
setReaction: ({ emoji }) => {
dispatched.push(emoji);
if (emoji === HOURGLASS) {
// Hold the ⏳ call open until the test releases it.
return new Promise((resolve) => {
releasePending = () => resolve({ success: true });
});
}
return Promise.resolve({ success: true });
},
});

runner.handleMessage(...mappedInboundWithId('fast run, slow ack', 'wamid-seq'));
// Give the run every chance to finish while the ⏳ call is still in flight.
await new Promise((r) => setTimeout(r, 20));
expect(dispatched).toEqual([HOURGLASS]); // ✅ must wait for the ⏳ to settle

releasePending?.();
await runner.whenIdle();
expect(dispatched).toEqual([HOURGLASS, CHECK]); // ⏳ strictly before ✅ at the API
});

test('the final ✅ is still dispatched when the ⏳ emit REJECTS', async () => {
const db = freshDb();
const dispatched: string[] = [];
const runner = createOmniRunner({
db,
config: rt(),
publish: () => {},
spawnClaude: async () => ({ stdout: 'ok', exitCode: 0 }),
setReaction: async ({ emoji }) => {
dispatched.push(emoji);
if (emoji === HOURGLASS) throw new Error('network down');
return { success: true };
},
});

runner.handleMessage(...mappedInboundWithId('resilient', 'wamid-rej'));
await runner.whenIdle();

// The chain survives a rejected ⏳ — the final ack still goes out.
expect(dispatched).toEqual([HOURGLASS, CHECK]);
});
});

// ---------------------------------------------------------------------------
Expand Down
33 changes: 23 additions & 10 deletions src/lib/omni-runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -740,8 +740,11 @@ export function createOmniRunner(deps: OmniRunnerDeps): OmniRunner {
controller.signal.addEventListener('abort', () => reject(new OneShotTimeoutError()), { once: true });
});
// ⏳ on the inbound message right before the spawn (route-scoped, no-op if the
// inbound carried no stanza id) — the first half of the run's ⏳→✅/❌ ack.
emitRouteReaction(route, messageId, STATUS_PENDING);
// inbound carried no stanza id) — the first half of the run's ⏳→✅/❌ ack. The
// settlement promise (always fulfilled — emit errors are swallowed inside) is
// kept so the final ✅/❌ can be chained AFTER the ⏳ HTTP call has landed: a run
// that finishes before the ⏳ reaches the API must never leave ✅→⏳ reordered.
const pendingAck = emitRouteReaction(route, messageId, STATUS_PENDING);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

When messageId is not provided (which is common for messages that do not support reactions), calling emitRouteReaction and chaining on its promise is unnecessary. We can optimize this by only creating the promise chain when messageId is present, avoiding useless promise allocations and microtask scheduling on the hot path.

Suggested change
const pendingAck = emitRouteReaction(route, messageId, STATUS_PENDING);
const pendingAck = messageId ? emitRouteReaction(route, messageId, STATUS_PENDING) : undefined;

try {
// Wrap so a SYNCHRONOUS throw from the executor becomes a rejection the
// race can observe — and so `aborted` always gets a handler attached
Expand All @@ -768,11 +771,14 @@ export function createOmniRunner(deps: OmniRunnerDeps): OmniRunner {
);
publish(replySubject, buildRoutedReplyPayload(route.instance, route.chat, content, genId(), now()));
// ✅ once a genuine reply is published; ❌ on a non-zero exit or soft error.
emitRouteReaction(route, messageId, ok ? STATUS_APPROVED : STATUS_DENIED);
// Chained on the ⏳ emit's settlement (fulfilled even when it failed) so the
// pair reaches the API in order; still fire-and-forget for this run.
pendingAck.finally(() => emitRouteReaction(route, messageId, ok ? STATUS_APPROVED : STATUS_DENIED));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Only chain the final reaction if pendingAck was successfully created (i.e., when messageId is present).

Suggested change
pendingAck.finally(() => emitRouteReaction(route, messageId, ok ? STATUS_APPROVED : STATUS_DENIED));
if (pendingAck) {
pendingAck.finally(() => emitRouteReaction(route, messageId, ok ? STATUS_APPROVED : STATUS_DENIED));
}

} catch (err) {
const content = err instanceof OneShotTimeoutError ? timeoutNotice(timeoutMs) : errorNotice(errText(err));
publish(replySubject, buildRoutedReplyPayload(route.instance, route.chat, content, genId(), now()));
emitRouteReaction(route, messageId, STATUS_DENIED); // ❌ on timeout / crash
// ❌ on timeout / crash — same ordering chain as the success path.
pendingAck.finally(() => emitRouteReaction(route, messageId, STATUS_DENIED));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Only chain the final reaction if pendingAck was successfully created (i.e., when messageId is present).

Suggested change
pendingAck.finally(() => emitRouteReaction(route, messageId, STATUS_DENIED));
if (pendingAck) {
pendingAck.finally(() => emitRouteReaction(route, messageId, STATUS_DENIED));
}

} finally {
clearTimeout(timer);
controller.abort(); // ensure a still-running child is killed on every path
Expand Down Expand Up @@ -817,6 +823,10 @@ export function createOmniRunner(deps: OmniRunnerDeps): OmniRunner {
* successful set: a dropped/failed react leaves `last_status_glyph` unchanged so
* the reconciliation pass retries it next tick. Never throws — a failed status
* reaction is logged and the approval decision still stands.
*
* Returns the emit's SETTLEMENT promise (always fulfilled — rejections are
* swallowed above; no-op emits resolve immediately) so a caller can sequence a
* follow-up ack after this one without ever awaiting it on the hot path.
*/
function emitReaction(params: {
instance: string;
Expand All @@ -827,10 +837,10 @@ export function createOmniRunner(deps: OmniRunnerDeps): OmniRunner {
recordGlyph: boolean;
/** Apply the `ackInFlight` double-fire guard (approval reconciliation only). */
guard: boolean;
}): void {
}): Promise<void> {
const { instance, chat, targetId, emoji, recordGlyph, guard } = params;
if (!targetId) return;
if (guard && ackInFlight.has(targetId)) return;
if (!targetId) return Promise.resolve();
if (guard && ackInFlight.has(targetId)) return Promise.resolve();
if (guard) ackInFlight.add(targetId);
const react = setReaction({ instance, chat, messageId: targetId, emoji })
.then((res) => {
Expand All @@ -846,6 +856,7 @@ export function createOmniRunner(deps: OmniRunnerDeps): OmniRunner {
inFlightReactions.delete(react);
});
inFlightReactions.add(react);
return react;
}

/** Approval-scoped ⏳/✅/❌ ack: scoped to the approval chat, glyph-recorded and
Expand All @@ -867,10 +878,12 @@ export function createOmniRunner(deps: OmniRunnerDeps): OmniRunner {
* route's own (instance, chat), NOT the approval chat. No glyph is recorded (a
* plain inbound has no approval row) and no reconciliation guard applies (the
* ⏳→✅/❌ pair fires exactly once, sequentially, per run). A missing messageId is
* a no-op. Fire-and-forget, drained by `whenIdle`; never blocks the run.
* a no-op. Fire-and-forget, drained by `whenIdle`; never blocks the run. Returns
* the emit's settlement promise so {@link runOneShot} can chain the final ✅/❌
* after the ⏳ has landed (else a fast run could get its acks reordered at the API).
*/
function emitRouteReaction(route: OmniRoute, messageId: string | undefined, emoji: string): void {
emitReaction({
function emitRouteReaction(route: OmniRoute, messageId: string | undefined, emoji: string): Promise<void> {
return emitReaction({
instance: route.instance,
chat: route.chat,
targetId: messageId,
Expand Down