Skip to content

fix(tasks): record execution ownership and settle orphaned records at restore - #147585

Merged
steipete merged 3 commits into
mainfrom
steipete/upd-task-registry-childless-records-drain
Sep 14, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/upd-task-registry-childless-records-drain

Conversation

@steipete

@steipete steipete commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes #143420: after a forced Gateway drain timeout, childless native task records can remain running and make the successor wait through another drain even though their execution process has exited.

Reported by @gregbond (#143420).

User Impact

Newly recorded tasks with a verifiably dead local execution owner become cancelled during restore, with the interruption reason retained, so they no longer block the next restart. Live matching owners retain existing behavior. Legacy rows, foreign hosts, remote transports, and harnesses without an available process identity retain the existing grace period, including 30 minutes for childless native tasks.

Why This Change Was Made

The task lifecycle records the execution process's host, PID, and start identity. Gateway run owners record their own process; Codex native scopes use the local app-server transport PID. Connection fingerprints are not process identity. Restore reads without write admission unless an orphan is confirmed; settlement then rereads under writer custody, uses the existing terminal-outcome normalizer and retention rules, and persists before publishing restored state. Only the latest linked task can synchronize a flow, preserving newer running or successful results.

Data-model checklist: maintainer-approved additive nullable columns on task_runs: execution_owner_host TEXT, execution_owner_pid INTEGER, and execution_owner_start_identity INTEGER. No defaults, constraints, schema-version bump, configuration option, or sidecar. The canonical schema declares the columns; first task write ensures them idempotently; the additive migration path includes them. Read-only access does not add columns. Older compatible readers ignore these nullable columns and preserve their bytes; downgrading does not undo a recorded terminal outcome. A build predating main's existing schema-version change still requires its pre-update backup.

Release-note context: prevent repeated restart drains on newly tracked native tasks whose recorded execution process exited; preserve live and unknown execution ownership.

Evidence

All proof used isolated synthetic state, without operator Gateways or authenticated providers.

  • Original restore behavior failed the real-child/SQLite regression: after a simulated drain timeout, child exit, and registry reload, the successor returned drained: false instead of true. The fix returns drained: true and durably records cancelled plus Task execution process exited before restart.
  • PID reuse, live matching owner, legacy NULL/foreign ownership, queued/terminal records, failed settlement writes, and ownership replacement during writer admission are covered. Lazy ensure, idempotence, older-column reads/writes, transaction rollback, unchanged schema version, and candidate reopen pass.
  • The newer-flow running/succeeded regressions both failed before the flow guard and pass afterward. Final flow/registry/store suites: 236 passed. SDK: 8 passed. Schema maintenance: 23 passed. Earlier full task/maintenance/store/SDK/Codex/Copilot suites: 339 passed.
  • Initial CI found read-only admission regressions and an expected additive-column catalog needing exactly the three approved entries. Both are corrected without weakening assertions. Final exact-head CI is green: run 34796309720, head a7b62001c39f71e8a5d76fe7e76491ab43a0ba06.
  • Fresh full-candidate independent P1 autoreview: scoped-clean. Build, Kysely generation check, targeted changed checks, and import-cycle check passed.

Published-driver and downgrade proof

The clean candidate was built and packed with node scripts/package-openclaw-for-docker.mjs --source-dir "$PWD" --allow-unreleased-changelog --output-dir "$PWD/.local/l289/upgrade-proof/candidate-pack" --output-name candidate.tgz. Its embedded build commit is the head above; tarball SHA256 is 391d7bf4df30ccdf05aed3d4dc042aed8cb0f6ced8829394c031e112298aa604.

Using official npm packages in an isolated Linux container:

  1. Published 2026.9.3 started successfully and created a verified backup. Its unchanged openclaw update --tag /proof/candidate.tgz --yes --no-restart --json returned status: ok in 108,988 ms, including candidate migration rehearsal and Gateway canary.
  2. Candidate first task write lazily created exactly the three nullable columns. A synthetic dead-owner row was then seeded; candidate Gateway startup durably cancelled it, and its active-work drain settled in 256 ms before clean shutdown.
  3. Published 2026.9.4 read the task with tasks show, started and cleanly stopped its Gateway, preserving the ownership and terminal-outcome bytes. Both candidate and reader used state schema 17.
  4. Published 2026.9.3 correctly refused state schema 17 because it supports 16. Its supported backup restore <archive> --target <fresh-state> --json succeeded; Doctor and Gateway startup then passed with schema 16. Version markers were never lowered. These fixtures contain no agent databases, so they do not claim coverage of the separate agent-schema transition.

The canonical managed first-hop cell also passed and verified the replacement service active. Its broader second-hop cell failed with update-executor-settlement-failed / Parent executor is suspended for its candidate. and rolled the package back successfully. That path is unchanged by this PR: the child executor suspends its parent, while package Doctor calls the retained parent authority assertion. This is a separate updater follow-up, not a green result for the full canonical suite. An initial auxiliary bind-mounted npm prefix hit the shipped driver's fixed verification timeout; native container storage passed without changing timeouts.

pnpm check:changed passed all typecheck lanes, dead-code scans, and full core lint, then extension declaration preparation rejected ancestor-install discovery of punycode/package.json in the nested worktree. The guard remains intact; final hosted CI passed the isolated-checkout gates. Remaining local schema/import guards passed separately.

Record nullable process ownership for Gateway runs and local native harness
processes. Settle confirmed dead owners through the existing restart outcome
normalizer before restored tasks can block another drain. Preserve live,
foreign-host, unknown, and legacy ownership.

Add compatible nullable SQLite columns without changing the schema version.
Reported by @gregbond (#143420).
@clawsweeper

clawsweeper Bot commented Sep 14, 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 agents Agent runtime and tooling extensions: codex plugin: file-transfer size: L maintainer Maintainer-authored PR labels Sep 14, 2026
@steipete
steipete marked this pull request as ready for review September 14, 2026 00:15
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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 Sep 14, 2026
@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 13, 2026, 9:41 PM ET / September 14, 2026, 01:41 UTC (Revision 3).

ClawSweeper review

What this changes

Records task execution process identities in SQLite and cancels tasks with confirmed dead local owners during restore, while preserving live owners and newer linked task results.

Warning

SQLite table change

This PR modifies persisted SQLite tables in src/state/openclaw-state-schema.sql. Prefer a design that avoids changing persisted SQLite tables. Migration or upgrade compatibility proof is recorded, but maintainers should still confirm that the schema change is necessary.

Merge readiness

⛔ Blocked before merge - 2 items remain

This remains a distinct, useful fix for repeated restart drains. The prior flow-synchronization finding is resolved, and no blocking code findings remain.

Priority: P1
Reviewed head: a7b62001c39f71e8a5d76fe7e76491ab43a0ba06

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused implementation and prior correction look sound, but release-to-candidate compatibility remains unproven.
Proof confidence 🌊 off-meta tidepool Not applicable: The supplied maintainer classification exempts ordinary contributor proof. The reported real-child/SQLite regression exercises restore and drain behavior, while the separate published-driver upgrade requirement remains outstanding.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied maintainer classification exempts ordinary contributor proof. The reported real-child/SQLite regression exercises restore and drain behavior, while the separate published-driver upgrade requirement remains outstanding.
Evidence reviewed 12 items Pinned patch ownership: Inspected the introduced merge-base-to-head diff and verified the original head's raw parent. The stale test merge was not used to infer removal of current-main behavior.
Prior finding resolved: The previous revision synchronized every settled task. Current restore checks the latest linked task before synchronizing; the added running/succeeded successor cases protect status, goal, and endedAt.
Conservative restore settlement: Settlement requires a running, unfinished row with a recorded same-host process that is dead or has a different start identity. Rows are reread under mutation custody before persistence; unknown and live identities remain untouched.
Findings None None.
Security None None.

How this fits together

The task registry stores background-work status that Gateway restart draining consults. Gateway runs and local harness processes supply execution identity; restoration reconciles retained records before they become restart blockers.

flowchart TD
  A[Gateway runs and local harnesses] --> B[Capture process identity]
  B --> C[SQLite task records]
  C --> D[Restore and check local owner]
  D -->|Dead owner confirmed| E[Persist cancelled outcome]
  D -->|Live or unknown owner| F[Preserve running record]
  E --> G[Update latest linked flow and drain blockers]
  F --> G
Loading

Before merge

  • Resolve merge risk (P1) - The nullable schema extension and restore-time terminal writes have not been exercised through a published updater, candidate startup, and rollback. Older-shaped SQL tests do not establish that an existing installation will complete those transitions successfully.
  • Complete next step (P2) - Record fresh-start and published-driver-to-candidate upgrade results, including candidate startup and rollback compatibility on isolated copied state.
Agent review details

Security

None.

PR surface

Source +204, Tests +495, Docs +28, Generated +3. Total +730 across 26 files.

View PR surface stats
Area Files Added Removed Net
Source 16 348 144 +204
Tests 6 495 0 +495
Docs 3 29 1 +28
Config 0 0 0 0
Generated 1 3 0 +3
Other 0 0 0 0
Total 26 875 145 +730

Review metrics

Metric Value Why it matters
Persistent and SDK contracts 3 nullable columns; 1 optional SDK parameter; no schema-version bump Compatibility validation must cover both older databases and callers that omit executionPid.
Production versus test growth Production +207 net lines; tests and test support +495 net lines Production growth implements durable process identity and restore settlement; most added coverage targets persistence and lifecycle regressions.

Stored data model

Persistent data-model change detected: database schema: src/state/openclaw-state-schema.sql. Migration or upgrade compatibility proof is recorded; maintainers should verify it before merge.

Merge-risk options

Maintainer options:

  1. Complete release-boundary validation (recommended)
    Record fresh startup and a published-driver-to-candidate upgrade on isolated existing state, including rollback compatibility after ownership columns and terminal outcomes are written.

Technical review

Best possible solution:

Keep conservative process-based settlement and the latest-task flow guard, backed by verified release-to-candidate startup and rollback compatibility.

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

Yes, from source: restore a recent running childless harness task after its execution process exits, then request another drain before reconciliation grace expires. This read-only review did not execute that sequence.

Is this the best way to solve the issue?

Yes: recording actual local process identity extends the existing registry and avoids guessing ownership for legacy or remote tasks. Upgrade validation remains necessary before landing.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The supplied maintainer classification exempts ordinary contributor proof. The reported real-child/SQLite regression exercises restore and drain behavior, while the separate published-driver upgrade requirement remains outstanding.
  • remove merge-risk: 🚨 session-state: Current PR review merge-risk labels are merge-risk: 🚨 compatibility.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: The linked report describes repeated 300-second Gateway restart drains caused by ended childless native tasks.
  • merge-risk: 🚨 compatibility: The patch changes persisted task shape and restart recovery semantics without published-driver upgrade and rollback evidence.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; 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 supplied maintainer classification exempts ordinary contributor proof. The reported real-child/SQLite regression exercises restore and drain behavior, while the separate published-driver upgrade requirement remains outstanding.

Evidence

What I checked:

  • Pinned patch ownership: Inspected the introduced merge-base-to-head diff and verified the original head's raw parent. The stale test merge was not used to infer removal of current-main behavior. (a7b62001c39f)
  • Prior finding resolved: The previous revision synchronized every settled task. Current restore checks the latest linked task before synchronizing; the added running/succeeded successor cases protect status, goal, and endedAt. (src/tasks/task-registry-state.ts:405, a7b62001c39f)
  • Conservative restore settlement: Settlement requires a running, unfinished row with a recorded same-host process that is dead or has a different start identity. Rows are reread under mutation custody before persistence; unknown and live identities remain untouched. (src/tasks/task-execution-owner.ts:64, a7b62001c39f)
  • Production boundary regression coverage: The restore test creates a real child process and SQLite task, observes a blocked drain, exits the child, reloads the registry, and asserts drained=true plus a persisted cancelled outcome. Other cases cover failed writes, ownership changes during admission, and preserved live/legacy/foreign owners. These tests were inspected, not executed in this review. (src/tasks/task-registry.restore-ownership.test.ts:105, a7b62001c39f)
  • Upgrade evidence remains bounded: The captured PR body explicitly limits compatibility proof to an older table contract. The test uses current schema validation and direct older-column SQL, rather than a published updater/Gateway. Root policy requires a published-driver × candidate cell for lifecycle and migration changes. (src/tasks/task-registry.store.execution-owner.test.ts:124, a7b62001c39f)
  • Current main still needs the fix: Current main restores persisted task status unchanged. The restart-blocker predicate still includes running tasks without endedAt, so this branch supplies behavior absent from the inspected main implementation. (src/tasks/task-registry-state.ts:303, a7344f3d0355)

Likely related people:

  • Peter Navarro III: Raw commit 0d84b12 adds src/tasks/task-run-owner.ts:25 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 0d84b12e65e1; files: src/tasks/task-run-owner.ts)
  • 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.

  • Record fresh startup and published-driver × candidate upgrade results, including rollback compatibility on isolated copied state.

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 (2 earlier review cycles)
  • reviewed 2026-09-14T00:26:59.594Z sha ef3ea03 :: blocked before merge. :: [P2] Synchronize restored flows only from their latest linked task
  • reviewed 2026-09-14T01:03:45.867Z sha 8d3cfe6 :: blocked before merge. :: [P2] Synchronize restored flows only from their latest linked task

Request write admission only when restored state contains a confirmed orphan,
then reread and revalidate ownership before persisting settlement. Preserve
existing create/delete admission-failure semantics and cover a concurrent
owner rebind.

List the three approved nullable ownership columns in the canonical additive
schema contract test without relaxing its declaration checks.
Synchronize a restored orphan's mirrored flow only when that task is the
latest linked record. Keep newer live and completed successors' status,
goal, and terminal timestamps while still settling the orphaned task.

Cover both mixed-owner cases through the registry restore boundary.
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 14, 2026
@steipete
steipete merged commit cc5a746 into main Sep 14, 2026
200 checks passed
@steipete
steipete deleted the steipete/upd-task-registry-childless-records-drain branch September 14, 2026 02:08
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 14, 2026
… restore (openclaw#147585)

* fix(tasks): settle orphaned execution records at restore

Record nullable process ownership for Gateway runs and local native harness
processes. Settle confirmed dead owners through the existing restart outcome
normalizer before restored tasks can block another drain. Preserve live,
foreign-host, unknown, and legacy ownership.

Add compatible nullable SQLite columns without changing the schema version.
Reported by @gregbond (openclaw#143420).

* fix(tasks): keep unchanged restores read-only

Request write admission only when restored state contains a confirmed orphan,
then reread and revalidate ownership before persisting settlement. Preserve
existing create/delete admission-failure semantics and cover a concurrent
owner rebind.

List the three approved nullable ownership columns in the canonical additive
schema contract test without relaxing its declaration checks.

* fix(tasks): preserve newer flow results during restore

Synchronize a restored orphan's mirrored flow only when that task is the
latest linked record. Keep newer live and completed successors' status,
goal, and terminal timestamps while still settling the orphaned task.

Cover both mixed-owner cases through the registry restore boundary.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: codex maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. plugin: file-transfer rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L 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.

Forced drain timeout leaves background task records running; successor restart drains on them again

1 participant