Skip to content

fix: keep background refreshes valid through compaction and shutdown - #170239

Merged
steipete merged 2 commits into
mainfrom
dbasync/bgwarn
Oct 12, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/bgwarn

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes background usage refresh failures after compaction, expected-cancellation warnings, and unnecessary cold loading while memory indexing drains at shutdown.

User Impact

Usage totals can refresh after compaction without losing valid schema admission. Expected shutdown and source-transcript cancellations stay in debug logs; actual provider, storage, and cleanup failures remain visible. Accepted memory indexing still drains before exit. The isolated candidate completed shutdown in 499 ms, versus 15.212 s on the baseline, with none of the targeted warnings.

Why This Change Was Made

A retained reader can adopt a structured-clone alias of the same revoked shared schema receipt while a usage worker refreshes it. Comparing the JavaScript wrappers made that alias look like a newer revoked schema, rejecting the worker's valid result. Remove that duplicate veto while retaining physical identity, agent ownership, received-proof validity, and real authority checks. The persisted-refresh regression exercises DDL, shared receipt adoption, and the actual usage worker.

Removed check / accepted edge case: independently checked schema receipts are not ordered by SharedArrayBuffer wrapper identity; the serialized writer's live receipt remains authoritative. Tests that pinned the removed wrapper veto are deleted. No new admission protocol or fallback is added.

Typed Gateway-draining and transcript-read cancellations now log at debug level. Aggregates containing independent failures still warn/error, and tasks still reject. Usage refresh cancellation is quiet only when its owning scope is closing and the failure is an AbortError; committed checkpoints allow unfinished usage work to resume.

Pure memory chunk preparation now loads session storage only for the transcript-statistics task. The diagnostic baseline attributed 15.18 seconds to the first chunk task, versus milliseconds for later tasks; its eager dependency graph contained 1,141 modules (12.73 MB), while chunk preparation needs 93 (0.88 MB). Final resource cleanup took only 24 ms. The candidate's accepted post-compaction indexing completed before close; memory plugin disposal took 1.99 ms and resource teardown 3.30 ms. Work was not discarded and the 5,000 ms disposal budget is unchanged.

Live Evidence and SQL Attribution

Baseline 4c0b8b1f2d50c224b46f79afcb0366077a8a84dd; candidate runtime b86f4b5b4a5de81f254157d5efe856bf50f4356e. One isolated baseline/candidate pair under the requested relaxed-testing workflow, plus a diagnostic baseline replay. Shared SQL harness v2, with observation-only admission/shutdown spans in a private copy. All 13 turns, child run, RPCs, cron, compaction, and graceful exit passed. Later changes only explain intentional test-mock isolation.

Metric Baseline Candidate
Mean warmed turn-caused statements/turn 210.0 216.3
Mean warmed logical requests/turn 47.0 49.1
Warmed statements, median [min–max] across 10 turns 210 [205–215] 212 [210–231]
Warmed requests, median [min–max] across 10 turns 47 [46–48] 49 [47–52]
Warmed MAIN statements/turn 0 0
Background statements/min 461.64 963.08
Legacy warmed-window statements/turn 237.3 279.0
Whole-workload statements / requests 7,285 / 1,247 7,784 / 1,414
Gateway shutdown 15.212 s 0.499 s
Memory plugin disposal 15.075 s 0.002 s

These are individual runs, not three-pair medians. The diagnostic baseline had 212.0 statements / 47.4 requests per warmed turn and 35.215 s shutdown under host load. Both baselines reproduced the admission, expected-cancellation, Workshop, and disposal warnings; the candidate had zero occurrences. The deterministic persisted-refresh test covers the admission bug even when the live interleaving does not occur.

Shared read family, causal SELECTs/turn Baseline Candidate
Exact-entry facts 4.0 4.9
Actor hydration 3.0 4.0
Entry-cache snapshot loads 0 0
Row facts 0 0
Watermark reads 1.0 1.0

No SQL reduction is claimed for this warning/correctness lane. Detached usage remains exactly 10 statements / 2 requests per warmed turn in both runs. Whole-workload usage changes from 215/38 statements/requests to 181/36. Schema refresh changes from 31/1 to 63/2, all outside warmed request origins: baseline refresh occurs at compaction; candidate refreshes occur during first-turn work. No SQL is added or moved by the patch; touched runtime T1 is 0 → 0.

The higher shared-read counts have a concrete independent cause: both baselines hit the existing memory startup creation-reference race, before the changed worker can run; the candidate did not. Candidate memory indexing performs 311 warm-window statements in 80 SQL-producing requests, versus zero in both baselines. Existing unscoped memory writes invalidate the actor/retained-facts caches. Nine additional actor hydrations immediately follow those writes; the remaining additional hydration has an identical occurrence in the diagnostic baseline. All five candidate admission receives would also pass the removed veto, so the added reads are not acceptance unlocked by this change. The raw increase is retained above; the coarse memory-write invalidation is recorded as a separate follow-up. The memory startup race remains owned separately and is not claimed fixed here.

Validation and Landing

All 93 cases in six changed test files passed in PR CI run 38308188276:

Changed test file Cases / summed case time CI job wall time
session-cost-usage-cache.sqlite 18 / 4.853 s 185 s
session-cost-usage-refresh 11 / 0.879 s 178 s
openclaw-agent-db-validation-cache 47 / 4.973 s 295 s
experience-review-scheduler 12 / 0.247 s 186 s
command-queue.failure-logging 4 / 0.001 s 178 s
manager-index.worker 1 / 0.043 s 347 s

The real persisted-refresh regression took 547 ms. Tests cover quiet owned cancellation versus real write/cleanup failures, preserved task rejection, and chunk preparation without session storage. No local suite pass is claimed; the local worker-preparation attempt was stopped before execution.

CI production/test types, type-aware core/extension lint, source contracts/export collisions, Madge, T1 and dialect ratchets passed. The separate full-tree Knip export scan passed (12m53s; ordinary PR CI omits that scan). Basic changed-file format/Oxlint and diff checks pass. Four intentional partial mocks now carry the exact isolation explanations required by the mock-export guard. The exact mock-export guard now passes: 9,813 grandfathered factories, no added violations. The separate comment-only Codex review is scoped-clean with no actionable P0/P1 findings.

Codex production review: scoped-clean, no actionable P0–P2 findings. No public SDK surface changed. Published-driver update cell is not applicable: no update, Doctor, schema migration, plugin registration/loading, or service lifecycle semantics change; the worker's internal module import becomes lazy.

Inherited test failures are assigned to the main repair owner rather than hidden: session abort-queue authority fails identically on main run 38305224828 / job 114997828731 with an unprepared user-profile catalog. Memory reindex/watcher fixtures fail in untouched host runtime-config preparation paths before this worker callback; source attribution confirms unchanged tests and owners, with no claim of a matching main test execution. Placement-admission fixtures also match all 19 failed cases and four unhandled errors on main run 38298274614 / job 114974958590. One unrelated broad test shard remained running at closeout; no changed-file failure remains.

Landing uses the authorized head-pinned squash, inherited-failure exception, and proof reuse after the one-push static-comment fix. Functional/static proof is reused for the test-comment-only follow-up. No ClawSweeper wait or re-review is requested.

LOC: Docs +7/−0 (net +7); Tests +277/−27 (net +250); Production +39/−16 (net +23).

@clawsweeper

clawsweeper Bot commented Oct 12, 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 docs Improvements or additions to documentation extensions: memory-core Extension: memory-core size: M labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR repairs schema-receipt publication, quiets expected cancellations, and defers session-storage loading during memory chunk preparation.

Example: Agent worker-1 refreshes usage after compaction while a retained reader adopts an alias of the revoked schema receipt.

  • Before: Wrapper identity can cause valid worker admission to be rejected, leaving usage totals stale.
  • After: The worker's validated receipt can publish while agent, physical-file, and received-proof checks remain enforced.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, focused, and source-consistent, with no actionable finding; execution evidence does not yet establish the candidate result, and ordinary contributor proof is exempt.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored PR is outside the ordinary contributor-proof gate; the supplied workload results describe the baseline, while candidate runtime verification and focused regression execution remain pending.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Usage totals can remain stale after compaction, expected cancellations look like failures, and shutdown can pay unnecessary session-storage loading cost.
Reason: The maintainer-authored direction addresses concrete observed failures with a small production change and preserves configuration, stored formats, and accepted-work completion.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it addresses source-confirmed background-refresh failures still present on main, and no concrete introduced defect was found.

Priority: P2
Reviewed head: b86f4b5b4a5de81f254157d5efe856bf50f4356e

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Candidate Gateway compaction, persisted usage refresh, cancellation logging, and accepted indexing drain remain unverified in the supplied runtime evidence; base-fail/head-pass regression execution is also not shown.
Agent review details

How this fits together

Gateway background queues send usage, learning, and indexing work to their existing owners; those owners publish usage results, report failures, and drain accepted work during shutdown.

flowchart TD
  A[Gateway background events] --> B[Background queues]
  B --> C[Usage worker]
  C --> D[Schema receipt validation]
  D --> E[Usage cache]
  B --> F[Memory indexing worker]
  B --> G[Workshop review]
Loading

Technical review

Best possible solution:

Complete the focused repair through the existing admission, cancellation, and worker owners while preserving current storage and authorization contracts.

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

Main contains the wrapper-identity veto and eager session-storage import described by the baseline report; source establishes both paths, but this review executed no target code.

Is this the best way to solve the issue?

The patch removes the invalid wrapper comparison at its shared owner, centralizes typed cancellation classification, and preserves the existing memory worker instead of weakening accepted-work drain.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: none.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 50d26ab adds src/state/openclaw-agent-db-validation-cache.ts:147 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 50d26ab3516b; files: src/state/openclaw-agent-db-validation-cache.ts)

PR surface

Source +23, Tests +246, Docs +7. Total +276 across 14 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 6 39 16 +23
Tests 6 273 27 +246
Docs 2 7 0 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 319 43 +276

Review metrics

Metric Value Why it matters
Production versus test changes Production +39/-16; tests +273/-27 Production growth supplies one shared cancellation classifier and focused call-site changes; tests cover receipt publication, cancellation diagnostics, settlement, and lazy loading.

Labels

Label changes:

  • add P2: Stale usage totals, expected-cancellation noise, and unnecessary shutdown loading warrant a focused reliability fix without evidence of an urgent core outage.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Stale usage totals, expected-cancellation noise, and unnecessary shutdown loading warrant a focused reliability fix without evidence of an urgent core outage.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

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

  • Record the candidate Gateway workload result, including post-compaction usage persistence and graceful indexing drain.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 12, 2026, 5:08 PM ET / 21:08 UTC.

@steipete
steipete merged commit 7d81b85 into main Oct 12, 2026
36 of 39 checks passed
@steipete
steipete deleted the dbasync/bgwarn branch October 12, 2026 21:34
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…penclaw#170239)

Keep usage refreshes valid after compaction by removing the duplicate SharedArrayBuffer wrapper-identity veto while retaining physical database and received-schema proof checks.

Log expected owned shutdown and transcript cancellations at debug level without hiding independent provider, storage, or cleanup failures. Defer session-storage loading for pure memory chunk preparation so accepted indexing can drain without unnecessary cold imports.

The isolated candidate completed shutdown in 499 ms versus 15.212 s on the baseline. Targeted warnings were absent, all 93 changed-file test cases passed, and static checks and two scoped Codex reviews passed. Warmed MAIN SQL remains zero; usage remains 10 statements and 2 requests per turn. The PR records the higher raw workload caused by independent memory startup and shared-cache invalidation, plus inherited CI fixture failures and their repair owners.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation extensions: memory-core Extension: memory-core P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M 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