Skip to content

fix(sessions): fence only prepared sessions after an uncertain category write - #161126

Closed
miorbnli wants to merge 1 commit into
openclaw:mainfrom
miorbnli:fix/narrow-uncertain-category-fence
Closed

miorbnli wants to merge 1 commit into
openclaw:mainfrom
miorbnli:fix/narrow-uncertain-category-fence

Conversation

@miorbnli

@miorbnli miorbnli commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Closes #160609

What Problem This Solves

When a committed session group-category write loses its worker acknowledgement (uncertain outcome), the uncertain-outcome fence invalidated every session row in the physical store ({ all: true, scope: { storePath }, factsInvalidated: true }). A concurrent, unrelated session's in-flight exact-read reply was discarded and re-read from the worker — redundant work on every lost category ack, exactly as reported in #160609. The category transaction can only change the rows the prepare step selected (applySessionGroupCategoryMutation re-validates and rewrites exactly the prepared rows), so the store-wide fence over-covers by construction.

Why This Change Was Made

The fence's authority and no-replay guarantees (#155620) are preserved; only its breadth is narrowed to the mutation's real blast radius:

  • runSessionCollaborationWrite's prepare hook may now return the affected session keys. updateSessionGroupCategoriesInWorker returns its prepared keys (already captured in its closure).
  • The uncertain-outcome catch for category.apply now emits one per-key { sessionKey, storePath, factsInvalidated: true } event for the prepared rows, plus discardCommittedSessionEntryCache exactly as before (the settled-worker cache cannot publish a trustworthy field patch). An empty prepared plan emits nothing (nothing was written); a prepare that never ran keeps the old conservative store-wide fence, because the write scope is then unknown.
  • Non-category commands keep their existing per-session fence.

The uncertainty semantics are unchanged: the affected keys stay fenced (their cached facts are dropped and their in-flight reads still reconcile through the projection's read worker), and no write is replayed.

User Impact

Gateway hosts that lose a category-update acknowledgement (worker restart, transport hiccup at the settled boundary) no longer invalidate the in-flight reads of every unrelated session in the same store; only the sessions the write could have touched re-read. Reported frequency is unestablished (see the issue), but the fix removes an entire class of redundant worker reads on shared stores.

Evidence

Red-green regression (new case in src/gateway/session-row-projection.worker-read.test.ts, instrumented worker replies counting every read, holding only the first):

  • Pre-fix main behavior: the store-wide fence discarded the held unrelated reply — the unrelated session key was read 2 times (expected [ …(2) ] to have a length of 1 but got 2).
  • With this fix: the held reply survives; the unrelated key is read exactly once, while the fenced target reconciles to its committed (removed) category through a fresh read. Full file: 19/19 pass.

Runtime probe (same instrumented commit-then-lose-the-reply scenario, verbatim):

===== BEFORE (upstream/main behavior) =====
PROBE uncertain category.apply emitted: [
 "STORE-WIDE all:true (every session in the store fenced)"
]

===== AFTER (fix) =====
PROBE uncertain category.apply emitted: [
 {
  "agentId": "main",
  "storePath": "/tmp/oc-vt-NNWDBO/openclaw-test-state-minimal-bOtvei/home/.openclaw/agents/main/agent/openclaw-agent.sqlite",
  "sessionKey": "agent:main:probe-uncertain",
  "factsInvalidated": true
 }

Sibling suites: session-sharing-store.worker.test.ts 13/13 (its category case's pinned store-wide expectation updated to the per-key event — same keys, same factsInvalidated, same cache discard), session-membership-projection.test.ts + session-sharing-preparation.test.ts 33/33.

Gates: pnpm tsgo exit 0, pnpm tsgo:test exit 0, run-oxlint 0/0 on changed files, oxfmt clean, line-cap and assertion-safety ratchets OK against upstream/main (54b1b1b), git diff --check clean. Node v26.5.0 on Linux x64.

Not tested: a live lost-acknowledgement produced by a real worker crash rather than the injected outcome-unknown at the settled boundary (the issue's own fixture uses the same injection); production occurrence frequency. The membership projection's per-key invalidation path (store.facts.delete + dirty.add) is covered by its existing suite, not by a new dedicated test here.


Authored with AI assistance (ZCode agent session); the investigation, fix, tests, and evidence above were produced and verified in that session per the current contribution rules.

@clawsweeper

clawsweeper Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S labels Sep 29, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 29, 2026
@clawsweeper

clawsweeper Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 29, 2026, 6:01 AM ET / 10:01 UTC.

ClawSweeper review

What this changes

The branch limits uncertain session category-write invalidation to the sessions selected during worker preparation and adds regression coverage for an unrelated in-flight read.

Regression provenance

Possible regression — probable (reviewed change; reproduction). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 2 items remain

Current main still uses the store-wide uncertain-write fence reported in the linked issue. This PR has a coherent, narrowly scoped fix, and the prepared keys match the worker transaction’s possible write set. No blocking correctness defect was found.

Priority: P2
Reviewed head: 3ae4ca6c6f719fe58524c9c734655137c41cf681

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch is focused and supported by a production-boundary fault scenario; the remaining gap is the repository-required test-cost measurement.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The contributor reports a before/after injected lost-acknowledgement run through the category worker and Gateway projection: the unrelated session read falls from two worker reads to one while the affected session reconciles. The committed regression exercises that production boundary with an injected reply failure; no stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The contributor reports a before/after injected lost-acknowledgement run through the category worker and Gateway projection: the unrelated session read falls from two worker reads to one while the affected session reconciles. The committed regression exercises that production boundary with an injected reply failure; no stored-data contract changes.
Evidence reviewed 7 items Introduced change: The pinned merge-base-to-head diff replaces the category write’s store-wide uncertainty event with per-key events from the completed prepare step.
Current main behavior: The fetched main revision still emits a store-wide invalidation when a category apply result is uncertain, so the central problem remains open there.
Write-set boundary: The worker returns keys from its prepared category plan and applies that same plan in the write transaction; the apply helper iterates only those prepared rows.
Findings None None.
Security None None.

How this fits together

The Gateway keeps session rows ready for list and detail requests while a SQLite worker owns category writes. After an uncertain write result, change notifications tell the Gateway which cached rows need a fresh worker read.

flowchart LR
  A[Category update request] --> B[Prepare session keys]
  B --> C[SQLite worker write]
  C --> D{Result certain?}
  D -->|Yes| E[Publish category facts]
  D -->|No| F[Fence prepared sessions]
  F --> G[Refresh affected rows]
Loading

Before merge

  • Resolve merge risk (P1) - The added Gateway regression has no recorded before/after wall-time benchmark or measured single-worker test cost, leaving its required per-PR CI cost unverified.
  • Complete next step (P2) - Add the Gateway test file’s before/after wall-time benchmark and the new test’s measured single-worker cost to the PR body before merge.
Agent review details

Security

None.

PR surface

Source +21, Tests +113. Total +134 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 2 32 11 +21
Tests 2 126 13 +113
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 158 24 +134

Review metrics

Metric Value Why it matters
Uncertainty scope store-wide to prepared session keys This is the behavior change that avoids rereading unrelated sessions after a lost acknowledgement.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #160609
Summary: The open issue describes the same lost category-acknowledgement read amplification that this PR targets.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep the worker’s prepared plan as the single source of affected keys, reconcile only those rows after an uncertain result, and retain the current no-replay behavior.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep the worker’s prepared plan as the single source of affected keys, reconcile only those rows after an uncertain result, and retain the current no-replay behavior.

Do we have a high-confidence way to reproduce the issue?

Yes, with high confidence from source and the supplied regression: current main broadcasts a store-wide fence, and the controlled lost-acknowledgement case observes a second read of an unrelated session. I did not execute it in this read-only review.

Is this the best way to solve the issue?

Yes. The worker applies exactly its prepared category rows, so using those keys for uncertain-result reconciliation is a narrow repair that preserves the existing no-replay path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 0c8e56cf9859.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The linked issue demonstrates redundant worker reads after an uncommon uncertain category write, with limited established user impact.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The contributor reports a before/after injected lost-acknowledgement run through the category worker and Gateway projection: the unrelated session read falls from two worker reads to one while the affected session reconciles. The committed regression exercises that production boundary with an injected reply failure; no stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The contributor reports a before/after injected lost-acknowledgement run through the category worker and Gateway projection: the unrelated session read falls from two worker reads to one while the affected session reconciles. The committed regression exercises that production boundary with an injected reply failure; no stored-data contract changes.

Evidence

What I checked:

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • Vincent Koc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Record before/after wall time for the affected Gateway test file and the new test’s single-worker cost in the PR body.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@miorbnli

Copy link
Copy Markdown
Contributor Author

CI failure attribution on head 3ae4ca6c6f (run 36551847746, created 2026-09-29T09:51Z): every failing checks-node-changed-compact-large shard fails in files outside this diff — board-store.parity.test.ts, subagent-control.publication.test.ts, cleanup-service.applied-summary/fix-missing.test.ts, legacy-main-session-migration.node-handoff.test.ts, server.catalog-startup.test.ts, server.incognito-lifetime.test.ts, session-cost-usage.archive-identity.test.ts. All sampled files pass locally on the exact head (e.g. board-store.parity.test.ts 21/21, cleanup-service.applied-summary + legacy-main-session-migration.node-handoff + server.catalog-startup green). main CI is green on newer commits. The same day's runs on four sibling PRs show the same scattered-shard pattern, consistent with the known runner-load flake family; the diff itself (session-store uncertain-fence narrowing) re-ran its full focused suites green before push. A maintainer rerun of the failed shards should clear these.

@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Thanks @miorbnli for investigating this and adding the focused regression. This is already fixed on main by #160656 (dad8de7).

I verified that commit is an ancestor of main at 2b0a8fe and checked the current path: category.prepare supplies publicationKeys, category.apply writes only those prepared keys, and unresolved settlement emits per-key invalidations through retainSessionEntryWorkerPublication. A surviving native commit receipt now also settles the write after ordinary reply loss. The existing worker-read regression checks that the unrelated session is read once, the changed category is current, and the mutation is not replayed. No additional change remains to lift from this PR. Closing as already fixed; thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Lost category update acknowledgements invalidate unrelated session reads

2 participants