Skip to content

refactor(sessions): move active accounting and companion reads to workers - #163045

Merged
steipete merged 6 commits into
mainfrom
dbasync/s07
Oct 1, 2026
Merged

steipete merged 6 commits into
mainfrom
dbasync/s07

Conversation

@steipete

@steipete steipete commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

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 readSessionTranscriptActiveStats and withRecentSessionTranscriptActiveEvents scope 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.

  • T1 sites: session-accessor.sqlite-active-events.ts 6 → 6; session-accessor.sqlite-reset-window.ts 10 → 10. Other runtime and native callers keep these shared files mixed; no inventory reclassification is justified.
  • Whole-transcript statistics remain 3 T1 sites in session-accessor.sqlite-transcript-stats.ts.
  • Production LOC: +487 / −364 = +123 net (tests, test support, and docs excluded; approved ceiling +300), measured with 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 with node 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 --json at 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.
  • Codex autoreview: branch review against merge base 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.ts passed 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_01m3wre1c0c4g9nq942c2b88a1 using pnpm test <file> --maxWorkers=1, with /usr/bin/time -p measuring 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.

File Passed Command wall
src/config/sessions/session-accessor.sqlite-active-events.test.ts 17 31.90s
src/config/sessions/session-accessor.sqlite-bounded-context.test.ts 21 31.79s
src/config/sessions/session-accessor.sqlite-byte-size.test.ts 20 22.09s
src/config/sessions/session-accessor.sqlite-history-events.legacy.test.ts 12 18.75s
src/config/sessions/session-accessor.sqlite-transcript-store.test.ts 25 25.35s
src/config/sessions/session-transcript-context-eligibility.test.ts 8 20.79s
src/auto-reply/reply/agent-runner-memory.test.ts 59 58.19s
src/auto-reply/reply/agent-runner-memory.accounting.test.ts 3 30.47s
src/gateway/session-companion-context.test.ts 20 46.89s

Remote 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:

pnpm test src/config/sessions/session-accessor.sqlite-active-events.test.ts --maxWorkers=1 --testNamePattern='keeps 100k-message reads bounded'
Revision Command wall Stress test body Result
Base 84dc4c73ceee27d8067570fc1cdc6e2bc5dbe272 30.94s 4.603s Passed
Head a6d88aa79ab58df77e0d2bfe0ff8f2376ae91a18 26.30s 4.071s Passed

Head/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-runtime retains the public readTranscriptStatsSync contract. readRecentSessionTranscriptActiveEvents still serves bootstrap context; readSessionTranscriptBoundedMessageTailPage and 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

Remaining S07 cohorts

  • Raw point statistics and manual-compaction preflight: estimated +120–180 production LOC.
  • Memory indexing batch statistics: estimated +160–240, preserving ordered duplicate/missing results and public synchronous SDK contracts.
  • Completion-input predicate: estimated +180–280 or more; its synchronous live recovery/delivery guards need a separate authority design.

@clawsweeper

clawsweeper Bot commented Oct 1, 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: XL labels Oct 1, 2026
@steipete

steipete commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 1, 2026, 6:41 PM ET / 22:41 UTC (Revision 2).

ClawSweeper review

What this changes

The 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
Reviewed head: a6d88aa79ab58df77e0d2bfe0ff8f2376ae91a18

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent worker migration with useful boundary coverage and no identified blocking defect.
Proof confidence 🌊 off-meta tidepool Not applicable: The ordinary contributor proof gate is exempt for the verified repository admin. Inspected tests cover the production SQLite worker facade and delayed-accounting rejection; they are supplemental tests, not a claimed live Gateway run. No stored-data contract changes or material authority expansion require a separate proof gate.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The ordinary contributor proof gate is exempt for the verified repository admin. Inspected tests cover the production SQLite worker facade and delayed-accounting rejection; they are supplemental tests, not a claimed live Gateway run. No stored-data contract changes or material authority expansion require a separate proof gate.
Evidence reviewed 10 items Pinned patch ownership: Inspected the merge-base-to-head introduced hunks. The raw GitHub test-merge commit records the pinned base followed by the exact PR head; unrelated endpoint drift was excluded from attribution.
Current main still needs the migration: Fetched main retains synchronous active statistics and event visits in memory accounting, and synchronous bounded-tail reads in companion context. The existing worker facade lacks the two added operations.
Existing worker and native ownership: The added accounting and bounded-tail operations use the established worker facade for durable stores. Process-held Incognito databases retain their native reader; accounting uses one admitted projection snapshot, and unavailable projections schedule the existing reconciliation owner without a synchronous fallback.
Findings None None.
Security None None.

How this fits together

Session 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]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +123, Tests +218, Other -1. Total +340 across 24 files.

View PR surface stats
Area Files Added Removed Net
Source 12 487 364 +123
Tests 11 285 67 +218
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 24 772 432 +340

Review metrics

Metric Value Why it matters
Production and test growth production net +123; tests net +197; test support net +21 The stated production growth supports two typed worker operations and one shared accounting snapshot rather than a competing storage owner.

Technical review

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

Labels

Label changes:

  • add P2: This is a bounded runtime responsiveness improvement with no demonstrated urgent user-facing regression.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The ordinary contributor proof gate is exempt for the verified repository admin. Inspected tests cover the production SQLite worker facade and delayed-accounting rejection; they are supplemental tests, not a claimed live Gateway run. No stored-data contract changes or material authority expansion require a separate proof gate.

Label justifications:

  • P2: This is a bounded runtime responsiveness improvement with no demonstrated urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The ordinary contributor proof gate is exempt for the verified repository admin. Inspected tests cover the production SQLite worker facade and delayed-accounting rejection; they are supplemental tests, not a claimed live Gateway run. No stored-data contract changes or material authority expansion require a separate proof gate.

Evidence

What I checked:

  • Pinned patch ownership: Inspected the merge-base-to-head introduced hunks. The raw GitHub test-merge commit records the pinned base followed by the exact PR head; unrelated endpoint drift was excluded from attribution. (7659a14c1011)
  • Current main still needs the migration: Fetched main retains synchronous active statistics and event visits in memory accounting, and synchronous bounded-tail reads in companion context. The existing worker facade lacks the two added operations. (src/auto-reply/reply/agent-runner-memory.ts:403, 166114b80d22)
  • Existing worker and native ownership: The added accounting and bounded-tail operations use the established worker facade for durable stores. Process-held Incognito databases retain their native reader; accounting uses one admitted projection snapshot, and unavailable projections schedule the existing reconciliation owner without a synchronous fallback. (src/gateway/session-transcript-readers.ts:107, a6d88aa79ab5)
  • Post-wait checks and context fencing: Memory flush checks cancellation and operator authority after accounting and token estimation; compaction checks before consuming awaited facts. Companion context retains its contiguous suffix and generation, leaf, indexed-sequence, and message-count fence, while its consumer rechecks session identity. (src/auto-reply/reply/agent-runner-memory.ts:1076, a6d88aa79ab5)
  • Boundary and retirement coverage: Inspected tests exercise the production worker facade with real SQLite and observe absence of host transcript SQL. Separate deferred accounting tests mock the read boundary and verify retired authority prevents compaction, flush, latch persistence, and accounting updates. The body reports Testbox passes and measured costs; this review executed no target tests. (src/auto-reply/reply/agent-runner-memory.accounting.test.ts:99, a6d88aa79ab5)
  • Compatibility and security scope: The public session-store SDK retains readTranscriptStatsSync. Removed scope exports have no remaining callers, and retained projection kernels serve production readers and test support. The introduced patch changes no schema, persisted format, configuration, dependencies, permissions, or authority-bearing contract. (src/plugin-sdk/session-store-runtime.ts:212, a6d88aa79ab5)

Likely related people:

  • Peter Steinberger: Raw commit 54d930a adds src/gateway/session-transcript-readers.ts:169 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 54d930a1d3ba; files: src/gateway/session-transcript-readers.ts)
  • Goutam Adwant: Raw commit 5129c0a adds src/auto-reply/reply/agent-runner-memory.ts:693 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 5129c0af2eeb; files: src/auto-reply/reply/agent-runner-memory.ts)

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-01T22:36:17.142Z sha a6d88aa :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 Oct 1, 2026
@steipete
steipete merged commit 9988da6 into main Oct 1, 2026
176 of 178 checks passed
@steipete
steipete deleted the dbasync/s07 branch October 1, 2026 23:54
@steipete

steipete commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

steipete added a commit that referenced this pull request Oct 2, 2026
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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…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
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
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.
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 2, 2026
…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
steipete added a commit that referenced this pull request Oct 5, 2026
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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 6, 2026
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.
amittell added a commit to amittell/openclaw that referenced this pull request Oct 9, 2026
…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.
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. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL 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.

1 participant