Repository navigation
refactor(sessions): move active accounting and companion reads to workers - #163045
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Codex review: needs maintainer review before merge. Reviewed October 1, 2026, 6:41 PM ET / 22:41 UTC (Revision 2). ClawSweeper reviewWhat this changesThe PR moves transcript accounting for memory flush and compaction, plus bounded side-chat context reads, into the existing background history worker. Merge readiness✅ Ready for maintainer review This migration remains useful: current main still performs the targeted reads synchronously, and neither related PR replaces this work. No actionable introduced defect or unresolved merge concern was found. Priority: P2 Review scores
Verification
How this fits togetherSession transcripts supply usage, size, and taint facts for agent maintenance and recent conversation context for side chat. The history worker reads SQLite snapshots and returns prepared results to Gateway callers. flowchart TD
A[Stored session transcript] --> B[History worker]
C[Maintenance or side-chat request] --> B
B --> D[Admitted SQLite snapshot]
D --> E[Accounting facts or bounded context]
E --> F[Caller authority and snapshot checks]
F --> G[Compaction, memory flush, or side chat]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +123, Tests +218, Other -1. Total +340 across 24 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Keep durable accounting and companion reads with the existing history worker, preserving native Incognito ownership and caller-side authority checks. Do we have a high-confidence way to reproduce the issue? Not applicable to a reported functional bug; current-main source directly establishes synchronous reads at the targeted call sites. No runtime execution was performed during this review. Is this the best way to solve the issue? Yes. Extending the admitted history worker and reusing projection kernels preserves the existing storage boundary without adding configuration or a parallel service. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 166114b80d22. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
|
Merged via squash.
|
Extract active-event visitation and bounded-tail selection into a read-only module. Callers retain the same admitted snapshots; host-facing APIs retain projection acquisition and reconciliation. Preserve SQL, byte budgets, error priority, and the public accessor's page types. Remove the obsolete assertion-baseline entry after documenting the moved cast. Fix the history import backedges introduced by #163045.
…kers (openclaw#163045) * refactor(sessions): read active accounting in history workers * refactor(sessions): narrow transcript accounting records * test(sessions): isolate accounting authority checks * test(sessions): seed memory flush source fixtures * test(sessions): spy on the entry writer boundary
Extract active-event visitation and bounded-tail selection into a read-only module. Callers retain the same admitted snapshots; host-facing APIs retain projection acquisition and reconciliation. Preserve SQL, byte budgets, error priority, and the public accessor's page types. Remove the obsolete assertion-baseline entry after documenting the moved cast. Fix the history import backedges introduced by openclaw#163045.
…elegate-claims test Upstream (openclaw#163045/openclaw#163054) moved artifacts.ts session resolution to prepareSessionMutationFacts; our test still mocked session-utils, so the handler never reached the transcript visitor. Use the same artifactFixtureSessionFacts mock as upstream's artifacts.test.ts. Refs #1408 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fq5EX9ESA3CG9cuZxVoKAK
Worker-backed companion context preparation introduced by #163045 can outlast the fixture's one-second polling window. Await the model-start signal and reject an ask that settles before reaching it. Keep cancellation, generation, late-answer, and exchange cleanup assertions unchanged. The original case failed three consecutive runs. The corrected case passed three runs, and the full lifecycle and companion sibling suites passed.
Worker-backed companion context preparation introduced by openclaw#163045 can outlast the fixture's one-second polling window. Await the model-start signal and reject an ask that settles before reaching it. Keep cancellation, generation, late-answer, and exchange cleanup assertions unchanged. The original case failed three consecutive runs. The corrected case passed three runs, and the full lifecycle and companion sibling suites passed.
…removed Main's test lifecycle now fails a file whose agent or state database outlives its fixture directory, and openclaw#163045 moved the active-stats read this branch's snapshot test used into a test-support module. After the merge that left three of the branch's own suites red: - transcript-grounding.test.ts and session-accessor.sqlite-conversation-snapshot.test.ts passed their cases and then failed teardown with "Agent database close failed" (ENOENT on the removed state/openclaw.sqlite). Both now await the agent and state database closes in afterEach, as session-accessor.sqlite-active-events.test.ts does. - The snapshot test called readSessionTranscriptActiveStats, which no longer exists; it reads the same count through readActiveTranscriptStats. - embedded-agent-subscribe.tools.media.test.ts closed its databases synchronously. Its case stores now sit under one suite root from useSessionStoreTempDirs, drained once before removal (openclaw#161871). No assertion changes.
What Problem This Solves
Memory-flush and compaction accounting read active transcript statistics and usage/taint facts synchronously on the Gateway thread. Side chat also reads each bounded context page and its final snapshot fence synchronously.
Why This Change Was Made
Run active accounting and bounded-tail reads through the existing session history worker. The accounting kernel returns byte/count, provider usage, and turn-taint facts from one admitted projection snapshot. Callers await prepared facts and recheck live authority before effects. Companion context retains its newest-contiguous suffix and generation/leaf/indexed-sequence fence.
Remove the obsolete
readSessionTranscriptActiveStatsandwithRecentSessionTranscriptActiveEventsscope exports. Existing storage tests now invoke the retained projection kernels through their test support.User Impact
This completes the active accounting cohort and bounded companion reads from S07. Whole-transcript point/batch statistics and the completion-input predicate remain separate cohorts.
The migrated durable reads execute in the history worker. This does not claim the entire turn or companion entry-metadata lookup is free of host SQLite.
session-accessor.sqlite-active-events.ts6 → 6;session-accessor.sqlite-reset-window.ts10 → 10. Other runtime and native callers keep these shared files mixed; no inventory reclassification is justified.session-accessor.sqlite-transcript-stats.ts.git diff --numstat 84dc4c73ceee27d8067570fc1cdc6e2bc5dbe272...HEAD. The merge-base comparison isolates these 24 lane files from the required upstream merge; the original pinned-base diff also contains 851 upstream file changes.Evidence
Validated head:
a6d88aa79ab58df77e0d2bfe0ff8f2376ae91a18. All changed-file SHA-256 checks passed on Testbox before execution. Base and head used separate detached checkouts, prepared withnode scripts/worktree-setup.mjs gateway, on the same Linux Blacksmith Testbox.node scripts/check-changed.mjs— passed: touched typecheck/lint lanes, guards, dead exports, and runtime import cycles. Final test-only refinements also passed messaging tsgo and scoped lint.pnpm check:database-worker-ratchet --base 98e86147b19c120d800dab559897276a582446da— passed, no T1 growth.pnpm check:madge-import-cycles— passed, 0 cycles.node scripts/database-worker-inventory.mjs --jsonat the original pinned base and head — filtered owner counts reported above; classification unchanged.node --import ./scripts/tsx.mjs scripts/build-all.mts qaRuntime— passed locally (5m24.1s); both remote checkout preparations also passed.git diff --check— passed.84dc4c73ceee27d8067570fc1cdc6e2bc5dbe272, followed by fresh reviews of the final fixture/import changes — scoped-clean through P2; no accepted actionable findings remain.The worker boundary proof in
src/gateway/session-transcript-readers.test.tspassed all 16 tests locally (988.88s command wall under host load). Its durable accounting case rejects synchronous SQLite primitives on the calling thread. The delayed accounting tests retire caller authority while the worker result is pending and assert no compaction, flush, latch persistence, or accounting update occurs afterward; worker rejection remains conservative without a native retry.All nine suites below passed on Blacksmith Testbox
tbx_01m3wre1c0c4g9nq942c2b88a1usingpnpm test <file> --maxWorkers=1, with/usr/bin/time -pmeasuring each command independently. Total: 185 tests passed. No real timers, sleeps, or polling were added to tests. Per-PR CI test seconds are not yet available.src/config/sessions/session-accessor.sqlite-active-events.test.tssrc/config/sessions/session-accessor.sqlite-bounded-context.test.tssrc/config/sessions/session-accessor.sqlite-byte-size.test.tssrc/config/sessions/session-accessor.sqlite-history-events.legacy.test.tssrc/config/sessions/session-accessor.sqlite-transcript-store.test.tssrc/config/sessions/session-transcript-context-eligibility.test.tssrc/auto-reply/reply/agent-runner-memory.test.tssrc/auto-reply/reply/agent-runner-memory.accounting.test.tssrc/gateway/session-companion-context.test.tsRemote invocation used
node scripts/crabbox-wrapper.mjs run --keep --timing-json -- bash -c <comparison-and-suite-script>. Testbox run: native provider result exit=0 / succeeded. The provider emitted an external portal-sync timeout after successful execution; its command result and timing JSON are the proof authority. Lease stopped after proof.Load-induced local timeouts
The existing 100k-message case hit its unchanged 60,000ms limit twice on the overloaded local host: full active-events command wall 499.78s (16 other cases passed), isolated command wall 273.54s. Two separate memory fixtures also initially failed because they relied on synchronous reads implicitly creating empty storage; the fixtures now seed their source explicitly, and the complete 59-case memory suite passed remotely.
Same stress command, same Testbox,
--maxWorkers=1, with no timeout increase:84dc4c73ceee27d8067570fc1cdc6e2bc5dbe272a6d88aa79ab58df77e0d2bfe0ff8f2376ae91a18Head/base wall ratio: 0.850, approximately 15% faster, below the coordinator's 1.25 regression threshold. The full head active-events suite subsequently passed with the stress body at 3.773s. This identifies the local timeouts as load-induced. Accounting still aggregates inside the worker and returns bounded facts; no large event batch was moved onto the host.
Compatibility retained
Process-held Incognito databases retain their existing native owner because another worker cannot reopen them by path.
openclaw/plugin-sdk/session-store-runtimeretains the publicreadTranscriptStatsSynccontract.readRecentSessionTranscriptActiveEventsstill serves bootstrap context;readSessionTranscriptBoundedMessageTailPageand the raw statistics readers remain in the deferred cohorts below. These are remaining migration debt, not new compatibility shims. No new synchronous compatibility export was added.Update behavior
No schema, persisted state format, retention, durability, configuration, or permission changes. Doctor and updater behavior are unchanged.
Overlapping open PRs
runMemoryFlushIfNeededandrunSessionCompactionIfNeeded; this change only replaces transcript fact preparation and adds post-wait authority checks.runMemoryFlushIfNeeded; those workspace expressions are unchanged here.Remaining S07 cohorts