Skip to content

fix(mcp): the sync /task route answers with an execution_id, not fetch failed (#2661) - #2675

Merged
vybe merged 6 commits into
devfrom
feature/2661-task-queued-timeout-receipt
Sep 11, 2026
Merged

vybe merged 6 commits into
devfrom
feature/2661-task-queued-timeout-receipt

Conversation

@trinity-ability

@trinity-ability trinity-ability commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The #914 gateway-timeout receipt covered the sequential /chat route only. chat_with_agent(parallel=true, async=false) dispatches through client.ts::task(), which held the backend fetch for timeout_seconds + 60 (up to 7260s). The MCP client's own gateway timeout kills the JSON-RPC call long before that, so the caller saw a bare fetch failed while the target kept running — no receipt, no execution_id, nothing to poll. The tool description's advice ("poll get_execution_result instead of retrying") was unreachable on this route because the caller never received an id.

Fleet incident 2026-09-08: every duplicate dispatch in a three-hop cascade was a re-send after "could not confirm delivery" on this path.

Why the #914 matcher could not simply be mirrored

/chat is queue-serialised, so "newest non-terminal MCP row wins" is near-unambiguous there. /task exists to run N tasks concurrently, and every filter that rule applies — triggered_by, source_mcp_key_id, the recency window — is identical across one caller's concurrent tasks. Mirroring it would have handed caller A the execution_id of caller B's task; A then polls and acts on a well-formed foreign result. Silent wrong data is worse than the loud error it replaces.

The issue's AC 2 ("emitted only when an execution row exists for the call") is not satisfiable by that matcher at all — it can only ever prove an execution exists.

Attribution is now provable or absent

Rule Why
Read execution_id out of an idempotency 409 instead of collapsing it into API error (409) Exact key→execution mapping the backend already sends (RELIABILITY-006)
Match the call's own message The only per-call discriminator on the row
>1 candidate ⇒ no receipt Ambiguity equals pre-#914 behaviour; a wrong id is worse than none
AbortError only A TypeError may mean the request never landed, and here a concurrent peer row is the normal state

Deliberately not done: re-POSTing the dispatch with the same key as a "probe". idempotency_service.begin() fails open, so on that path the probe dispatches a second execution — precisely the bug being fixed.

Three latent defects in the shipped /chat route, fixed alongside

  • The operator knob was a silent kill-switch. The recency window was a fixed 30s while the abort fires at MCP_CHAT_TIMEOUT_MS. Raising that documented knob to ≥30s ("for unusually slow networks") put every candidate row outside the window, degrading every receipt on both routes to the no-match throw. Now derived (timeout + 10s).
  • The recovery lookup was unbounded. It ran through _fetch, which has no AbortController and re-authenticates once on 401. We abort at 25s because the gateway ceiling is close; an unbounded lookup spends what's left and — when the backend is the slow party, the usual reason we aborted — reproduces the very fetch failed this exists to prevent. Now MCP_RECOVERY_TIMEOUT_MS, no retry, 50 rows instead of 10.
  • The trigger allowlist had to become per-call-site. Widening the shared constant with self_task would have let a /chat abort attribute a concurrently-running parallel self-task row — /task is unqueued, so such a row can be RUNNING while a /chat sits queued.

Backend counterpart: the 24h idempotency wedge

_map_task_failure raises between begin() and complete(), and nothing covered that path — so every failed/cancelled/timed-out sync /task left its claim in_flight for the full 24h TTL. A legitimate retry then answered 409 for a day against a task dead for minutes, and rewording was the only way through — which derives a different key and dispatches a genuine duplicate. The wedge didn't just block retries; it selected for the duplicate-dispatch behaviour this issue exists to stop. idem is keyword-only and required so a third sync branch can't silently reintroduce it.

All three exits are closed now (2026-09-11 round, after the merge-train hold): _map_task_failure (failed/cancelled → release) plus the two in _dispatch_sync_backlog — a vanished row releases; a long-poll timeout re-reads the row, settles a terminal the wait missed normally, and for a row still queued/running completes the claim with a queued_timeout receipt (not released — a retry would dispatch a duplicate beside the live execution; not left in_flight — nothing downstream completes it). An AST guard pins that no raise in that function precedes a fail()/complete().

⚠️ Behaviour change worth knowing: releasing the claim means a genuine re-send after a failure now re-executes instead of being absorbed by the 409. That's the intended semantic — a failed task should be retryable — but the wedge was accidentally suppressing retry storms against a persistently-failing agent. The dispatch breaker and capacity manager are the real protection there, not a stuck idempotency row.

The client change is CI-gated (2026-09-11)

src/mcp-server/src/task-receipt.test.ts drives TrinityClient.task() and chat() against a stubbed fetch: 409 → receipt, abort → executions lookup → receipt, the ambiguity throw, async_mode and TypeError NOT recovering, and that both routes emit the same receipt for the same 409. Mutation-checked — disabling either branch in sendTask reds the file. chat() now honours the 409 rule the tool description promises for every sync route; verify_914.ts uses a per-route prompt (the shared one made both mode refuse on its own ambiguity) and exits non-zero on a fast response; MCP_RECOVERY_TIMEOUT_MS is wired into all three composes + .env.example, and MCP_CHAT_TIMEOUT_MS into prod/hosted.

Also ships CI for this package

Nothing ran the MCP server's suite: helper-mcp-test.yml covers src/helper-mcp/** only, and container-security.yml filters on src/mcp-server/Dockerfile, not src/mcp-server/src/**. So 341 tests across 28 files gated nothing, and npm run build — this package's only typecheck — first ran when deploy-dev built the image on dev, breaking the deploy instead of the PR. A reliability fix whose only guard is a suite nothing runs is not a guard. (Partially addresses #2363.)

Changes

File What
src/mcp-server/src/client.ts sync task() bound + receipt + 409 read; matcher gains triggers/message/ambiguity rule; bounded recovery fetch; extractIdempotencyExecutionId
src/mcp-server/src/tools/chat.ts parallel-branch receipt log; description covers every sync mode
src/backend/services/chat_execution_service.py _map_task_failure releases the claim; idem required keyword-only
.github/workflows/mcp-server-test.yml new — build (typecheck) + unit
tests/unit/test_2661_task_timeout_receipt.py new — 9 cases incl. an AST guard over call sites
client.test.ts / chat.test.ts matcher + tool-layer coverage
scripts/verify_914.ts [chat|task|both] modes; unique prompt; real key id
docs requirements §37 (renamed Chat → Dispatch), architecture/mcp-server.md, mcp-orchestration.md, index

Test Plan

  • cd src/mcp-server && npm test → 341 passed / 0 failed (was 328)
  • npx tsc --noEmit → clean
  • pytest tests/unit/test_2661_task_timeout_receipt.py → 9 passed
  • Full backend unit suite → 15009 passed; 2 failures pre-existing on clean dev (verified by stashing — both blame venv/site-packages/ and the enterprise submodule)
  • Mutation-verified: removing the release → 6 fail; dropping idem= from a call site → the AST guard fails
  • Live — abort at 400ms on /task returned a real receipt; polling its execution_id resolved with triggered_by=mcp, the exact message, and the real source_mcp_key_id, so the key filter genuinely engaged (the harness previously passed a fabricated id that could never match a row, making green runs meaningless — fixed here)
  • Live — wedge before/after: without the fix a second send after a failure returned 409 request_in_progress against an already-dead task; with it, a fresh dispatch

Follow-ups filed

Fixes #2661

🤖 Generated with Claude Code

https://claude.ai/code/session_01PmVdJbnrh1kZJjuYHQYNCE

…ch failed` (#2661)

The #914 gateway-timeout receipt covered the sequential /chat route only.
`chat_with_agent(parallel=true, async=false)` dispatches through
`client.ts::task()`, which held the backend fetch for `timeout_seconds + 60`
(up to 7260s). The MCP client's own gateway timeout kills the JSON-RPC call
long before that, so the caller saw a bare `fetch failed` while the target kept
running — no receipt, no execution_id, nothing to poll. Fleet incident
2026-09-08: every duplicate dispatch in a three-hop cascade was a re-send after
"could not confirm delivery" on this path.

The #914 matcher could NOT simply be mirrored. /chat is queue-serialised, so
"newest non-terminal MCP row wins" is near-unambiguous there. /task exists to
run N tasks concurrently, and every filter that rule applies — triggered_by,
source_mcp_key_id, the recency window — is IDENTICAL across one caller's
concurrent tasks. Mirroring it would have handed caller A the execution_id of
caller B's task; A then polls and acts on a well-formed FOREIGN result. Silent
wrong data is worse than the loud error it replaces.

Attribution is now provable or absent:
  - read the execution_id out of an idempotency 409 instead of collapsing it
    into an opaque `API error (409)` — an exact key->execution mapping the
    backend already sends (RELIABILITY-006)
  - match the call's own `message`, not just key + trigger
  - return NOTHING when more than one candidate survives; ambiguity yields no
    receipt, which is exactly the pre-#914 behaviour, so refusing to guess is
    never worse than before
  - recover on AbortError only — a TypeError may mean the request never landed,
    and on this route a concurrent peer row is the normal state

Deliberately NOT done: re-POSTing the dispatch with the same key as a "probe".
`idempotency_service.begin()` fails open, so on that path the probe would
dispatch a second execution — precisely the bug being fixed.

Three latent defects in the already-shipped /chat route, fixed alongside:

  - The recency window was a fixed 30s while the abort fires at
    MCP_CHAT_TIMEOUT_MS. Raising that documented operator knob to >=30s put
    every candidate row outside the window, silently degrading every receipt on
    both routes to the no-match throw — the knob disabled the feature it was
    meant to tune. The window is now derived (timeout + 10s).
  - The recovery lookup ran through `_fetch`, which has no AbortController and
    re-authenticates once on 401. We abort at 25s precisely BECAUSE the gateway
    ceiling is close; an unbounded lookup spends what is left of it and, when
    the backend is the slow party (the usual reason we aborted), reproduces the
    very `fetch failed` this feature exists to prevent. Now bounded by
    MCP_RECOVERY_TIMEOUT_MS with no retry, and reads 50 rows rather than 10.
  - The trigger allowlist had to become per-call-site. Widening the shared
    constant with `self_task` would have let a /chat abort attribute a
    concurrently-running parallel self-task row — /task is unqueued, so such a
    row can be RUNNING while a /chat sits queued.

Backend counterpart: a failed/cancelled/timed-out sync /task left its
idempotency claim in_flight for the full 24h TTL, because `_map_task_failure`
raises between `begin()` and `complete()` and nothing covered that path. A
legitimate retry then answered 409 for a day against a task dead for minutes,
and REWORDING was the only way through — which derives a different key and
dispatches a genuine duplicate. The wedge did not just block retries, it
selected for the duplicate-dispatch behaviour #2661 exists to stop. `idem` is
keyword-only and required so a third sync branch cannot silently reintroduce it.

Also ships `.github/workflows/mcp-server-test.yml`. Nothing ran this package's
suite: helper-mcp-test.yml covers src/helper-mcp only, and container-security
filters on the Dockerfile, not src/**. So 341 tests across 28 files gated
nothing, and `npm run build` — this package's only typecheck — first ran when
deploy-dev built the image ON dev, breaking the deploy instead of the PR.

Verified live against a running stack, not just in unit tests:
  - abort at 400ms on /task returned a real receipt; polling its execution_id
    resolved, with triggered_by=mcp, the exact message, and the real
    source_mcp_key_id — so the key filter genuinely engaged. The harness
    previously passed a fabricated keyId that could never match a row, making a
    green run meaningless; fixed here.
  - wedge before/after: without the fix a second send after a failure returned
    409 request_in_progress against an already-dead task; with it, a fresh
    dispatch.
  - both new backend guards mutation-verified (remove the release -> 6 fail;
    drop idem= from a call site -> the AST guard fails).

fan_out is the third route of this class and stays open (#2670) — it needs a
fan_out_id receipt and no polling surface resolves one. The read-only
idempotency lookup that would retire this heuristic on every route is #2671.

Fixes #2661

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01PmVdJbnrh1kZJjuYHQYNCE
- a selection heuristic ported to a route with different concurrency turns
  "no answer" into a confident wrong one; ambiguity must return nothing, and
  the identity the system already records beats elimination
- a documented operator knob whose dependent constant is hardcoded is a silent
  kill-switch: raising MCP_CHAT_TIMEOUT_MS as documented disabled every receipt
- a failure path between begin() and complete() wedges the idempotency claim,
  and the reword that gets a caller past the 409 is what creates a real
  duplicate — fix the choke point, guard the call sites with AST

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01PmVdJbnrh1kZJjuYHQYNCE
@vybe

vybe commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

merge-train 2026-09-10: held for the next train. This one is ours (trinity-ability), so there is no author to send it back to — it's a work item for us, not a hand-off. Recording why it didn't ride, so the next run doesn't re-derive it.

It is security-clean. Zero criticals across /validate-pr, /review and /cso --diff, with two fresh-context adversarial verifiers returning nothing. The new workflow is pull_request (not pull_request_target), has zero ${{ }} expressions anywhere, declares explicit permissions: contents: read — better than codeql.yml and sync-docs-to-vertex.yml, which declare none — and pulls in no third-party actions. One this.token use in the whole diff (the Authorization header at client.ts:966); no receipt embeds the user's prompt. The >1 candidate → undefined rule is a security improvement over the pre-PR matches[0]. verify_914.ts is not shipped (outside the Dockerfile COPY set, tsconfig include, and the npm test glob), and mcp_api_keys.id is not credential material.

Why it's held — the fix is two-thirds done while the body claims it's whole. chat_execution_service.py:1697 and :1712 are two exits that still wedge the 24h idempotency claim, which is the exact failure this PR exists to close. A reliability fix that leaves two of its own exits unfixed, and states completeness in its body, is the #2603 class: the PR reads as done and the defect survives. Closing those two exits is a behaviour decision (whether a budget-409 should release the claim is not obvious), so it's real work rather than a train patch.

Second reason, same root. The client-side change has zero CI coverage — mutation-proven, not inferred. This PR ships a CI gate specifically to guard this behaviour, and the behaviour it guards isn't the behaviour it changed.

Mechanical items to sweep at the same time:

  • MCP_RECOVERY_TIMEOUT_MS is unwired, and MCP_CHAT_TIMEOUT_MS is absent from prod compose — both fail safe, but the lever is inert (#1039 class)
  • verify_914.ts is broken in default mode
  • chat() doesn't implement the "every route" 409 rule the PR describes
  • a tautological exit condition, and a stray markdown separator

One pre-existing item found on the way, explicitly NOT this PR's to fix. idempotency_service.make_agent_scope() returns f"agent:{agent_name}" with no identity component, and the sibling make_inline_auth_scope() docstring (same file, lines 64-83) spells out the failure mode itself: two verified users of a shared agent derive the same (scope, key), and the second replays the first's stored response snapshot and execution_id — a cross-user disclosure. The residual is narrower than that docstring implies for the MCP path, because deriveMcpIdempotencyKey already folds caller identity in; the exposure is a direct REST caller supplying an arbitrary Idempotency-Key on /api/agents/{name}/task against a shared agent. idempotency_service.py is not in this diff and the behaviour is identical before and after — this PR only changes what the MCP client does with a 409 body that already carried execution_id. Deserves its own ticket, with make_inline_auth_scope and derive_payment_key (#1018) as the precedent for the fix shape.

@github-actions

Copy link
Copy Markdown

⚠️ Nightly unit-suite check skipped — merge conflict against dev.

Resolve by running git merge dev locally and pushing the result. The next nightly run will re-test once the conflict is gone.

dolho and others added 3 commits September 11, 2026 16:12
…te the client change (#2661 review)

The 2026-09-10 merge-train hold on #2675, item by item.

Backend — `_dispatch_sync_backlog` had two exits between `begin()` and
`complete()` that `_map_task_failure` never saw:

- long-poll timeout: no longer raises from the `except`. The row is read
  first; a terminal the wait missed is reconstructed and settled the normal
  way (success → complete, failed → release). A row still queued/running
  completes the claim with a `queued_timeout` RECEIPT (`_queued_payload`
  shape, the MCP client's own vocabulary) — not released, because a retry
  would dispatch a second execution beside the live one; not left in_flight,
  because nothing downstream completes it and a retry after the row
  terminates would still 409 for a day.
- vanished row (503): releases. Nothing is running under this key that
  anyone can find, so a retry must be allowed to dispatch.

Four executed cases plus an AST guard that every `raise ChatDispatchError` in
that function is preceded by a `fail()`/`complete()` in its block.

MCP client — `task-receipt.test.ts` drives `TrinityClient.task()` and `chat()`
against a stubbed `fetch`: the 409 → receipt branch, the abort → executions
lookup → receipt path, the ambiguity throw, async_mode and TypeError NOT
recovering. Mutation-checked: disabling either branch reds the file.

- `chat()` now honours the same 409 rule the tool description promises for
  every sync route, through a shared `inFlightReplayReceipt` so the two
  routes cannot drift.
- `verify_914.ts`: per-route prompt — in `both` mode the still-running chat
  row matched the task lookup's exact-message filter, two survivors, refused
  on ambiguity, exit 1. And `? 0 : 0` is now `? 0 : 1`.
- `MCP_RECOVERY_TIMEOUT_MS` wired into all three composes + `.env.example`;
  `MCP_CHAT_TIMEOUT_MS` added to prod + hosted (it was dev-only).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht
…ed-timeout-receipt

# Conflicts:
#	docs/memory/learnings.md
@dolho

dolho commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Addressed the 2026-09-10 hold in 3484ef732 + 10228b395 (and merged dev — the nightly conflict in learnings.md was the append-only keep-both).

The two wedged exits (_dispatch_sync_backlog) — the behaviour decision, stated:

  • Vanished row → release. Nothing is running under that key that anyone can find, so a retry must be allowed to dispatch. Same verdict _map_task_failure gives a failed row.
  • Long-poll timeout → read the row first. A terminal the wait missed (lost wakeup, or one landing in the cap's last tick) is reconstructed and settled the normal way — success completes, failed/cancelled releases. A row still queued/running completes the claim with a queued_timeout receipt (the _queued_payload shape, the MCP client's own vocabulary). Not released, because a retry would dispatch a second execution beside the live one — the duplicate idempotency exists to stop. Not left in_flight, because nothing downstream completes it, so a retry after the row terminates would still 409 for a day. A replay answers 200 + the execution to poll; the row stays the single source of truth.
  • Four executed cases in test_2661_task_timeout_receipt.py (14 total) plus an AST guard: every raise ChatDispatchError in that function must be preceded in its block by a fail()/complete().

Client-side CI coverage — task-receipt.test.ts drives TrinityClient.task()/chat() against a stubbed fetch: 409 → receipt, abort → lookup → receipt, ambiguity throw, async_mode and TypeError not recovering. Mutation-checked: === 4090 reds 1, disabling the abort branch reds 2. Full package: 350 pass, tsc clean.

Mechanical sweep

  • chat() now honours the 409 rule the description promises for every sync route, via a shared inFlightReplayReceipt (a test asserts chat() and task() emit the identical receipt for the same 409).
  • verify_914.ts default mode: one shared prompt on two routes meant the task lookup saw the still-running chat row too → two survivors → refused on ambiguity → exit 1. Per-route prompt now; and ? 0 : 0 → ? 0 : 1.
  • MCP_RECOVERY_TIMEOUT_MS wired into all three composes + .env.example; MCP_CHAT_TIMEOUT_MS added to prod and hosted (test_2280_hosted_compose_parity green).
  • The stray markdown separator: I could not find one in the diff or the body — if you still see it, point me at the line.

PR body updated to say what is actually closed. make_agent_scope() residual left alone per your note — its own ticket.

🤖 Generated with Claude Code

https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht

@github-actions

Copy link
Copy Markdown

⚠️ Live-instance suite skipped — merge conflict against dev.

Resolve by merging dev locally and pushing the result; the next nightly re-tests.

@vybe

vybe commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

merge-train 2026-09-11: on this train. Lane C validated: the new workflow runs npm run build before npm test as its comment says, paths: covers src/mcp-server/**, contents: read is the only permission, the two timeouts land in all three compose files with matching defaults and .env.example. /cso --diff has nothing at the gate. test_2661_task_timeout_receipt.py runs the real _dispatch_sync_backlog; task-receipt.test.ts drives real task()/chat() against a stubbed fetch. 350/350 TS, 49/49 pytest locally.

Follow-ups for #2671, none blocking:

  • A fourth begin → no fail exit remains outside the "all three exits" claim — chat_execution_service.py:1295 process_task_file_uploads raises 502 after begin() with no fail(), so the claim wedges 24 h with execution_id=None. Only reachable with files, which the MCP client never sends; the AST guard covers _dispatch_sync_backlog only. Wrap the call in dispatch_parallel_task with except ChatDispatchError: fail(idem); raise.
  • Receipt shape drift on replay — the backend receipt (:1740) uses agent_name/task_execution_id/async_mode; the MCP receipt uses agent. A same-key re-send after the long-poll timeout returns 200 + snapshot which task() passes through verbatim, so the caller sees agent_name where the tool description promises agent. runAgentChat still routes correctly on status.
  • chat()'s abort → findRecentMcpExecution wiring (client.ts:844-848) and the recovery-lookup failure path (getRecentExecutionsForRecovery, MCP_RECOVERY_TIMEOUT_MS) have no executing test — task() has the hangUntilAbort case; chat() never did. client.ts:1122's "no execution could be attributed" also fires when the recovery fetch itself timed out; only debugLog distinguishes.
  • _SYNC_BACKLOG_TERMINAL (:1558) duplicates sync_waiter.TERMINAL_TASK_STATUSES; chat() still builds its receipt inline (client.ts:850-858) while task() uses the shared queuedTimeoutReceipt.

…ed-timeout-receipt

# Conflicts:
#	docs/memory/learnings.md

@vybe vybe left a comment

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.

merge-train: batch validated on train/20260911-1635 (#2729)

@vybe vybe left a comment

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.

merge-train: batch validated on train/20260911-1635 (#2729)

@vybe
vybe merged commit d9854e7 into dev Sep 11, 2026
29 checks passed
vybe added a commit that referenced this pull request Sep 11, 2026
#2670) (#2679)

* fix(mcp): the sync /task route answers with an execution_id, not `fetch failed` (#2661)

The #914 gateway-timeout receipt covered the sequential /chat route only.
`chat_with_agent(parallel=true, async=false)` dispatches through
`client.ts::task()`, which held the backend fetch for `timeout_seconds + 60`
(up to 7260s). The MCP client's own gateway timeout kills the JSON-RPC call
long before that, so the caller saw a bare `fetch failed` while the target kept
running — no receipt, no execution_id, nothing to poll. Fleet incident
2026-09-08: every duplicate dispatch in a three-hop cascade was a re-send after
"could not confirm delivery" on this path.

The #914 matcher could NOT simply be mirrored. /chat is queue-serialised, so
"newest non-terminal MCP row wins" is near-unambiguous there. /task exists to
run N tasks concurrently, and every filter that rule applies — triggered_by,
source_mcp_key_id, the recency window — is IDENTICAL across one caller's
concurrent tasks. Mirroring it would have handed caller A the execution_id of
caller B's task; A then polls and acts on a well-formed FOREIGN result. Silent
wrong data is worse than the loud error it replaces.

Attribution is now provable or absent:
  - read the execution_id out of an idempotency 409 instead of collapsing it
    into an opaque `API error (409)` — an exact key->execution mapping the
    backend already sends (RELIABILITY-006)
  - match the call's own `message`, not just key + trigger
  - return NOTHING when more than one candidate survives; ambiguity yields no
    receipt, which is exactly the pre-#914 behaviour, so refusing to guess is
    never worse than before
  - recover on AbortError only — a TypeError may mean the request never landed,
    and on this route a concurrent peer row is the normal state

Deliberately NOT done: re-POSTing the dispatch with the same key as a "probe".
`idempotency_service.begin()` fails open, so on that path the probe would
dispatch a second execution — precisely the bug being fixed.

Three latent defects in the already-shipped /chat route, fixed alongside:

  - The recency window was a fixed 30s while the abort fires at
    MCP_CHAT_TIMEOUT_MS. Raising that documented operator knob to >=30s put
    every candidate row outside the window, silently degrading every receipt on
    both routes to the no-match throw — the knob disabled the feature it was
    meant to tune. The window is now derived (timeout + 10s).
  - The recovery lookup ran through `_fetch`, which has no AbortController and
    re-authenticates once on 401. We abort at 25s precisely BECAUSE the gateway
    ceiling is close; an unbounded lookup spends what is left of it and, when
    the backend is the slow party (the usual reason we aborted), reproduces the
    very `fetch failed` this feature exists to prevent. Now bounded by
    MCP_RECOVERY_TIMEOUT_MS with no retry, and reads 50 rows rather than 10.
  - The trigger allowlist had to become per-call-site. Widening the shared
    constant with `self_task` would have let a /chat abort attribute a
    concurrently-running parallel self-task row — /task is unqueued, so such a
    row can be RUNNING while a /chat sits queued.

Backend counterpart: a failed/cancelled/timed-out sync /task left its
idempotency claim in_flight for the full 24h TTL, because `_map_task_failure`
raises between `begin()` and `complete()` and nothing covered that path. A
legitimate retry then answered 409 for a day against a task dead for minutes,
and REWORDING was the only way through — which derives a different key and
dispatches a genuine duplicate. The wedge did not just block retries, it
selected for the duplicate-dispatch behaviour #2661 exists to stop. `idem` is
keyword-only and required so a third sync branch cannot silently reintroduce it.

Also ships `.github/workflows/mcp-server-test.yml`. Nothing ran this package's
suite: helper-mcp-test.yml covers src/helper-mcp only, and container-security
filters on the Dockerfile, not src/**. So 341 tests across 28 files gated
nothing, and `npm run build` — this package's only typecheck — first ran when
deploy-dev built the image ON dev, breaking the deploy instead of the PR.

Verified live against a running stack, not just in unit tests:
  - abort at 400ms on /task returned a real receipt; polling its execution_id
    resolved, with triggered_by=mcp, the exact message, and the real
    source_mcp_key_id — so the key filter genuinely engaged. The harness
    previously passed a fabricated keyId that could never match a row, making a
    green run meaningless; fixed here.
  - wedge before/after: without the fix a second send after a failure returned
    409 request_in_progress against an already-dead task; with it, a fresh
    dispatch.
  - both new backend guards mutation-verified (remove the release -> 6 fail;
    drop idem= from a call site -> the AST guard fails).

fan_out is the third route of this class and stays open (#2670) — it needs a
fan_out_id receipt and no polling surface resolves one. The read-only
idempotency lookup that would retire this heuristic on every route is #2671.

Fixes #2661

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01PmVdJbnrh1kZJjuYHQYNCE

* docs(learnings): three durable classes from the #2661 review

- a selection heuristic ported to a route with different concurrency turns
  "no answer" into a confident wrong one; ambiguity must return nothing, and
  the identity the system already records beats elimination
- a documented operator knob whose dependent constant is hardcoded is a silent
  kill-switch: raising MCP_CHAT_TIMEOUT_MS as documented disabled every receipt
- a failure path between begin() and complete() wedges the idempotency claim,
  and the reword that gets a caller past the 409 is what creates a real
  duplicate — fix the choke point, guard the call sites with AST

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01PmVdJbnrh1kZJjuYHQYNCE

* fix(mcp): fan_out answers with a fan_out_id, and a batch can be polled (#2670)

The third and last route of the #914 class, and the one that hits it most
reliably: a fan-out dispatches N tasks and by construction runs longer than any
single one of them, so it exceeds the gateway ceiling more often than the two
routes already fixed. `client.ts::fanOut()` carried the identical unbounded
`(timeout_seconds ?? 7200) + 60`, so the MCP client's own 30-60s timeout killed
the JSON-RPC call and the caller saw a bare `fetch failed` while every dispatched
task kept running — with nothing to poll.

**The receipt names a `fan_out_id`, not an `execution_id`.** A batch is N rows
sharing one id, so a single execution id could only ever name an arbitrary
member of it. `{status: "fan_out_timeout", agent, fan_out_id, execution_ids,
task_count, message}`; `execution_ids` is evidence, not a manifest, since a
slot-starved subtask has no row yet.

**Ambiguity is redefined, not reused.** #2661 refuses when more than one ROW
survives its filters, because on `/task` it cannot tell which row is the
caller's. A fan-out stamps one `fan_out_id` on all N of its rows, so finding ANY
row finds the batch and N survivors is the expected shape. The unit that must be
unambiguous is the BATCH: `pickRecentFanOut` returns nothing when more than one
distinct `fan_out_id` survives. Same rule ("a wrong id is worse than none"),
measured on the right thing.

**Status is deliberately not filtered.** `/chat` and `/task` require a
non-terminal row, because a terminal one is evidence the receipt is unnecessary.
By abort time a fan-out is normally a mix — some subtasks finished, others
running — so requiring non-terminal rows would drop exactly the batches furthest
along. The derived recency window (#2661's rule, `timeout + 10s`, never a fixed
constant) is what bounds staleness.

**The polling surface reads rows, not the idempotency snapshot.**
`GET /api/agents/{name}/fan-out/{fan_out_id}` folds `schedule_executions` — where
`fan_out_id` has been stamped on every subtask since FANOUT-001 — into
`{status, total, completed, failed, running, results[]}`. `routers/fan_out.py`
does store the whole aggregate under the call's key, which looks like a free
receipt, but `complete()` runs only once the batch has FINISHED, so the snapshot
cannot answer what a timed-out caller is actually asking: what is happening
right now. That is also why this does not collapse into #2671.

Batch status is `running` while any subtask can still change, then `completed` /
`partial` / `failed`. `partial` exists because best-effort is the fan-out's
default policy. `deadline_exceeded` is absent by construction — it is the
dispatcher's verdict on its own outer deadline, not a property of any row.
Per-task status is the EXECUTION status verbatim, so a subtask waiting for a
slot is distinguishable from one that ran; the dispatch response's two-value
`completed`/`failed` pair would report a healthy queued subtask as a failure.
Enumeration-safe: malformed, unknown and belonging-to-another-agent are one 404.

**Two backend contracts the client depends on.** The in-flight 409 now returns
the same `{error, message, execution_id}` shape `/chat` and `/task` do — it was
a bare string, so `fan_out` could not benefit from the #2661 client that reads
that field — and the batch id is attached to the idempotency claim WHEN IT IS
MINTED (`FanOutService.execute(on_started=…)`) rather than at `complete()`.
Attaching at the end records it exactly when nobody needs it any more: the
window in which a duplicate arrives, and in which this call's gateway gives up,
is the whole run. The hook is best-effort — bookkeeping must not fail a dispatch.

**MCP surface** (Invariant #13): new `get_fan_out_result` in
`tools/executions.ts`, gated to `{self} ∪ permitted` like `get_execution_result`
beside it; the `fan_out` description states the receipt and the retry asymmetry
(an identical re-send dedupes server-side, a REWORDED one dispatches all N
tasks again). `verify_914.ts` grows a `fanout` mode with three tasks, so the
harness exercises batch identification rather than a single row.

Tests: 13 TS cases on the matcher (N-rows-is-normal, two-batches-refuses,
part-finished-still-found, per-call-site trigger set, derived window) and 26
backend cases on the fold, the read surface's enumeration safety, and the two
contracts. `354` MCP tests and `15072` backend tests pass; the 15 failures in
the full run are DNS-dependent SSRF tests that fail identically on the base
branch with this change stashed.

Fixes #2670
Follow-up of #2661

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN

* fix(mcp,chat): close the two remaining idempotency-claim exits and gate the client change (#2661 review)

The 2026-09-10 merge-train hold on #2675, item by item.

Backend — `_dispatch_sync_backlog` had two exits between `begin()` and
`complete()` that `_map_task_failure` never saw:

- long-poll timeout: no longer raises from the `except`. The row is read
  first; a terminal the wait missed is reconstructed and settled the normal
  way (success → complete, failed → release). A row still queued/running
  completes the claim with a `queued_timeout` RECEIPT (`_queued_payload`
  shape, the MCP client's own vocabulary) — not released, because a retry
  would dispatch a second execution beside the live one; not left in_flight,
  because nothing downstream completes it and a retry after the row
  terminates would still 409 for a day.
- vanished row (503): releases. Nothing is running under this key that
  anyone can find, so a retry must be allowed to dispatch.

Four executed cases plus an AST guard that every `raise ChatDispatchError` in
that function is preceded by a `fail()`/`complete()` in its block.

MCP client — `task-receipt.test.ts` drives `TrinityClient.task()` and `chat()`
against a stubbed `fetch`: the 409 → receipt branch, the abort → executions
lookup → receipt path, the ambiguity throw, async_mode and TypeError NOT
recovering. Mutation-checked: disabling either branch reds the file.

- `chat()` now honours the same 409 rule the tool description promises for
  every sync route, through a shared `inFlightReplayReceipt` so the two
  routes cannot drift.
- `verify_914.ts`: per-route prompt — in `both` mode the still-running chat
  row matched the task lookup's exact-message filter, two survivors, refused
  on ambiguity, exit 1. And `? 0 : 0` is now `? 0 : 1`.
- `MCP_RECOVERY_TIMEOUT_MS` wired into all three composes + `.env.example`;
  `MCP_CHAT_TIMEOUT_MS` added to prod + hosted (it was dev-only).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht

* docs(feature-flows): the two backlog exits of the idempotency claim (#2661)

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht

* merge-train: the fan-out router's mcp header names its second tool module (#2679) — mechanical, per the merge-train note on the PR

The router is now also covered by executions.ts (get_fan_out_result) — the
Invariant #13 header is how /validate-architecture tells "unexposed on
purpose" from "forgotten", so it names both. The flow doc's harness line
still advertised [chat|task|both]; verify_914.ts takes [chat|task|fanout|all].

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018h3Ku8HFzwPfNR75kf1Gxe

---------

Co-authored-by: sim <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Eugene Vyborov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants