Skip to content

refactor(state): simplify admitted database lifecycle - #173527

Closed
steipete wants to merge 3 commits into
mainfrom
deslop/z05-2-state-read-lifecycle-20261015
Closed

steipete wants to merge 3 commits into
mainfrom
deslop/z05-2-state-read-lifecycle-20261015

Conversation

@steipete

@steipete steipete commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Admitted database work repeats preliminary grants, close/release handshakes, warm schema polling, and duplicate queue bookkeeping. Those paths add work and obscure the actual owners of authority and completion.

What Changed

Use cold worker preparation, one foreground FIFO grant, and actual task completion for reclamation. Keep one bounded maintenance preparation instead of UUID slots and a release RPC. Session mutations await their real completion through the existing abortable FIFO. Heartbeat workers keep independent renewal and committed lease checks without synchronous liveness acknowledgments. Shared-state reads retain consistent snapshots and await native/child settlement before releasing them. Projection maintenance keeps its bounded cursor and writer-receipt invalidation without traversal generations. Internal producers retain their owned values without defensive cloning and repeated typed guards.

No intentional schema, durability, retention, permission, public config/protocol, SDK, or dependency change. Phase E standalone session memory, security-effect revalidation, ordinary-shutdown settlement, and human-incident protections remain.

Net production LOC: 956 removed (+1008 / -1964). Tests, fixtures/support, declarations, generated files, and docs excluded. The older preserved cleanup branch overlaps this cut and is not additive credit.

Best-effort tradeoffs accepted

Evidence

Current signed head: e3d559cd3bd6d2e26a4adba49fcede9b701ef147. Its production tree is identical to the conflict-graph proof head c3a625ab39f3843ff7cda82468feb2789e018d01; the final commit only corrects the reviewed storage wording. Exact-head hosted CI remains the broad gate.

Fresh combined review and focused repair proof are complete. Final formatting passed across 129 files, and the ordinary core type-aware lint invocation passed. Exact-head hosted CI is the broad gate.

Conflict-only rebase onto 4cf3df6352cea03d80bf0ff35758503089ba30db preserves main's authored-source publication/policy invalidation fix (#173334), its value-fact caches and tests, and the newer shared GitHub read route. The removed preparation hash moved modules on main; its now-unused relocated definition is removed as part of the same cut. On rebased head 4d04f1f266c2749609a41cafa6f76681367c651c, affected source/test type graphs, narrow type-aware lint, seven-file formatting, and runtime/static cycles (0/0) passed. All four affected owner suites passed: 17 GitHub publication/lifecycle cases and 59 runtime-config/value-fact cases, including the authored-policy invalidation controls. The wrapper completed generation verification/cleanup and exited 1 after 720.21 seconds, retaining the suppression failure below (78 total passing cases, one failing case); no aggregate-green claim.

The post-rebase suppression guard passed two cases and failed its allowlist comparison on two unchanged base entries: scripts/lib/control-ui-warm-reload-probe.ts|typescript/unbound-method|1 (#173266) and src/agents/code-mode-node.watchdog.test-support.ts|typescript/unbound-method|1 (#173574). Both files and the guard are byte-identical to the rebase base. No suppression or allowlist change is included; the subsequent exact baseline replay is recorded below.

GitHub reported another conflict on the verified pushed 4d04f1f266c... head. The next conflict-only rebase onto 6b91e8cb63a67ae5dee6c1ddd4226ade6ad7d76d preserves main's measured bounded reconciliation batching (#173620), its shared readiness predicate and new bounded-SQL regression. The sole conflicting overlap removes the already-retired traversal-counter increment while retaining the new batching. Code head c3a625ab39f3843ff7cda82468feb2789e018d01 passes affected strict source/test types, ordinary type-aware lint, formatting and runtime/static cycles (0/0). All 14 projection-status/readiness cases pass, including the new bounded-SQL regression, rollback/savepoints, orphan bounds, receipt invalidation, contention and cursor progress. The wrapper completed generation verification/cleanup and exited 1 after 880.04 seconds, retaining only the suppression failure below (16 passing cases, one failing case). Prior unchanged-owner proof above remains valid; passing readiness cases do not establish a fix for the earlier unexplained timeout.

The original suppression guard was also replayed on clean exact main 6b91e8cb63a67ae5dee6c1ddd4226ade6ad7d76d: two cases pass and line 190:72 fails with exactly the same two extra entries (96 received versus 94 expected). The original test and both implicated files have identical blobs on candidate and baseline. That establishes this specific baseline assertion only, not another CI failure or gate waiver. A fresh narrow P0-P2 documentation review is scoped-clean for the two-line storage-description correction: writer receipts request a new bounded scan after the current cursor completes, while local writes consume the pending queue. No schema or trigger change is included.

Exact prior head 8d6bd9e19794aab604631406df6b86d8903d476a, CI run 38826267037 attempt 1, exposed security post-grant, explicit-invalid-proof worker routing, and replacement-cache integration regressions. Security checks and explicit-invalid-proof routing are restored; the incomplete watcher-removal proposal is excluded. All 17 failing root jobs were inspected individually; none is called inherited without current-main proof. Existing security/cancellation/FIFO/committed-data assertions remain unchanged.

The queue cancellation assertion in job 116734771814 independently reproduces on clean current main 6574349e132d11db684392cfd1ef8cb9f32598e6: queue.authority.test.ts:285 expects [false,true], receives [true,true]. The exact-case baseline wrapper exited 1 after generation verification. This attributes that assertion only, not the other failed jobs.

Combined production-graph types and a separate graph rooted in all 21 surviving changed test files passed; runtime and static import cycles are both zero. All three lint-suppression tests passed. Independent full-candidate review completed both passes and final source verification, returning one P2 about background CAS input mutation. Declined after tracing the actual request-owned callers and retained database CAS/effect authority, under the explicit queued-input best-effort tradeoff above; not a scoped-clean verdict. The final mechanical changes shrink one obsolete assertion allowance and drop an unrelated getter edit, restoring that file exactly to base.

The changed-check invocation passed conflict, max-lines suppression, and environment-count checks, then required the getter revert and one shrink-only assertion allowance. It was stopped after 26 minutes, with 11 minutes in SQLite-worker inventory without a result; no aggregate or inventory pass is claimed. Only its verified task-owned processes were stopped. Exact-head hosted CI owns broad proof. The completed focused repair batch passed 107 tests: 64 storage admission/reclamation/projection cases, 21 auth-profile SQLite cases, 19 infra cases and three suppression cases. The auth suite includes the prior schema-error classification failure; storage includes the prior off-thread integrity, cold admission, revocation and replacement failures. The batch also reproduces the matching baseline queue failure. Its MCP suite timed out in its unchanged 180-second setup hook, so none of its 17 cases ran; this is an unresolved local proof gap, not a passing security claim. Completed-generation verification and cleanup finished; wrapper exit 1 retains both failure observations.

Prior focused proof and its gaps are retained in the lane ledger. Two Doctor cases subsequently passed serially on both candidate and exact clean base at unchanged budgets; their original batch timeouts remain unexplained, not a claimed fix. Readiness comparison was inconclusive after the clean-base wrapper stopped before a result, not evidence of inheritance. No timeout increases, retries, skips, new suppressions, or hosted CI reruns.

The kept failed-native-retirement test was also replayed serially on the candidate and exact clean base 0001c2cd97518a456109caaba920de201ef726e0. Both fail at the same initial one-second vi.waitFor(retryEntered) gate, before any native-close settlement assertions. Both wrappers completed generation verification and cleanup. This establishes a matching baseline fixture-entry failure, not load causality or passing settlement proof; the test and all its assertions remain.

@clawsweeper

clawsweeper Bot commented Oct 15, 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 size: XL labels Oct 15, 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: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 15, 2026
@clawsweeper

clawsweeper Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR simplifies shared-state read cleanup, warm database admission, transcript projection tracking, session-entry grants, and lease drainage.

Example: Three asynchronous readers select a metadata snapshot containing "first", a current value containing "second", and the original snapshot again.

  • Before: Retained continuations advance query completion and cleanup explicitly.
  • After: Readers await completion and cleanup while retaining snapshot bytes, preserving "first", "second", "first".

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, explicitly justified simplification with no discrete defect found; incomplete lifecycle validation limits confidence.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; supplied evidence reports production-owner storage tests, while the inspected images cover earlier UI work and the readiness failures remain unattributed.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes · Fix scope: Complete
User problem: Repeated admission and cleanup machinery adds runtime work and maintenance complexity after a database is already admitted.
Reason: The area owner's direction is explicit, the production code shrinks substantially, and the removed safeguards have recorded tradeoffs without adding settings or competing owners.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep open: this maintainer-authored refactor has a supported simplification rationale and no concrete introduced defect identified, but remains draft with a confirmed merge conflict.

Priority: P2
Reviewed head: 15bea2f520f856200c6eae3c777f05108cfd6f43

Before merge

  • Complete next step - Resolve GitHub's reported merge conflict while preserving the reviewed lifecycle changes and applicable main-branch updates.

Findings

None.

Tests

  • Missing end-to-end proof: The reported snapshot and current-entry checks do not establish successful readiness retirement and cancellation; the three retained readiness failures still lack completed head-versus-base attribution.
Agent review details

How this fits together

Gateway and agent operations enter shared SQLite admission and worker owners, which return query results, publish writer facts, and settle native handles and private snapshots.

flowchart LR
A[Gateway and agent requests] --> B[Database admission owner]
B --> C[Read operation]
C --> D[SQLite workers and snapshots]
D --> E[Results and ordered cleanup]
B --> F[Agent writer]
F --> G[Projection cursor and writer receipts]
Loading

Technical review

Best possible solution:

Retain the simpler owners and documented tradeoffs while completing integration and attributing the readiness failures.

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

This is a refactor rather than a new bug report; source confirms the repeated machinery, and no target code was executed during this read-only review.

Is this the best way to solve the issue?

The changes consolidate existing owners and preserve the incident-backed unknown-revision fix; the removed checks have explicit maintainer rationale rather than unexplained reversions.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Retained shared-state reads changes intended behavior with a stated reason (9c93bc3: Retain native-child custody and snapshot cleanup through worker failures, including serviceable continuation progress.)
  • Warm agent admission changes intended behavior with a stated reason (perf(state): reuse retained agent writer admission #172371: Reuse retained writer preparation while retaining physical schema comparisons for tracked DDL; this PR explicitly accepts removing warm readmission.)
  • Schema-publication replay changes intended behavior with a stated reason (7c06f39: Readmit a refused schema publication before execution without replaying entered operations; this PR explicitly chooses to surface that refusal.)
  • Validation path observation changes intended behavior with a stated reason (3ac0c05: Retain database facts across native close with external invalidation; this PR delegates replacement rejection to receiving opens and privileged writes.)
  • Post-grant session-entry comparison changes intended behavior with a stated reason (3440df0: Compare session-specific facts instead of whole-store tokens after unrelated commits caused dropped events; this PR retains the grant predicate and explicitly accepts synchronous callback mutation using selected facts.)
  • Projection tracking changes intended behavior with a stated reason (359eb9c: Avoid repeated full-store status scans using bounded connection-local tracking; this PR retains bounded traversal while replacing schema generations and completion counters.)
  • Unknown-revision incident repair keeps the original intent (1eec4da: Prevent repeated first-batch scans from starving a late session after compaction.)
  • Lease drainage changes intended behavior with a stated reason (8a5b4af: Prevent agent deletion and recreation while database owners remain live; the consolidated transaction preserves live-owner exclusion and explicitly accepts rollback of stale-row cleanup.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source -510, Tests -757, Docs +29, Other 0. Total -1238 across 25 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 13 319 829 -510
Tests 9 137 894 -757
Docs 2 33 4 +29
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 25 490 1728 -1238

Review metrics

Metric Value Why it matters
Production versus tests and fixtures Production +319/-829; tests and fixtures +137/-894 The net production reduction of 510 lines removes superseded lifecycle machinery; surviving tests retain snapshot values, identity rejection, rollback, and late-session traversal contracts.

Labels

Label changes:

  • add P2: This is a substantive shared-storage simplification with normal maintainer value and no demonstrated urgent user regression.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: This is a substantive shared-storage simplification with normal maintainer value and no demonstrated urgent user regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rank-up moves

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

  • Complete exact-head versus clean-base attribution of the three readiness failures and repair any candidate-only cause.

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 15, 2026, 7:03 PM ET / 23:03 UTC.

@steipete
steipete marked this pull request as ready for review October 15, 2026 23:26
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-16T02:26:36.234756Z e3d559c New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 15bea2f520

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if (admitted === true) {
receipt.phase = "read";
borrowed?.observe();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the query error when source observation fails

When an independently borrowed read returns { error, sourceAdmitted: true } after its original native handle has retired, borrowed.observe() throws here before the worker error is examined, so the caller loses the actual SQL/domain failure and receives only the lifecycle error. Preserve the query error as primary and aggregate any observation failure, as the removed lifecycle regression test previously required.

Useful? React with 👍 / 👎.

input: {
stagingRoot,
expectedSourceIdentity: sourceIdentity,
command,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Snapshot the command before awaiting staging

When a caller starts the cold artifact-preserving plugins.metadata.read path and then mutates command.input.stateKeys while staging is allocated, this branch forwards the same object after the await, so the in-flight read can select different rows than requested. The normal transport clones commands at creation, and the previous implementation also captured this command before withSqliteSnapshotWorker; retain that invocation-time snapshot here.

AGENTS.md reference: AGENTS.md:L74-L74

Useful? React with 👍 / 👎.

@steipete
steipete force-pushed the deslop/z05-2-state-read-lifecycle-20261015 branch from 15bea2f to 8d6bd9e Compare October 15, 2026 23:53

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8d6bd9e197

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

controller.abort(new Error("Shared-state read admission closed"));
await closeTransport();
// The public result reports query failures; shutdown still joins native cleanup.
await producer.catch(() => undefined);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Close snapshot preparation before awaiting its producer

When shutdown aborts a read while startSqliteReadOnlyLocationAsync is still pending, this await can block database close indefinitely: the producer may require preparation.startClose() to join or terminate its worker, but that method is only invoked later by cleanup(), after this await completes. Start the preparation close before joining the producer on the aborted shutdown path so Gateway close/restart can settle stalled snapshot work.

AGENTS.md reference: AGENTS.md:L7-L9

Useful? React with 👍 / 👎.

await cleanup();
},
};
const unregisterSource = source.own(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Release inherited snapshots when source admission fails

If a read starts from synchronousReadSnapshots while the retained worker source is being sealed, source.own() throws synchronously here. The snapshot was already retained by the caller, but no completion or cleanup path is installed, so its reference is never released and the parent reader's snapshot directory can remain pinned after close. Setup failures need to unwind the selected snapshot and any registrations acquired so far.

AGENTS.md reference: AGENTS.md:L50-L53

Useful? React with 👍 / 👎.

@steipete steipete changed the title refactor(state): simplify admitted reads and projection lifecycle refactor(state): simplify admitted database lifecycle Oct 16, 2026
@steipete
steipete force-pushed the deslop/z05-2-state-read-lifecycle-20261015 branch from effe9b5 to 4d04f1f Compare October 16, 2026 02:01
Use existing FIFO and native task completion instead of preliminary grants,
release handshakes, and mirrored custody state. Preserve security-effect
authority, physical replacement invalidation, and ordinary shutdown settlement.

Trust admitted schema facts and producer-owned values. Keep cold worker
preparation when explicit proof is invalid and retain full initial validation.
@steipete
steipete force-pushed the deslop/z05-2-state-read-lifecycle-20261015 branch from 4d04f1f to e3d559c Compare October 16, 2026 02:21
@steipete

Copy link
Copy Markdown
Contributor Author

Closing this cleanup attempt under the campaign's required inconclusive-failure fallback, not treating its failed CI as inherited.

The managed-image fresh-artifact E2E failure remains unattributed. Its retained exact-head CI log exposes only a redacted non-retryable session-mutation error and the client stack. The bounded head/base attempts did not establish a causal repair or matching baseline failure; the baseline was stopped during its original build without a case verdict. Passing adjacent tests does not resolve that gap.

The conservative changed import graph reaches the entire coherent cleanup: 95 changed production files directly, six additional worker entrypoints/runtime companions through computed imports, and the TEMP helper through the schema-facts owner. Removing every reachable changed file and its companion tests/docs leaves no production remainder to land. Therefore this PR is withdrawn rather than receiving an inherited-failure exception or a meaningless empty repair push.

The full signed candidate is preserved on deslop/z05-parked-managed-image-import-graph-20261015 at 6baeb0b1bc9314449d4d8e8d38d49e13c93a7d67 for a later independently attributable repair. It is not landed cleanup credit. No assertion, timeout, retry, skip, suppression, or persisted schema is weakened. Phase E standalone session memory remains untouched.

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 P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant