Repository navigation
perf(sessions): reduce append and maintenance database calls - #167291
Conversation
Merge main at cbfbdc8 while retaining the selected session execution owner. Preserve transcriptOwner alongside the consolidated sessionPreparation input. Seed the queued-reader freshness fixture through the existing synchronous writer so unrelated automatic maintenance cannot occupy its controlled race window. Preserve the original snapshot, queued-write, and event-order assertions. The original head reproduced the fixture failure in all five runs; the merge base passed all five. A diagnostic proved that consumption preceded the queued write, and the corrected fixture passed all seven tests. Production and core test types, Madge, and independent P2 review passed on the integrated tree.
Merge main at e1dbb59 after #166698 landed. Keep the selected session execution and foreground fact implementation, and its freshness-fixture correction, unchanged while incorporating the canonical TEMP generation admission fix. The integration required no conflict resolution or additional product changes. Fresh P2 review is clean; affected checks and alternating statement measurements remain required before landing.
Merge main at 0abba2b while preserving both required-worker selection and the retained session reader. Keep main's reply-input and classification helpers alongside the cohort fingerprint path. Reuse main's sessionTarget object while carrying the reader, lifecycle facts, abort check, and acknowledged initialization handoff through their existing owners. Fresh independent P2 review found no actionable defects in the integrated tree. Exact-head runtime, SDK, CI, and statement proof remain landing gates.
Merge current main into the turn-budget step-one branch without rebasing. Preserve main's native writer claim and empty-maintenance completion alongside retained session-reader authority and the extracted preparation regressions. Route the two model-selection consumers to the existing host-owned test project after main moved placement reads to the shared-state worker. The three missing-broker cases reproduce before the routing repair and pass through the normal test router afterward. Post-integration production and core test types pass; Madge reports no cycles. Fresh independent P2 review found no actionable correctness findings.
Complete the async placement-reader cutover for the mixed-inline consumer, matching the entry already landed on main. The normal threaded test project reproduces five missing-host-broker failures; the existing host-owned infra project passes all 26 cases without assertion, fixture, or runtime changes. Focused proof: pnpm test src/auto-reply/reply/directive-handling.mixed-inline.test.ts --maxWorkers=1 Wall time: 104.621 seconds. Fresh P2 review is clean.
Merge current main without rebasing. Preserve its identity-preserving publication facts and fences alongside retained cohort reads and prepared execution. Keep main's close-wedge test consolidation and migrate each retained operation to the internal batched request/result contract. Fresh P2 review is clean. Core and core-test types pass, Madge reports no cycles, and 155 focused publication, cohort, authority, close/recovery and import/wrapper tests pass (1366.158 seconds including runtime preparation).
Close session database owners before deleting native-slash fixtures. Verify compressed transcript previews without requiring expanded SQLite TEXT, while retaining zero-payload title-only reads.
Integrate the iOS manual connection initializer repair and current session owner changes. Preserve the explicit worker request boundary, admitted-connection lookup, transcript sequence tracking, and retired lifecycle-count routing alongside retained cohorts.
Retain main cold-registration joins, schema generation receipts, and request-owned command cleanup alongside the turn-budget reader. Resolve the single test helper import overlap by preserving both promise helpers and all cases.
Consume main nonblocking title-deletion coverage and compressed-payload controls. Preserve complete decoded payload checks together with per-row preview markers; retain the current retry continuation and prepared runtime behavior.
Carry the existing projection readiness and latest-sequence facts through the append receipt. Consume no-op maintenance deadlines within the original synchronous read phase while preserving source checks, native mutation fences, FIFO, and fresh fallback reads.
Merge main at 6fc16a8 without rebasing. Preserve restart-safe chat's physical write-target callback in the extracted writable reader, carry the retained cohort reader separately, and keep membership projection independent from participant suppression. Extend the existing cohort flow to write through the captured physical target and reject reads after release. The case passes with the target handoff and fails when that handoff is deliberately omitted. Core and core-test types, import-cycle checks, and independent P2 review pass on the merged tree. The PR-specific changes preserve public SDK signatures, schemas, stored bytes, and configuration.
Merge main at bf67191 without rebasing. Adopt main's independent 3deadc1 cleanup fix: close each fixture's agent database owners and clear retained test trust before removing its directory. Keep every existing native command and initialization assertion; this file now matches main. All 49 native-slash cases, production and core-test types, import-cycle checks, and fresh independent P2 review pass on the merged tree.
Batch known nondecreasing entry updates within the existing quiet allowance without extending the deadline on later writes. Preserve earlier age deadlines, immediate handling for urgent or unknown changes, and owner closure while each batch performs a fresh maintenance read.
Resolve the worker-operation type imports while preserving main retained transcript reads, generation-pinned execution settlement, and asynchronous memory capture. Retain the turn-budget cohort admission changes.
Transfer the retained reader from the committed predecessor to its accepted successor using the existing same-generation handoff. Preserve reset rejection, cancellation, and release settlement in embedded and preflight compaction without adding a persisted guard read. Recognize the combined data-version freshness query in the cohort regression while retaining the exact one-probe assertion. Both compaction entry paths failed before the repair and pass afterward; focused and sibling runtime checks, type lanes, cycle checks, and P2 review passed.
Integrate main with a merge commit, preserving the read-only maintenance adoption race and the age-settlement boundary. Tool-authority snapshots now resolve the reader through their captured admission owner for each fingerprint phase. Preserve frozen classification identity, old-view revocation, and rejection after close or replacement. Real handoff regressions fail before the repair and pass afterward; focused runtime, types, cycle checks, and full P2 review passed.
Merge current main to retain the refresh-lock acquisition and serialized search projection fixes. Preserve the selected execution owner and retained-reader handoff semantics. Validation: core and all core-test type graphs, Madge, 158 focused integration and wrapper tests, and a clean P2 review. Statement measurements and current-head CI remain landing gates.
|
🦞👀 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. |
Security-sensitive guard clearedCurrent revision: This PR no longer changes files in the maintainer security-review tier. Separate CODEOWNERS requirements still apply to security policy and enforcement files. |
Preserve the landed turn-budget parent and current main changes while retaining transaction-local append metadata and maintenance deadlines. Resolve maintenance snapshot capture with both optimizations intact. Fresh P2 autoreview is scoped-clean; focused integration validation continues.
|
Landed as The native inherited-failure verifier passed for the exact head and tested merge, including source hashes, current security publisher, required gates, writer authority, and complete failed-job accounting. CI run 37841767944 had only the two synthetic-fixture failures independently reproduced in main run 37840570898; no cancellations, and all other selected jobs passed. Security-fast passed, and ClawSweeper reviewed this exact head with no findings. Its requested baseline comparison is documented in the PR body. Fresh P2 autoreview, production types, all 27 selected test-type graphs, and Madge passed. The local warm-cap timeout and aborted pre-allocation Testbox attempt remain disclosed; neither is relabeled as passing proof. Existing valid SQL, SDK, packaging, and updater evidence was reused under the landing instructions. |
…w#167291) Reduce repeated session append projection queries and no-op maintenance worker requests while preserving public receipts, stored bytes, schemas, durability, retention, permissions, and update behavior. Share verified append metadata within the existing transaction, consume no-op maintenance deadlines under the existing writer queue and live mutation witness, and coalesce eligible activity updates within the existing bounded maintenance allowance. Preserve the already-landed turn-budget parent and main's conditional snapshot capture. Recorded alternating proof reduced warmed all-thread SQL from 1221.9 to 1181.5 statements per turn and worker requests from 273.4 to 267.7. Fresh integrated P2 review is clean; production types, all 27 selected test-type graphs, and Madge pass. ClawSweeper reviewed the integrated head with no findings. CI run 37841767944 has two inherited synthetic-fixture failures matching main run 37840570898; every other selected job and security-fast passed. The native inherited-failure verifier qualified the exact head, tested merge, unchanged fixture/transport inputs, security publisher, and admin authority. The local warm-cap timing failure remains disclosed in the PR rather than claimed fixed. Landed with the reviewed head pinned after native worktree provisioning timed out on shared allocation capacity and a refreshed retry remained blocked. See PR openclaw#167291 for the full integration, proof, and inherited-failure evidence.
What Problem This Solves
Session persistence repeats projection/tail observations after appending a message and opens another maintenance read after a no-op plan. Faster no-op completion can also fragment a short write burst into multiple maintenance passes.
User Impact
No user-visible behavior change. Session persistence uses fewer SQLite statements and worker requests while preserving stored bytes, schemas, durability, retention policy, permissions, and released SDK contracts.
Why This Change Was Made
The existing anchor query also returns the latest sequence from the canonical readiness query. An internal append receipt carries its verified visible tail to the next consumer in the same transaction. Native reentry, pending-input mutations, non-tail identities, and unavailable projection facts retain canonical fresh reads. Public append callers keep their original receipts.
No-op maintenance returns its next deadline with the existing plan. A synchronous consumer uses it under the original writer queue, physical-source checks, and native mutation witness; subsequent metadata uses remain fresh. Completed owners coalesce known nondecreasing activity updates within a bounded window using the existing one-second allowance. New inserts, backdates, restores, unknown changes, and policy changes remain immediate and can preempt that window. Monotonic timer bookkeeping preserves earlier deadlines across clock rollback; each batch performs a new worker read.
After integrating main, the change spans 22 files: production +272/−89 across 14 files, tests/support +304/−45 across 7 files, and documentation +10. The growth carries the internal result through its callers, enforces bounded consumption and timer lifecycle checks, and covers the freshness, authority, and coalescing regressions. No new worker or public SDK entrypoint is introduced.
Related: #166703.
Evidence
The final three-pair series reduces warmed all-thread SQL from 1,221.9 to 1,181.5 statements/turn (−40.4, −3.31%) and worker requests from 273.4 to 267.7 per turn (−5.7). First-turn SQL falls 3,442 → 3,391 (−51). Warmed MAIN SQL is 0 on both revisions.
Three alternating pairs (P,C,P,C,P,C) ran on one AWS c7a.2xlarge machine with Node 24.21.0 and pnpm 12.5.1. Values are median [min–max]. Warmed samples are each run’s ten-turn mean; other rows are phase totals. “All” includes Gateway, worker threads, and helper processes; MAIN is the Gateway main thread. The shared harness workload (
run.mts) is unchanged. All six workload receipts report success, calibration and exact statement conservation passed, and raw SQL-error counts are zero. Duration ratios across nonempty phases are 0.983–1.010, with no skew flags.Boot’s +1 statement is the unchanged
deliveryQueue.outboundqueue SELECT. Its SQL and normalized stack counts in candidate runs 1 and 3 exactly match parent run 3; worker/request identities and timestamps bind those observations. Requests are unchanged, and +1 is within the non-turn tolerance. All other phase SQL medians are unchanged or lower, and no phase request median increases. No adjacent-window exception is needed.Attribution. The changed owners remove 41.4 SQL and 6 requests per warmed turn, identically across all three runs. Other-owner variation offsets 1.0 SQL and 0.3 requests in the aggregate medians, yielding the measured net savings above. All-thread totals include statements left unassigned by the heuristic foreground classifier; its labels do not omit work from this gate.
session.metadata.appendsession.maintenance.readEvery removed warmed-turn statement is accounted for below. The anchor query gains
latestSeqone-for-one and is not counted as a saving. Maintenance reductions come from consuming the existing plan’s deadline, sharing the transaction’s revision facts, and coalescing completed-pass write bursts. Each remaining maintenance operation still observes a fresh revision and retains required inventory/age reads.BEGINCOMMITdata_versionwith conditional schema/user markers)The four age/candidate classes are canonical-pending rows, the next-age indexed seek, prune-candidate projection, and namespace-age candidates: each falls from 3 to 1.9 statements/turn. The request saving is six fewer existing maintenance read operations; append still uses two requests.
The following table attributes each observed phase delta. For each metric, it uses the parent and candidate runs supplying that phase’s median, so every row sums exactly. SQL and request medians can come from different runs. “Other owners” is measured variation and is not credited as optimization.
Other-owner SQL accounting: first turn has ACP metadata +1, catalog +1, device pairing −5, shared row facts −1, and placement +1. Warmed turns have ACP metadata +0.4, pairing +0.7, plugin entries +0.4, exact-entry reads −0.1, row facts −0.2, target inventory +0.1, and shared facts −0.3; the request offset is row facts +0.2 and shared facts +0.1. Second-session variation is history +1, mentions +1, exact-entry reads −4, backfill +1, row facts +10, target inventory −1, entry-patch commit +1, shared facts −2, transcript hydration −1, and placement +1. Its row-fact/shared-fact request changes cancel. Shutdown has two fewer unchanged eight-statement integrity clean-close sequences (−16) and one extra existing passive WAL checkpoint (+1), with unchanged requests. None of these owner implementations changed in this PR.
Fresh Codex P2 autoreview is scoped-clean on the complete 23-file diff against parent
3475aeef1585. The earlier conflict resolution retained the parent's final input-authority assertion and active-row assertions, and migrated the removed age-RPC regression to the synchronous metadata-consumption boundary. The subsequent clean parent integration carries its fixes for five inherited unused test-support exports; the lane's original 22 files are byte-for-byte unchanged. The final follow-up removes one unused type-only re-export left in the pending-input storage module; its canonical exported type definition remains intact.Focused validation on
88ec503a42dfpassed 247/247 tests across 14 files, with no failures. The final follow-up only removes an unused type-only re-export, with no executable code or test-input changes; that exact diff is verified before reusing these results. Commands usepnpm test <file-or-group> --maxWorkers=1; combined command wall time was 338.33 seconds. Per-file execution seconds below are the measured CI cost estimate.Execution seconds are observed Vitest file execution on the proof host, not hosted CI wall time. The ten remaining files share one command wall time.
The regressions cover native append reentry, rollback, dirty/unclassified foreign projections, physical-source replacement, live maintenance authority, expired consumers, foreign-write cadence, earlier deadlines, clock rollback, bounded bursts, and closure cancellation.
Negative controls use unchanged production code and restore their test files afterward:
35f5a7f2d6b3, both append cases execute three projection queries where the candidate permits two, with no standalone raw-tail query. The native assertion and exact test names bind the result despite redacted stack coordinates.["maintenance-plan", "maintenance-age"]where the candidate permits only["maintenance-plan"].697b1bf27250, all three bounded-burst cases perform two planning passes during the first 100 ms where one is expected. The verified functional run passes those cases, including earlier deadlines and wall-clock rollback.check:changedpassed on the final head in 2,105.51 seconds, including the core typecheck, all 27 core-test type graphs, the full unused-export scan, lint, and storage/source guards. Explicit Madge, Knip, and the SQLite worker ratchet also passed. The ratchet compares directly with parent3475aeef1585and reports no T1 call-count growth. The final source-clean check passed. No skip flags, baseline expansion, or scanner exceptions were used.The native SDK comparison passed in 595.63 seconds (digest
b508c89e): zero entrypoints added/removed and zero direct declaration or export-kind changes. All 131 affected exports arereachablechanges from seven internal declaration blocks. The conservative whole-module renderer includes the age-change predicate, latest-sequence query field, private append receipt/anchor helper, internal maintenance deadline shapes, and the deleted unused type re-export. Independent report/source review confirmed that public append receipts, the capturedownerStorePathselector, JavaScript worker-store operations, and the releasedprepare(source, signal?)contract remain unchanged. No acknowledgement override or baseline edit was used.Canonical packaging passed in 421.66 seconds. The published 2026.9.8 driver × final 2026.9.9 candidate update cell passed in 462.11 seconds (updater execution: 368.166 seconds). The managed service was replaced, readiness returned 200, and the connected Gateway reported build ID
2026.9.9-1becd47b6e95-2026-10-08T14-36-39.276Z, matching the candidate. Durable history retained its session ID and message; incognito history correctly cleared from one message to zero on restart. Update status and service-stop checks passed.The tested canonical package is 104,061,625 bytes, SHA-256
5e6170d63c740433959d534e992ea0d05f931c67a9958ddffa8720ef26d0f65a. All 54 commands in the final combined proof returned their expected successful exit, the final source remained clean, and the kernel OOM log is empty.Comparison provenance: candidate
1becd47b6e9597e82e6340d5cb00196d0f69808c, parent3475aeef1585cca748ef30d7fa6cc8a9afae274b. The stacked change is gated against its pinned parent. Functional tests ran on a standard 16-class Testbox at88ec503a42df, with the final type-only difference verified before reuse. Final static gates, SDK comparison, builds, all alternating measurement pairs, packaging, and the update cell ran on one AWS c7a.2xlarge lease. Landing reuses this valid paired proof under the maintainer instruction; the integration preserves the measured SQL paths and adds no SQL requests.Scope and limits: this is a synthetic Gateway/SQLite workload, not a live-model or live-channel campaign; regular PR CI is not claimed. Canonical packaging emitted a nonfatal UI startup gzip warning: 373,474 B versus a 373,454 B limit (+20 B). This PR changes no UI or budget files; a separate parent UI-package budget comparison was not run.
Infrastructure: proof waited for fleet capacity and Testbox admission, then completed on AWS. Broker heartbeat/telemetry HTTP 500 warnings were preserved; the native run finished successfully and all workload, error, and conservation receipts remained valid. All task-owned leases are released.
Release-note context: reduce repeated session append metadata queries and no-op maintenance worker requests while preserving persistence behavior and timely maintenance.
Landing integration
Integrated main
8879e5ef4b98e7ff17b0ac04e7695f66f3e143b2with merge commit60430f9282e90d1f5bc6007ce16a2e0f8d4be3d1; no rebase. The already-landed parent #166703 is preserved exactly outside this child delta. Overlap with #166674 in maintenance snapshot capture preserves main’s conditional capture and this PR’s transaction-local revision reuse. An automatic merge duplicated an inheritedisInspectionCurrentdeclaration; resolution retains main’s single declaration.Fresh Codex P2 autoreview is scoped-clean for the complete 22-file integrated delta. Core production types and Madge pass (zero import cycles). A source check against released
v2026.10.1-beta.1confirms the changed append envelope and maintenance callback are internal; public append receipts and released SDK signatures stay unchanged. The prior native SDK diff report remains applicable to this child scope. Existing host-worker routing covers the affected suites. This diff adds no newOPENCLAW_*names.Local integration validation recorded a 120-second timeout in the maintenance worker suite’s
warm-capcase on the loaded host. Its completion arrived after Vitest advanced to the next case, so it is not counted as passing. Cold, warm, removal, and physical-source replacement cases passed before the run was stopped; the worker build alone took 526.4 seconds. The separate isolated attempt was stopped during source staging before a machine was acquired; exact-head GitHub CI supplies the hosted integration evidence. Test-type validation first encountered a stale local Ghostty patch (onCopymissing); installing the lockfile’s exact patch resolved that error. All 27 selected core-test type graphs now pass, alongside production types and Madge. These observations do not claim the original timeout is fixed.The prior CI run
37797069894failed on Discord quiet-progress assertions and a Doctor auth-profile subprocess exiting 143. The Discord assertion repair41dd80a3b8843is included in integrated main. Required CI 37841767944 completed on60430f9282e90d1f5bc6007ce16a2e0f8d4be3d1with exactly two failed test jobs and their aggregate gate, no cancellations, and all other selected jobs successful. Security-fast passed.The two remaining failures are independently inherited from main run 37840570898:
agent-runner-required-maintenance.pending-input.test.ts, one/two archive cases, returns the fixture compaction summary instead ofFOREGROUND_READY, with no foreground request recorded.agent-runner-memory.private-transcript.test.ts, completed/interrupted cases, returns the generic empty-response fallback instead ofFOREGROUND_READY.Main change #167309 projects runtime notices as
developeroruser, whileisModelRuntimeContextCarrierin the shared fixture recognizes onlysystem. Both synthetic servers consequently mistake the trailing notice for the human request. The two tests, shared classifier, and transport implementation have identical Git blobs in the tested PR merge, its main parent, and the independent main run. This PR changes none of those inputs. Native admin landing is authorized for this independently qualified inherited red; the failed checks remain reported as failures. Tested merge:bbbc42e9abe4b1d24958e5e7ec034b0e5324295a, parentsd76f6ec74ec63dafea02cfda258bdcf6ad055a52and60430f9282e90d1f5bc6007ce16a2e0f8d4be3d1.