Skip to content

fix(infra): attribute SQLite worker exits instead of defaulting every one to "exit" - #163907

Closed
wangmiao0668000666 wants to merge 1 commit into
openclaw:mainfrom
wangmiao0668000666:fix/sqlite-worker-exit-attribution
Closed

wangmiao0668000666 wants to merge 1 commit into
openclaw:mainfrom
wangmiao0668000666:fix/sqlite-worker-exit-attribution

Conversation

@wangmiao0668000666

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: SQLite store worker retirements are always recorded as the fallback reason exit, so the stability bundle cannot distinguish an idle drain from a deliberate terminate, an error/messageerror event, or a heap-limit kill. workerLifecycle for sqlite-store.worker.js reports retired: [{reason: "exit", count: N}] even when the broker retired the slot on purpose, and the gateway logs contain no exit code or cause.

User Impact

No runtime behavior changes. Operators triaging SQLite worker churn (#159638) or "lost its native owner" failures (#163151) can now see why each worker exited, and a genuine crash logs its exit code once instead of being silently absorbed by fail().

Why This Change Was Made

worker-task-pool already attributes its own retirements by calling markWorkerRetirement with closed, cancelled, or failure. The SQLite broker's createSlot imported only createCpuTrackedWorker and never marked anything, so forgetWorker always fell back to "exit" (src/infra/worker-cpu.ts:132).

This change makes the lifecycle owner declare the cause at each exit path:

  • Owner-initiated drain (retire()): mark closed before terminate(), so a normal idle/eviction retirement stops reading as a crash.
  • error / messageerror: mark failure and log the message once (previously the cause reached fail() with no log line).
  • exit handler: forward the owner-declared reason; an unclaimed non-zero exit is recorded as failure and logged once with its code. A clean unclaimed exit keeps the existing exit label.

The Slot type gains an optional retirementReason field (the first claim wins), mirroring WorkerSource.retirementReason in worker-cpu.ts. The marks are recorded before native exit so the owner's intent is preserved, matching the existing markWorkerRetirement contract ("only confirmed native exit increments retirement").

Evidence

  • New regression attributes an owner-initiated retirement instead of the default exit reason: a slot retired through lifecycle.retire() now forwards closed to markWorkerRetirement, not the default exit.
  • New regression records an unclaimed non-zero exit as a failure with its code logged: an unclaimed exit(134) forwards failure and emits SQLite worker exited unexpectedly with code 134 through the infra/sqlite-worker logger.
  • node scripts/run-vitest.mjs src/infra/sqlite-worker-broker-lifecycle.test.ts — 8 passed (6 existing lifecycle cases plus the 2 new ones). Both new cases fail on the pre-change source (the existing exit handler called neither markWorkerRetirement nor a logger).
  • node scripts/check-changed.mjs selected lanes core production + core test for the three changed files pass; the only unrelated failure is the line-cap ratchet choking on an untracked scratch directory in the local tree (none of the changed files appear in config/max-lines-baseline.txt).
  • node --import ./scripts/tsx.mjs scripts/check-line-cap-ratchet.mts --base origin/main exits 0 for this change.

Scope

Diagnostics only: no stored-data, schema, retention, or recovery change; no user-visible behavior change. The exit code and reason are additive metadata on the existing stability-bundle retirement accounting.

Fixes #163150.

… one to "exit"

Record the owner-declared retirement reason before native exit so the
stability bundle can tell an idle drain from a crash, and log an
unclaimed non-zero exit code once instead of settling silently.

- retire() marks "closed" before terminate()
- error/messageerror mark "failure" and log the cause once
- exit forwards the owner reason; an unclaimed non-zero code is
  "failure" and is logged with its code

Fixes openclaw#163150.

Co-Authored-By: Claude Code <[email protected]>
@clawsweeper

clawsweeper Bot commented Oct 3, 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.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 3, 2026
@clawsweeper

clawsweeper Bot commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed October 2, 2026, 9:03 PM ET / October 3, 2026, 01:03 UTC.

ClawSweeper review

What this changes

The PR adds SQLite worker retirement reasons and failure logging, with two mocked lifecycle regressions.

Merge readiness

⛔ Blocked before merge - 3 items remain

The diagnostics gap remains on current main, but this patch does not repair retirement counters because it forwards attribution after the registry has removed the worker. Another open PR covers the same problem; neither implementation has merged.

Priority: P2
Reviewed head: 20232dfb51a83d321a47de8b69c9a7ac22d745fa

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful logging work remains, but the central accounting repair is ineffective and supplied validation mocks away the failing boundary.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: The captured PR body reports mocked lifecycle tests and static checks, without after-fix observations of the production broker feeding the real registry. Needs real behavior proof before merge: provide redacted terminal output or logs showing actual closed/failure counter changes and once-only failure logging; screenshots or recordings count when they show those results. Redact credentials, IP addresses, phone numbers, and private endpoints. Updating the PR body should trigger review; otherwise ask a maintainer to comment @clawsweeper re-review. No stored-data contract changes. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The captured PR body reports mocked lifecycle tests and static checks, without after-fix observations of the production broker feeding the real registry. Needs real behavior proof before merge: provide redacted terminal output or logs showing actual closed/failure counter changes and once-only failure logging; screenshots or recordings count when they show those results. Redact credentials, IP addresses, phone numbers, and private endpoints. Updating the PR body should trigger review; otherwise ask a maintainer to comment @clawsweeper re-review. No stored-data contract changes. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 9 items Pinned introduced change: Inspected the complete introduced patch and affected modules. The verified test-merge result carries the same lifecycle changes onto the pinned main parent.
Attribution arrives after accounting: createCpuTrackedWorker registers the accounting exit listener before returning. That listener counts the default exit reason and removes the source; markWorkerRetirement then ignores the missing source. The broker only stores earlier intent on its separate Slot object and forwards it from its later exit listener.
Mocked tests hide the ordering defect: Both added cases replace the CPU registry with spies and assert calls to markWorkerRetirement. They never inspect actual retirement counters or register the registry's earlier exit listener.
Findings 1 actionable finding [P2] Record attribution before the registry's exit listener runs
Security None None.

How this fits together

The SQLite worker broker runs database operations outside the Gateway main thread and owns worker shutdown. Its lifecycle events feed a shared registry that publishes worker retirement counters in diagnostics and stability bundles.

flowchart TD
  A[Database operations] --> B[SQLite worker broker]
  B --> C[Worker lifecycle]
  C --> D[Requested shutdown or failure]
  D --> E[Worker accounting registry]
  E --> F[Stability bundle counters]
  D --> G[Gateway logs]
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The captured PR body reports mocked lifecycle tests and static checks, without after-fix observations of the production broker feeding the real registry. Needs real behavior proof before merge: provide redacted terminal output or logs showing actual closed/failure counter changes and once-only failure logging; screenshots or recordings count when they show those results. Redact credentials, IP addresses, phone numbers, and private endpoints. Updating the PR body should trigger review; otherwise ask a maintainer to comment @clawsweeper re-review. No stored-data contract changes. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Record attribution before the registry's exit listener runs (P2) - createCpuTrackedWorker() registers worker-cpu.ts's exit listener before returning. That listener calls forgetWorker(), records the fallback exit reason, and deletes the source before this broker listener executes. Consequently this new call is always too late: deliberate retirement, error-driven retirement, and unclaimed non-zero exits still increment exit. Forward owner intent before termination/error cleanup and handle unclaimed exits before registry accounting. Add a regression using the real registry and assert retirement counters; the new spies conceal this failure.
  • Complete next step (P2) - Repair retirement-attribution ordering and replace spy-only assertions with real counter regressions.

Findings

  • [P2] Record attribution before the registry's exit listener runs — src/infra/sqlite-worker-broker-lifecycle.ts:165-166
Agent review details

Security

None.

PR surface

Source +50, Tests +81. Total +131 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 2 55 5 +50
Tests 1 83 2 +81
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 138 7 +131

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #163150
Summary: This PR and another open implementation target the same diagnostics report; the worker-churn and native-owner recovery reports require distinct repairs.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep one shared accounting owner, deliver retirement intent before its exit accounting runs, and validate actual counters and once-only logs without changing database cleanup semantics.

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

Yes, from source: registry registration order guarantees that its exit accounting runs before the newly added broker attribution call. No runtime reproduction was executed.

Is this the best way to solve the issue?

No, the current forwarding point is too late; the existing registry must receive intent before accounting, and regressions should assert real counter changes rather than mocked calls.

Full review comments:

  • [P2] Record attribution before the registry's exit listener runs — src/infra/sqlite-worker-broker-lifecycle.ts:165-166
    createCpuTrackedWorker() registers worker-cpu.ts's exit listener before returning. That listener calls forgetWorker(), records the fallback exit reason, and deletes the source before this broker listener executes. Consequently this new call is always too late: deliberate retirement, error-driven retirement, and unclaimed non-zero exits still increment exit. Forward owner intent before termination/error cleanup and handle unclaimed exits before registry accounting. Add a regression using the real registry and assert retirement counters; the new spies conceal this failure.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.99

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: This is a bounded operational diagnostics repair with no demonstrated change to database execution or user-turn availability.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The captured PR body reports mocked lifecycle tests and static checks, without after-fix observations of the production broker feeding the real registry. Needs real behavior proof before merge: provide redacted terminal output or logs showing actual closed/failure counter changes and once-only failure logging; screenshots or recordings count when they show those results. Redact credentials, IP addresses, phone numbers, and private endpoints. Updating the PR body should trigger review; otherwise ask a maintainer to comment @clawsweeper re-review. No stored-data contract changes. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Label justifications:

  • P2: This is a bounded operational diagnostics repair with no demonstrated change to database execution or user-turn availability.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The captured PR body reports mocked lifecycle tests and static checks, without after-fix observations of the production broker feeding the real registry. Needs real behavior proof before merge: provide redacted terminal output or logs showing actual closed/failure counter changes and once-only failure logging; screenshots or recordings count when they show those results. Redact credentials, IP addresses, phone numbers, and private endpoints. Updating the PR body should trigger review; otherwise ask a maintainer to comment @clawsweeper re-review. No stored-data contract changes. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Pinned introduced change: Inspected the complete introduced patch and affected modules. The verified test-merge result carries the same lifecycle changes onto the pinned main parent. (src/infra/sqlite-worker-broker-lifecycle.ts:166, 20232dfb51a8)
  • Attribution arrives after accounting: createCpuTrackedWorker registers the accounting exit listener before returning. That listener counts the default exit reason and removes the source; markWorkerRetirement then ignores the missing source. The broker only stores earlier intent on its separate Slot object and forwards it from its later exit listener. (src/infra/worker-cpu.ts:190, 20232dfb51a8)
  • Mocked tests hide the ordering defect: Both added cases replace the CPU registry with spies and assert calls to markWorkerRetirement. They never inspect actual retirement counters or register the registry's earlier exit listener. (src/infra/sqlite-worker-broker-lifecycle.test.ts:10, 20232dfb51a8)
  • Current main still needs attribution: Pinned main still forwards worker events to fail without marking retirement reasons or logging their general causes. Its retirement path terminates workers without attribution. (src/infra/sqlite-worker-broker-lifecycle.ts:124, 688f68e7779c)
  • Latest release retains the gap: The v2026.9.7 source likewise forwards error, messageerror, and exit without recording retirement reasons. No implemented-on-main or shipped-fix close is supported. (src/infra/sqlite-worker-broker-lifecycle.ts:75, c074824a27c9)
  • Existing accounting contract: Documentation defines closed and failure reasons, with exit reserved for unspecified causes, and requires counting only confirmed native exits. Existing task-pool retirement marks the shared registry before termination. Public docs: docs/gateway/prometheus.md. (docs/gateway/prometheus.md:321, 20232dfb51a8)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Repair event ordering and assert actual retirement counters with the shared registry active.
  • Provide redacted after-fix production-boundary observations for intentional retirement and unexpected failure.

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.

@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Closing in favor of #163377, which covers the same issue #163150 with the ordering-correct implementation.

The P2 finding on this PR is correct: createCpuTrackedWorker() registers the registry's exit-accounting listener before returning, so the broker's later worker.once("exit", ...) runs markWorkerRetirement() only after forgetWorker() has already counted the fallback "exit" reason and deleted the source — the attribution forward here always arrives too late, and the spy-only tests concealed that.

#163377 already implements what that finding prescribes: intent marked on the error/messageerror events and before terminate() (both strictly precede native exit), plus regressions against the real registry asserting actual retirement counters. Reimplementing the same approach here would just duplicate it, so I'm standing this PR down. Will reopen only if #163377 stalls.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: SQLite store worker exits are all counted as "exit" with no code or cause, and the broker never logs why a worker slot failed

1 participant