Skip to content

fix(workspace): bound the reply poll to a turn's real life, and stop offering Retry when it is merely lost (#2133) - #2150

Merged
vybe merged 3 commits into
devfrom
fix/2133-bounded-reply-poll
Aug 13, 2026
Merged

vybe merged 3 commits into
devfrom
fix/2133-bounded-reply-poll

Conversation

@dolho

@dolho dolho commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Closes #2133.

Two failures sit on opposite sides of one number, and both were live on dev.

Too small — the one that costs money, and it was mine

The marker TTL and the client ceiling were both 300 + 60 — one turn timeout plus slack. But run_resumable_turn re-runs the whole turn when a resume finds no JSONL, so a legitimate turn can take two full timeouts.

At 360s the marker expired mid-retry, the client was told "nothing is running", and a live, already-billed turn was declared not delivered with a Retry beside it — the exact double-billing #2120 fixed, reappearing on precisely the cold-retry path that fix existed for.

I introduced this myself in #2138 when I shortened the TTL from an hour. The issue reports the hour; the hour was already gone, and what replaced it was worse in the other direction.

Both bounds are now 2 × PORTAL_TURN_TIMEOUT_SECONDS + 60, derived from the constant the dispatch actually uses — pinned by a test, because a literal 300 at the call site is exactly how the two drift apart again.

Too large — the reported symptom

An orphaned marker (a hard kill skips the finally; except Exception never catches CancelledError) left the loop polling a dead turn ~5,100 times per tab, with nothing in the UI saying the reply was not coming. The ceiling ends it, and the poll now widens with elapsed time — 700ms → 2s → 5s → 15s — cutting the long tail by an order of magnitude at the same total wait.

Giving up is not a failure

Running out of budget while the marker still claims a turn means the turn probably ran and was billed and we merely lost sight of it. That path returns lost and renders the explanation without a Retry — re-sending is the one action guaranteed to be wrong. A genuine no-answer (server reports nothing running, no new reply) keeps its existing message and its Retry.

The budget travels on the 202 as wait_budget_seconds rather than living as a frontend constant, because the server owns the timeout. The client constant survives only as an older-backend fallback, sized identically and pinned by a test that the two agree.

Also: the #2138 guard was wrong

portalUndefinedCalls.spec.js false-positived on this change. It stripped single-quoted strings before double-quoted ones, so an apostrophe inside "we've" opened a phantom string that swallowed the rest of the file and made every later identifier read as undefined. One alternation now, leftmost match wins. Verified by mutation that it still catches a genuinely undefined call.

Verification

6 new backend tests, 254 frontend (18 files), 424 passed across the portal/session suites, build clean.

AC coverage

  • The poll cannot run unbounded when the marker is stale
  • A legitimately long turn including one cold retry still resolves — this is the half the issue asked for and the half that was actually broken
  • Giving up does not offer Retry for a turn that may have run
  • Regression test naming this issue

…offering Retry when it is merely lost (#2133)

Two failures sit on opposite sides of one number, and both were live.

**Too small — and this one costs money.** The marker TTL and the client ceiling
were both `300 + 60`, one turn timeout plus slack. But `run_resumable_turn`
re-runs the WHOLE turn when a resume finds no JSONL, so a legitimate turn can
take two full timeouts. At 360s the marker expired mid-retry, the client was
told "nothing is running", and a live, already-billed turn was declared not
delivered with a Retry beside it — the exact double-billing #2120 fixed,
reappearing on precisely the cold-retry path that fix existed for. I introduced
this myself when I shortened the TTL from an hour.

Both bounds are now `2 × PORTAL_TURN_TIMEOUT_SECONDS + 60`, derived from the
constant the dispatch actually uses (pinned by a test, because a literal `300`
at the call site is how the two drift apart again).

**Too large** was the reported symptom: an orphaned marker — a hard kill skips
the `finally`, and `except Exception` never catches `CancelledError` — left the
loop polling a dead turn ~5,100 times per tab with nothing in the UI saying the
reply was not coming. The ceiling now ends it, and the poll widens with elapsed
time (700ms → 2s → 5s → 15s), cutting the long tail by an order of magnitude at
the same total wait.

**Giving up is not a failure.** Running out of budget while the marker still
claimed a turn means the turn probably RAN and was billed and we lost sight of
it. That path now returns `lost`, which renders the explanation WITHOUT a Retry:
re-sending is the one action guaranteed to be wrong. A genuine no-answer (server
reports nothing running, no new reply) keeps its existing message.

The budget travels on the 202 (`wait_budget_seconds`) rather than living as a
frontend constant, because the server owns the timeout; the client constant
remains only as an older-backend fallback, sized identically.

Also fixes the #2138 undefined-call guard, which false-positived here: it
stripped single-quoted strings before double-quoted ones, so an apostrophe
inside "we've" opened a phantom string that swallowed the rest of the file and
made every later identifier read as undefined. One alternation now, leftmost
match wins. Verified it still catches a genuinely undefined call.

Closes #2133

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@dolho
dolho requested a review from vybe August 13, 2026 10:03
dolho and others added 2 commits August 13, 2026 13:05
…2133)

CodeQL `js/redos`, high, on the string-stripping regex this PR introduced.

The template-literal branch carried `\$\{[^}]*\}` alongside `[^`\\]`, and the
latter already consumes a `${...}` placeholder character by character — so an
input could be matched two ways and the alternation backtracked exponentially on
an unterminated literal.

It reads only our own source files, so it was never exploitable, but "not
reachable" is not the same as "not a defect" and the branch bought nothing:
dropping it leaves every alternative unambiguous, because `\\.` starts with a
backslash and each character class excludes one.

Re-verified both properties the guard exists for: it still catches a genuinely
undefined call (mutation), and it still tolerates an apostrophe inside a
double-quoted string — the false positive it was fixed for in this same PR.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Five confirmed defects in my own fix, three of them in the part that was
supposed to be the fix.

**The bound was still too small.** I sized it as two turn timeouts on the
assumption that one attempt costs at most `timeout_seconds`. It does not:
`execute_task` dispatches with `timeout_seconds + 10`, and the #678 reader-race
auto-retry adds a whole second HTTP call — capped at `_AUTO_RETRY_MAX_TIMEOUT_S`
(300s), NOT at the remaining budget, unlike the SUB-003 retry. So one attempt
reaches ~610s and a resume+cold pair ~1220s, against a 660s marker set once at
dispatch. The marker expired mid-turn and the client offered a Retry for billed
work — the exact failure this PR exists to stop. Now derived from the real terms,
with a test that reads `_AUTO_RETRY_MAX_TIMEOUT_S` so raising either constant
fails loudly.

**The idle give-up still offered Retry**, contradicting its own comment. It
returned `null`, `deliver` threw, and `retryable: !res?.lost` evaluated
`undefined` → true. That is the REACHABLE path: with Redis down
`mark_turn_inflight` no-ops, so `inFlightExecutionId` is null from the first
poll and a perfectly healthy, already-billed turn got a Retry after seconds. Both
give-up paths now return `lost` and render without one.

**The two clocks did not share an origin**, so the ceiling could rarely fire: the
marker starts ticking at dispatch, the client started counting after the stream
broke — which on the orphaned-marker path is minutes later. The client now
measures from the dispatch instant.

**The idle window was poll-count-based**, so the new backoff silently stretched
"~5.6s" into up to 120s of spinner before the no-answer message. Time-based now.

**Both of my new tests were tautologies** — they asserted literals declared
inside the test and imported nothing, so changing the component constant left
them green, which is precisely the drift they claimed to catch. The budget
constants moved to `portalUtils` and the tests read them; verified by mutation
that they now fail when the constant drifts.

Also corrected the ReDoS-fix comment: dropping the template-placeholder branch
did NOT "buy nothing" — it was what made a nested template literal strip as one
unit. Accepted with the reason stated, rather than claimed away.

Not fixed, stated instead: `reattach()` still grants a fresh full budget on a
turn that has already been running for an unknown time. Bounding it properly
needs the history response to carry the remaining budget; filing separately.

Related: #2133

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@dolho

dolho commented Aug 13, 2026

Copy link
Copy Markdown
Contributor Author

Pushed fixes for the review findings. Five were real, and three were in the part of this PR that was supposed to BE the fix.

The bound was still too small. I sized it as two turn timeouts on the assumption one attempt costs at most timeout_seconds. It does not: execute_task dispatches with timeout_seconds + 10, and the #678 reader-race auto-retry adds a whole second HTTP call capped at _AUTO_RETRY_MAX_TIMEOUT_S (300s) — not at the remaining budget, unlike the SUB-003 retry. One attempt reaches ~610s, a resume+cold pair ~1220s, against my 660s marker. Same failure as the one this PR fixes, one layer down. Now derived from the real terms, with a test that reads _AUTO_RETRY_MAX_TIMEOUT_S so raising either constant fails loudly.

The idle give-up still offered Retry — and it is the reachable path. With Redis down mark_turn_inflight no-ops, so inFlightExecutionId is null from the first poll and a perfectly healthy, already-billed turn got a Retry within seconds. Both give-up paths return lost now and render without one.

The two clocks did not share an origin. The marker starts ticking at dispatch; the client started counting after the stream broke, which on the orphaned-marker path is minutes later — so the ceiling could rarely fire at all. The client measures from a stamped dispatch instant now.

The idle window was poll-count-based, so my own backoff silently stretched "~5.6s" into up to 120s of spinner. Time-based now.

Both of my new tests were tautologies — literals declared inside the test, importing nothing, so changing the real constant left them green. That is exactly the drift they claimed to catch. Constants moved to portalUtils; verified by mutation that they now fail when it drifts.

Also corrected the ReDoS comment: dropping the template-placeholder branch did not "buy nothing" — it was what made a nested template literal strip as one unit. Accepted with the reason written down instead of claimed away.

Not fixed, recorded instead: reattach() still grants a fresh full budget to a turn already running for an unknown time. Bounding it needs the history response to carry the remaining budget — a behaviour change I would rather not make blind in a freeze week. Filing separately.

254 frontend tests, 211 backend across the portal suites, build clean.

@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.

Validated via /validate-pr: Closes #2133, all 4 required checks green, no secrets, no new config var, no raw palette classes.

The two-sided framing is right, and the derivation survived review better than the PR body did. Deriving the client budget from a server-sent wait_budget_seconds rather than a frontend constant is the correct ownership call, and keeping the client constant only as an older-backend fallback (pinned equal by test) is the right way to keep the fallback honest. PORTAL_ATTEMPT_CEILING_SECONDS = timeout + 10 + 300 is the part I checked hardest: the #678 reader-race retry really does stack a second call on top of attempt 1 rather than sharing its budget (unlike the SUB-003 retry), so one attempt genuinely can exceed timeout_seconds, and two attempts is the real worst case on the cold-retry path. Returning lost without a Retry when the budget runs out while the marker still claims a turn is the correct asymmetry — re-sending is the one action guaranteed to be wrong for work that was probably billed.

Note the PR body is stale against the final commit: it says both bounds are 2 × PORTAL_TURN_TIMEOUT_SECONDS + 60 (660s), but the shipped value is 2 × PORTAL_ATTEMPT_CEILING_SECONDS + 60 = 1280s. The code is the better answer; the body just didn't follow the review round. Worth knowing that an orphaned marker now disables the composer for up to ~21 min — bounded and argued, but longer than the body implies.

@vybe
vybe merged commit c467fb1 into dev Aug 13, 2026
23 checks passed
vybe pushed a commit that referenced this pull request Aug 13, 2026
No conflicts. Merged rather than left alone because this branch's CI last ran
against a `dev` from before #2147, #2148, #2150 and #2151 landed — three of
which touch the same portal files (`client_portal/service.py`,
`PortalConversation.vue`, `Portal.vue`). A green run against the older base is
not evidence the combination works, and it also leaves a stale cancelled pytest
shard on the PR.

Frontend suite on the merge result: 282 tests across 19 files.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
trinity-ability pushed a commit that referenced this pull request Aug 21, 2026
…evidence (#2320)

A Workspace turn that fails before or at start persists no assistant message and
its `finally` clears the in-flight marker on every exit path. The client learns a
turn's outcome exactly two ways — a new assistant row, or the marker still being
set — so a fast failure produced neither, and after the 6s idle give-up the
client rendered the #2133 "we've lost track of this turn — it may still finish"
copy for a turn the backend had diagnosed precisely and written to
`schedule_executions.error`. Every clause of that message was false, and Retry
was suppressed on the one path where re-sending is safe.

The `idle` flag meant to distinguish the two give-ups was returned and never
read — and worse, `deliver()`'s retryable `if (!data)` branch, which PR #2150's
body describes as preserved ("a genuine no-answer keeps its Retry"), was
unreachable: `awaitPersistedReply` has three returns and null is not one.

- `ClientPortalError` carries `category` + `retryable`, decided at the raise
  site. `_fail_unstarted_execution` is reached from the pre-start branch AND the
  generic `except Exception` (which can fire after `execute_task` returned), so
  "was this billed" is not a property of the row being written. `retryable`
  defaults False.
- Classification reads `TaskExecutionResult.error_code`, keeping the substring
  tests as the None-code fallback. AUTH/BILLING had no branch and fell through to
  the generic 502 — the subscription-limit case this was reported from.
- The verdict rides Redis beside the marker it is the terminal half of
  (`portal_turn_outcome:{session_id}`, 900s), written BEFORE the `finally`
  clears the marker: the client's give-up timer starts when the marker vanishes.
  Cleared at dispatch and on success. Surfaced as
  `PortalHistory.last_turn_outcome` — declared on the model, since the route's
  `response_model` strips undeclared keys.
- No schema change. An error message row was rejected: `_format_history_context`
  replays any non-`user` role to the agent as its own words, and
  `_persist_user_turn`'s dedupe reads `recent[-1].role == "user"`, so Retry would
  duplicate the user message and break a #2120 pin.
- The client believes a verdict only for the turn it awaits, words the two
  give-ups distinctly, and offers Retry iff nothing reached the agent.
  `reattach()`/`loadThread()` render failures too — that surface checked only for
  a reply and rendered nothing at all, so refreshing mid-turn showed less than
  staying put. `markLastUserTurnFailed` marks only the unanswered tail.

Tests: 42 backend + 25 frontend, mutation-verified. The frontend spec is the
first to exercise `PortalConversation.vue`; there was no executable coverage of
the no-Retry rule at all.

Fixes #2320
trinity-ability pushed a commit that referenced this pull request Aug 21, 2026
…evidence (#2320)

A Workspace turn that fails before or at start persists no assistant message and
its `finally` clears the in-flight marker on every exit path. The client learns a
turn's outcome exactly two ways — a new assistant row, or the marker still being
set — so a fast failure produced neither, and after the 6s idle give-up the
client rendered the #2133 "we've lost track of this turn — it may still finish"
copy for a turn the backend had diagnosed precisely and written to
`schedule_executions.error`. Every clause of that message was false, and Retry
was suppressed on the one path where re-sending is safe.

The `idle` flag meant to distinguish the two give-ups was returned and never
read — and worse, `deliver()`'s retryable `if (!data)` branch, which PR #2150's
body describes as preserved ("a genuine no-answer keeps its Retry"), was
unreachable: `awaitPersistedReply` has three returns and null is not one.

- `ClientPortalError` carries `category` + `retryable`, decided at the raise
  site. `_fail_unstarted_execution` is reached from the pre-start branch AND the
  generic `except Exception` (which can fire after `execute_task` returned), so
  "was this billed" is not a property of the row being written. `retryable`
  defaults False.
- Classification reads `TaskExecutionResult.error_code`, keeping the substring
  tests as the None-code fallback. AUTH/BILLING had no branch and fell through to
  the generic 502 — the subscription-limit case this was reported from.
- The verdict rides Redis beside the marker it is the terminal half of
  (`portal_turn_outcome:{session_id}`, 900s), written BEFORE the `finally`
  clears the marker: the client's give-up timer starts when the marker vanishes.
  Cleared at dispatch and on success. Surfaced as
  `PortalHistory.last_turn_outcome` — declared on the model, since the route's
  `response_model` strips undeclared keys.
- No schema change. An error message row was rejected: `_format_history_context`
  replays any non-`user` role to the agent as its own words, and
  `_persist_user_turn`'s dedupe reads `recent[-1].role == "user"`, so Retry would
  duplicate the user message and break a #2120 pin.
- The client believes a verdict only for the turn it awaits, words the two
  give-ups distinctly, and offers Retry iff nothing reached the agent.
  `reattach()`/`loadThread()` render failures too — that surface checked only for
  a reply and rendered nothing at all, so refreshing mid-turn showed less than
  staying put. `markLastUserTurnFailed` marks only the unanswered tail.

Tests: 42 backend + 25 frontend, mutation-verified. The frontend spec is the
first to exercise `PortalConversation.vue`; there was no executable coverage of
the no-Retry rule at all.

Fixes #2320
trinity-ability pushed a commit that referenced this pull request Aug 21, 2026
…evidence (#2320)

A Workspace turn that fails before or at start persists no assistant message and
its `finally` clears the in-flight marker on every exit path. The client learns a
turn's outcome exactly two ways — a new assistant row, or the marker still being
set — so a fast failure produced neither, and after the 6s idle give-up the
client rendered the #2133 "we've lost track of this turn — it may still finish"
copy for a turn the backend had diagnosed precisely and written to
`schedule_executions.error`. Every clause of that message was false, and Retry
was suppressed on the one path where re-sending is safe.

The `idle` flag meant to distinguish the two give-ups was returned and never
read — and worse, `deliver()`'s retryable `if (!data)` branch, which PR #2150's
body describes as preserved ("a genuine no-answer keeps its Retry"), was
unreachable: `awaitPersistedReply` has three returns and null is not one.

- `ClientPortalError` carries `category` + `retryable`, decided at the raise
  site. `_fail_unstarted_execution` is reached from the pre-start branch AND the
  generic `except Exception` (which can fire after `execute_task` returned), so
  "was this billed" is not a property of the row being written. `retryable`
  defaults False.
- Classification reads `TaskExecutionResult.error_code`, keeping the substring
  tests as the None-code fallback. AUTH/BILLING had no branch and fell through to
  the generic 502 — the subscription-limit case this was reported from.
- The verdict rides Redis beside the marker it is the terminal half of
  (`portal_turn_outcome:{session_id}`, 900s), written BEFORE the `finally`
  clears the marker: the client's give-up timer starts when the marker vanishes.
  Cleared at dispatch and on success. Surfaced as
  `PortalHistory.last_turn_outcome` — declared on the model, since the route's
  `response_model` strips undeclared keys.
- No schema change. An error message row was rejected: `_format_history_context`
  replays any non-`user` role to the agent as its own words, and
  `_persist_user_turn`'s dedupe reads `recent[-1].role == "user"`, so Retry would
  duplicate the user message and break a #2120 pin.
- The client believes a verdict only for the turn it awaits, words the two
  give-ups distinctly, and offers Retry iff nothing reached the agent.
  `reattach()`/`loadThread()` render failures too — that surface checked only for
  a reply and rendered nothing at all, so refreshing mid-turn showed less than
  staying put. `markLastUserTurnFailed` marks only the unanswered tail.

Tests: 42 backend + 25 frontend, mutation-verified. The frontend spec is the
first to exercise `PortalConversation.vue`; there was no executable coverage of
the no-Retry rule at all.

Fixes #2320
vybe pushed a commit that referenced this pull request Aug 21, 2026
…evidence (#2320) (#2359)

A Workspace turn that fails before or at start persists no assistant message and
its `finally` clears the in-flight marker on every exit path. The client learns a
turn's outcome exactly two ways — a new assistant row, or the marker still being
set — so a fast failure produced neither, and after the 6s idle give-up the
client rendered the #2133 "we've lost track of this turn — it may still finish"
copy for a turn the backend had diagnosed precisely and written to
`schedule_executions.error`. Every clause of that message was false, and Retry
was suppressed on the one path where re-sending is safe.

The `idle` flag meant to distinguish the two give-ups was returned and never
read — and worse, `deliver()`'s retryable `if (!data)` branch, which PR #2150's
body describes as preserved ("a genuine no-answer keeps its Retry"), was
unreachable: `awaitPersistedReply` has three returns and null is not one.

- `ClientPortalError` carries `category` + `retryable`, decided at the raise
  site. `_fail_unstarted_execution` is reached from the pre-start branch AND the
  generic `except Exception` (which can fire after `execute_task` returned), so
  "was this billed" is not a property of the row being written. `retryable`
  defaults False.
- Classification reads `TaskExecutionResult.error_code`, keeping the substring
  tests as the None-code fallback. AUTH/BILLING had no branch and fell through to
  the generic 502 — the subscription-limit case this was reported from.
- The verdict rides Redis beside the marker it is the terminal half of
  (`portal_turn_outcome:{session_id}`, 900s), written BEFORE the `finally`
  clears the marker: the client's give-up timer starts when the marker vanishes.
  Cleared at dispatch and on success. Surfaced as
  `PortalHistory.last_turn_outcome` — declared on the model, since the route's
  `response_model` strips undeclared keys.
- No schema change. An error message row was rejected: `_format_history_context`
  replays any non-`user` role to the agent as its own words, and
  `_persist_user_turn`'s dedupe reads `recent[-1].role == "user"`, so Retry would
  duplicate the user message and break a #2120 pin.
- The client believes a verdict only for the turn it awaits, words the two
  give-ups distinctly, and offers Retry iff nothing reached the agent.
  `reattach()`/`loadThread()` render failures too — that surface checked only for
  a reply and rendered nothing at all, so refreshing mid-turn showed less than
  staying put. `markLastUserTurnFailed` marks only the unanswered tail.

Tests: 42 backend + 25 frontend, mutation-verified. The frontend spec is the
first to exercise `PortalConversation.vue`; there was no executable coverage of
the no-Retry rule at all.

Fixes #2320
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