Repository navigation
fix(sessions): avoid turn errors when write receipts overtake reads - #169174
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review in progressClawSweeper is reviewing this revision. This supersedes any previous blocked status. |
|
Codex review: needs maintainer review before merge. What this changesThis PR recovers session reads overtaken by committed receipts using the current replica and one bounded worker-read retry. Example: A read of agent:main:actor-replica overlaps a receipt changing updatedAt from 1 to 2 and label from before to after.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this PR addresses a reported session-read failure still present on main, and source review found no actionable correctness or security defect. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherThe session actor connects turn-processing callers to the existing SQLite worker owner, installs committed receipts in a shared replica, and returns authorized session snapshots. flowchart TD
A[Turn processing caller] --> B[Session actor]
B --> C[Physical writer FIFO]
C --> D[SQLite worker]
D --> E[Committed replica]
E --> B
B --> F[Caller authorization]
F --> G[Returned session snapshot]
Technical reviewBest possible solution: Recover through the existing receipt-maintained replica while retaining bounded retries and caller-owned disclosure authorization. Do we have a high-confidence way to reproduce the issue? Main deterministically rejects a read whose installation or disclosure snapshot is superseded; the body reports live occurrences and base-failing regressions, but this read-only review executed no target code. Is this the best way to solve the issue? The shared actor is the appropriate repair boundary, and reacquiring its existing committed replica avoids another state owner or mutation replay. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 23ad242958a4. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +10, Tests +83, Docs +3. Total +96 across 4 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed October 11, 2026, 11:18 AM ET / 15:18 UTC (Revision 2). |
…penclaw#169174) Use the receipt-maintained replica when a committed write overtakes a session actor read. Retry the existing worker read once only when the replica is still empty, and reauthorize a replacement before disclosure. Preserve live authority checks and bounded failure. Regression coverage exercises newer receipts during worker reads and disclosure, plus one-read recovery and retry exhaustion.
What Problem This Solves
Fixes session reads failing with “Session actor changed before its read could publish” when a committed write receipt overtakes a worker read. A live soak observed this twice in roughly 108 cycles, including a correct reply reported by
agent.waitas an error.User Impact
An overtaken read returns the newer committed session snapshot and can complete normally. Caller authority still controls disclosure; schemas, stored data, update behavior, and SDK contracts are unchanged.
Why This Change Was Made
The Gateway owns both the actor and its receipt-maintained replica. A rejected stale read installation now reacquires that replica. If it is empty, the same command retries the existing worker read once, then fails if no snapshot can be installed. A snapshot superseded before disclosure is reacquired once and authorized again. No new generation, fence, or worker operation is introduced.
Removed failure checks and accepted edges:
Evidence
pnpm test <file> --maxWorkers=1): actor 34.25 s (4.165 s test execution); replica 43.52 s (4.421 s test execution). Compilation/import dominates. Hosted CI cancelled the test matrix after an unrelated UI failure, so current-head per-file CI seconds are unavailable.check:changedpassed formatting, core typing, all 28 test typecheck graphs, and its early guards, then stopped on one inherited full-tree Knip unused export. Production/script Knip scans passed. Type-aware oxlint and every skipped source guard were run explicitly and passed; Madge, export collisions, and T1/dialect ratchets passed.No update cell or SDK API diff is applicable.
SQL measurement
The unchanged shared harness ran three alternating base/candidate pairs plus the one permitted ambiguity pair on the same Testbox, comparing base
91a860e080610d5f1d7ac833b698effdf9e0ef4bwith heade6c8c5b1d1dde990a4c0e9025e5df807e7bc9d60. Counts include all threads and split multi-statement execution into statements. Warmed figures are per-turn averages summarized across runs as median [min–max].Actor-read first-turn work is exactly 4 statements / 4 requests in every valid run. Whole-workload actor-read medians remain 57 statements / 57 requests on both sides. Warmed actor-read medians are 4.4 / 4.4 versus 4.35 / 4.35; each read still executes one statement per request. Other warmed actor operations are unchanged: acceptInput 16/2, adoptRun 4/1, appendTranscriptEvent 23/2, completeTurn 6/1, deliverySettled 7/2 (statements/requests). The small aggregate warmed decrease is timing variance, not a claimed optimization.
The extra pair was required because first-turn statements increased. Four-pair first-turn medians are 1035.5→1111.5 statements and 200.5→208.5 requests; whole-workload medians are 9765.5→9782 statements (+0.17%) and 1711.5→1712.5 requests (+0.06%). The extra pair alone is 9774→9794 statements and 1709→1713 requests. The equal-or-lower whole-workload shortcut therefore does not pass; this is not reported as an aggregate SQL reduction.
A raw SQL/request-stack scan across all eight valid workloads found zero native SQL under
session-actor.tsand zero SQL or worker sends under either the existing authorization call or the added replacement-authorization call. Every actor-read send comes from the existing worker operation; whole-workload actor-read medians are identical and the extra pair falls from 58 to 57 reads. Actor mutation counts are identical in every workload: 26 acceptInput, 13 adoptRun, 41 appendTranscriptEvent, 13 completeTurn, 26 deliverySettled, and 1 appendToolResult. The changed ordinary path adds no SQL/request work.The extra pair's positive deltas occur in unchanged owners: model context +7 statements/+1 request, session corpus inventory +13/0, session entry +5/+1, row backfill +3/+1, tombstones +2/+1, prune +6/+1, transcript statistics +2/+1, and patch +14/0; offsets include lifecycle projection −13 statements and entry list −11. First-turn variation includes existing session-node/participant TEMP-trigger setup and schema inspection moving between phases; identical fingerprints already exist in the baseline. This residual is recorded as unchanged-owner timing/setup variance under the relaxed landing decision, supported by direct changed-path inspection, rather than waived as a T1 move or described as numerical non-increase.
All eight valid workloads completed. SQL diagnostics recorded 3 base / 5 candidate
database is lockedattempts in unchanged post-ready startup maintenance and idle-close state owners; none came from the actor and warmed turns had zero SQL errors. First/warmed median duration ratios were 1.045/0.991, within the 1.5 comparison limit.One attempted extra baseline failed before the workload because remote source synchronization invalidated its task-owned Git metadata. Its unpaired candidate is excluded. The baseline metadata was repaired, exact source bytes verified, and the valid extra M/C pair completed. No additional pairs were run.
CI disposition
The exact-head CI run 38149421297 stopped after UI job 114499862139:
chat-panel-layout.e2e.test.tstimed out waiting for a hidden 560×312 terminal canvas to become visible (1 failed, 91 passed). Its mock Gateway replaces WebSocket and never executes the session actor. The UI test, mock helpers, terminal implementation, panel layout/CSS, and workflow are unchanged by this PR.Recent scheduled main job 114494370803, head
6233a19ea75bbcd079ec4dbe4660bfef9b9321ed, shows the same hidden-terminal-canvas timeout in sibling terminal-repaint/readiness tests, rather than the identical test. The CI monitor cancelled remaining jobs after the UI failure. This is recorded as unrelated inherited UI breakage, not passing CI; focused owner proof and all required static checks remain merge gates.Landing uses the explicitly authorized head-pinned REST squash fallback after native review artifact initialization twice refused a moving tooling-root dependency mismatch. The first exact-head merge request was rejected with HTTP 405 after main changed the actor layout; it was confirmed unmerged before recovery.
Main integration
Merged main
5bd4f88535c66197b6d07442b82f7f68d94be6fainto this branch, producinged22f47330558ac77a100d15abfb85643971108c. Main extracted the durable implementation intosession-actor-sqlite.ts; conflict resolution preserves its wrapper and moves the same bounded recovery into that existing SQLite executor. The final diff remains four files, with unchanged production/test/documentation LOC. The measurement and callback-stack evidence above belongs to the pre-integration head and original file layout. No SQL statement, request, or recovery semantics changed in this port; the campaign's conflict-only measurement reuse rule applies. Post-integration Testbox proof passed all 81 tests across 10 actor/replica/kernel/worker/diagnostics/memory suites (28.83 s Vitest, 30.70 s test wrapper). Formatting and changed-file type-aware oxlint passed. Core typecheck (45.9 s), the session test type graph (44.2 s), Madge (12.6 s), export collisions, source guards, and T1/dialect ratchets all passed. Exact focused-command wall time was 31.085 s.Full-tree Knip reports the same seven findings on final head and integrated baseline
5bd4f88535c66197b6d07442b82f7f68d94be6fa: six unused exports inextensions/telegram/src/bot-native-commands.runtime.ts(ensureConfiguredBindingRouteReady,getAgentScopedMediaLocalRoots,getSessionEntryAsync,recordDeliveredCommandExchange,resolveChunkMode,resolveStorePath) and the subagent export noted below. The exact rule/file/export match was reproduced by running the baseline scan; no PR-caused static failure remains.Final-head CI run 38153491821 has green required CI, dependency-review, and security-sensitive-review gates. The earlier unrelated UI failure is historical evidence; the final merge does not require a CI-failure override.
The inherited static failure is
loadSubagentMaintenanceCandidatesInDatabaseinsrc/agents/subagents/registry/subagent-registry.store.sqlite.ts. An actual full-tree Knip scan on current-mainea576bd11d8c304c1a8cc53823b0081d65cee0ccreproduced that same rule/file/export; the file is byte-identical to the candidate. No failing static rule is introduced by this PR.