Skip to content

fix(context-engine): keep background maintenance from blocking new messages - #97175

Closed
Jerry-Xin wants to merge 20 commits into
openclaw:mainfrom
Jerry-Xin:fix/turn-maintenance-per-task-timeout
Closed

Jerry-Xin wants to merge 20 commits into
openclaw:mainfrom
Jerry-Xin:fix/turn-maintenance-per-task-timeout

Conversation

@Jerry-Xin

@Jerry-Xin Jerry-Xin commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Deferred context-engine maintenance can outlive an idle session and block the next message. This PR makes that boundary safe and visible:

  • a foreground message or manual /compact asks maintenance to stop and allows one second for cooperative cleanup
  • if the engine ignores cancellation, the waiting turn fails promptly with retry/restart guidance instead of hanging or silently doing nothing
  • fallback stays serialized behind the original engine call and admitted transcript writes
  • late writes are rejected, and the maintenance task remains timed_out
  • the selected installed context-engine plugin is made usable in the prepared runtime via promotion from the active registry, so the engine that owns this behavior is available for recovery without mutating the process-wide registry and without force-constructing a discovery-mode factory
  • an operator's restrictive plugins.allow is now honored end-to-end: when the allow list excludes the selected context-engine plugin, the prepared runtime drops that owner and falls back to the core engine instead of rewriting the allow list to include it

Those are two parts of one operational fix: safe maintenance recovery, and loading the selected engine into the runtime where that recovery runs — without broadening the operator's execution allowlist. No config, environment variable, command-queue policy, notification policy, or persistent state is added.

Discovery-mode context-engine registrations stay read-only

The prepared-runtime handle presents registrationMode: "discovery" to plugins (so full-only side effects — broker acquisition, WSL probes, HTTP routes — do not fire during gateway prewarm) while still needing the selected context engine usable at runtime for wedge recovery. A context-engine registration now becomes lifecycle: "runtime" only for genuine full activation (registrationMode === "full"); a discovery-mode registration — including one made under a private runtime handle — stays readOnlyDiscovery.

This honors the documented read-only-discovery contract (src/plugins/plugin-registration.types.ts; discovery registration skips runtime resources): the resolver short-circuits a readOnlyDiscovery slot and falls back to the default engine without constructing the registered factory, so a discovery-conditioned, construction-unsafe factory is never built. The selected engine still reaches the prepared handle as runtime-usable through the existing promotion mechanism: promoteMatchingRuntimeContextEngineRegistrations (src/context-engine/registry.ts, called from src/agents/runtime-plugins.ts) carries the genuinely full-activated, runtime-safe factory from the active gateway registry into the prepared handle's read-only slot. Directly marking the private discovery registration runtime (the earlier approach) both risked constructing a discovery-only factory and defeated this promotion (which only replaces slots that are still readOnlyDiscovery), so switching the lifecycle decision to registrationMode === "full" is strictly safer and keeps the recovery path intact.

A regression pins the contract: an active registry holds a runtime-safe factory for the engine, the private prepared handle's discovery-mode registration uses a factory that throws if constructed, and resolving the configured engine under the prepared registry uses the promoted runtime-safe factory (called at least once), never constructs the throwing discovery factory (zero calls), and records no quarantine. A companion loader test asserts a private runtime handle's context-engine registration stays readOnlyDiscovery.

Why This Change Was Made

The deferred-maintenance scheduler owns invocation, preemption, settlement, rerun coalescing, and the host-write fence. The context-engine registry owns quarantine and fallback routing. The prepared-runtime loader owns the private runtime-capable plugin registry and the allow-list boundary for that private handle. The reply boundary carries the producer-owned recovery message to the channel.

OpenAI Codex needs no protocol field. Direct source inspection found no maintenance-debt or cancellation field in codex-rs/app-server-protocol/src/protocol/v2/thread.rs:95-180; thread-start processing consumes the existing shape in codex-rs/app-server/src/request_processors/thread_processor.rs:810-865. OpenClaw's shared lifecycle therefore owns this behavior.

Compatibility: abortSignal and undeclared engines

The additive abortSignal on maintain() does not break existing undeclared context-engine plugins, because host-parameter projection to undeclared engines is intentional current behavior, not an accidental leak:

  • The projection rule (src/context-engine/registry.ts, projectContextEngineHostParams) returns the full host-parameter set to any engine that does not declare acceptedHostParams. This is the deliberate model after refactor(context-engine): retire legacy host param default (refactor(context-engine): retire legacy host param default #122434), which removed the previous date-gated legacy narrowing (its removal window closed 2026-08-12). The retired narrowing is recorded in the compat registry (src/plugins/compat/registry-records.ts) as status: "removed", with the note that engines without acceptedHostParams now receive all current host fields.
  • The public contract documents this: docs/concepts/context-engine.md states that engines without an acceptedHostParams declaration receive every current host field, and that an engine validating a narrower input shape should declare an explicit list (including []). An engine that strictly rejects unknown keys therefore declares acceptedHostParams and is never sent abortSignal unless it lists it. The default legacy engine declares [...CONTEXT_ENGINE_HOST_PARAMS], explicitly opting in.
  • The maintain().abortSignal field is documented in src/context-engine/types.ts as additive, optional, and cooperative: an engine that ignores it (or never declares awareness of it) is still bounded by the host and recovered on the fallback engine, so no engine is required to change. The registry wrapper enforces this — a maintain() throw is caught, the slot is quarantined, and the fallback engine serves the turn.
  • Upstream tests already assert this is intended: src/context-engine/host-param-projection.test.ts asserts that fresh and resolved undeclared engines receive every host parameter, including abortSignal.

Gating abortSignal behind an explicit acceptedHostParams membership would contradict #122434, the documented contract, and those tests, and would also weaken this fix: the normal-inbound foreground-preemption regression (src/agents/embedded-agent-runner/context-engine-maintenance.test.ts) drives an undeclared background engine and asserts its abortSignal fires so the foreground turn is released. Removing the signal from undeclared engines would strip the cooperative-yield path from exactly the default case #96703 targets, to protect a strict-but-undeclared engine that the quarantine + fallback machinery already protects and that the contract already directs to declare acceptedHostParams.

User Impact

Before this change, a background maintenance task that never settled could hold a queued interactive message indefinitely, so the user's next message or manual /compact appeared to hang with no feedback. After this change, the foreground turn is released promptly: it either proceeds once maintenance yields, or fails fast with visible retry/restart guidance while the stuck task is quarantined to the fallback engine and its late writes are rejected. Operators who configure a restrictive plugins.allow continue to see that allow list respected — a custom context-engine plugin omitted from the allow list is not silently loaded or force-enabled; the runtime falls back to the core engine instead. No user-facing configuration changes; behavior is safe by default.

Evidence

Exact head: 0074d2fb81c804b344b8a6524f7abe1c07a97316

The fixed behavior was exercised at head 0074d2fb81c804b344b8a6524f7abe1c07a97316 against the real maintenance modules driven through the production admission helper, not a single unit assertion. The reproduce entrypoint reads the live git head and asserts it equals the pinned code SHA before the driver runs. A background-mode context engine whose maintain() ignores its abort signal and never self-settles — the exact wedged condition from the report — is registered through the real plugin registry, resolved via the real resolveContextEngine, and scheduled as real deferred turn-maintenance; a second same-session foreground admission then goes through the exact production helper waitForDeferredTurnMaintenanceForSession (src/agents/embedded-agent-runner/run-orchestrator.ts:188). The real code paths under test are context-engine-maintenance.ts (deferred run, foreground preemption, bounded grace, timed_out terminal state), context-engine-maintenance-abort-signal.ts (real AbortController wiring), context-engine-maintenance-fence.ts (write-fence close/drain and late-write rejection), context-engine-maintenance-error.ts (visible recovery guidance), context-engine/registry.ts quarantine + fallback routing with legacy.registration.ts/legacy.ts, process/command-queue.ts per-session lane serialization, and the tasks/* task-registry terminal status. Only true leaf I/O boundaries are stubbed — the capability lookup, the transcript-rewrite sink, SessionManager.open, and the runtime transcript read target — identical to the shipped unit tests; nothing in the preemption, fence, quarantine, or serialization path is stubbed. performance.now, setTimeout, and the real TURN_MAINTENANCE_PREEMPT_GRACE_MS=1000 grace are the real wall clock (no faked time).

{"schemaVersion":"wedge-maint-proof/1","verdict":"PASS","headSha":"0074d2fb81c804b344b8a6524f7abe1c07a97316","ranInContainer":true,"containerImage":"docker.io/library/node:24-bookworm@sha256:5711a0d445a1af54af9589066c646df387d1831a608226f4cd694fc59e745059","containerNode":"v24.18.0","wedgedEngine":"background turnMaintenanceMode engine whose maintain() ignores abortSignal and never self-settles","boundedGraceClockMs":1000,"blockedTurn":{"visibleRecoveryGuidance":"⚠️ Deferred maintenance did not stop. The context engine was quarantined, but this turn was stopped to avoid overlapping engine operations. Retry after maintenance finishes or restart the gateway.","elapsedMs":1031,"providerCallsWhileBlocked":0},"recovery":{"abortObserved":true,"quarantinedToFallback":true,"fallbackEngine":"legacy","originalEngine":"wedge-maint-proof-engine","originalEngineMaintainCalls":1,"lateHostRewriteRejected":true,"hostRewriteSinkCalls":0,"originalSettledBeforeFallback":false,"visibleFallbackReply":"Background task timed out: Context engine turn maintenance (run turn-mai).","taskStatus":"timed_out","taskStatusStable":true},"successorResult":{"changed":false,"enteredWedgedEngine":false,"blocked":true,"reason":"successor did not enter the wedged engine before prior run exited (serialized)"},"boundariesReal":["context-engine-maintenance.ts (deferred run, foreground preemption, bounded grace, timed_out terminal)","context-engine-maintenance-abort-signal.ts (real AbortController + signal handlers)","context-engine-maintenance-fence.ts (write fence close/drain, late-write rejection)","context-engine-maintenance-error.ts (visible recovery guidance)","context-engine/registry.ts (real resolveContextEngine + quarantineResolvedContextEngine + fallback routing)","context-engine/legacy.registration.ts + legacy.ts (real fallback engine)","process/command-queue.ts (real per-session lane serialization + task terminal status)","tasks/* task-registry + detached-task-runtime (real terminal status persistence)","waitForDeferredTurnMaintenanceForSession (the run-orchestrator.ts:189 admission helper)","real wall clock: performance.now(), real setTimeout, real TURN_MAINTENANCE_PREEMPT_GRACE_MS=1000ms"],"boundariesStubbed":["context-engine-capabilities.resolveContextEngineCapabilities (LLM/tool capability lookup — pure leaf lookup)","transcript-rewrite.rewriteTranscriptEntriesInSessionManager (transcript write sink — leaf I/O)","sessions/index.SessionManager.open (durable session store open — leaf I/O)","transcript-runtime-state.resolveRuntimeTranscriptReadTarget (runtime transcript read target — leaf I/O)"]}

The blocked foreground turn is released within the bounded grace (the real wall clock advanced ~1031 ms, just past the 1000 ms TURN_MAINTENANCE_PREEMPT_GRACE_MS, before release — versus hanging forever on the never-settling run), with no additional engine maintain() calls during the blocked window. The successor maintenance only enters after the prior run exits and observes the engine downgraded to legacy.

Foreground-preemption teardown now closes the deferred-maintenance write fence before firing the scheduler abort (previously abort ran first). Closing the fence first makes any write initiated from a synchronous abort listener a guaranteed no-op via the fence-closed rejection, instead of slipping past a still-open fence and landing a late transcript rewrite after preemption has begun. The two statements have no await between them, so both effects (fence closed, controller aborted) land in one synchronous tick and any suspended async worker observes them atomically regardless of order; the only observable difference is the synchronous-abort-listener write path, where close-first is strictly safer and never worse. The maintenance/command-queue unit tests remain green (abortSignal.aborted after preemption and the post-preemption fence-closed rewrite rejection both hold under the new ordering), and no test asserts the old abort-then-close sequence.

Logical-turn resolver now honors quarantine on the production recovery path. Normal embedded runs resolve their context engine through resolveLogicalTurnContextEngines, but that resolver previously neither attached the default-engine metadata needed to record a quarantine nor consulted existing quarantine state, so a wedged or timed-out deferred-maintenance run failed to quarantine the engine and the next logical turn re-resolved the same stuck engine instead of recovering on the fallback. The configured (non-default) logical-turn wrapper now carries the default engine id so a host-owned maintenance failure quarantines that slot (the default engine still never self-quarantines), and a quarantined configured engine is skipped in favor of the fallback until process restart or re-registration. The skip is recorded as a typed resolution field so the operator warning selects the correct persistence wording without re-parsing the failure text. Successor-turn regressions assert that after quarantine the next logical turn is served by the fallback (legacy) with a quarantine failure reason and the wedged custom factory is not re-invoked, and that the default engine is never quarantined.

Foreground preemption covers the normal inbound path, not only manual compaction. The mechanism lives in the shared waitForDeferredTurnMaintenanceForSession helper (which triggers preemptForForeground on the in-flight run), and the normal inbound admission calls it inside runEmbeddedAgentInternal before the global lane and before the context-engine lease begins, while the CLI next-same-session inference calls the same helper before its run; the manual /compact queued path adds one further call for its own lifecycle. A regression drives that shared helper against a wedged, abort-ignoring same-session maintenance run and asserts the run is preempted (its abort signal fires and the wait settles within the bounded grace instead of hanging), while an unrelated session's in-flight maintenance run is left untouched — proving the preemption is scoped to the matching session lane.

Restrictive-allowlist behavior is now enforced end-to-end for the selected context-engine owner. resolveSelectedContextEnginePluginIds in src/agents/harness/runtime-plugin-load-plan.ts now consults the same restrictiveAllowlistOmitsPlugin guard the memory-slot and codex-harness siblings already use, so a non-empty plugins.allow that omits the selected engine id causes the resolver to return no owner; the prepared runtime then falls back to the core engine without materializing the allow list or force-activating the excluded plugin. An empty or absent plugins.allow remains nonrestrictive (the guard is allow.length > 0 && !allow.includes(pluginId)), so operators without an allow list keep the same custom-vs-core selection as before, and denylist / enabled: false remain honored by the shared slot resolver ahead of this guard. A paired pair of regressions in src/agents/harness/runtime-plugin.test.ts drives the guard end-to-end through resolveAgentRuntimePluginLoadPlan: the omitted case asserts the engine is dropped from plan.pluginIds, plugins.allow stays ['unrelated-plugin'] unchanged, and no forced entries entry is added; the explicitly-allowed case asserts the engine is kept in plan.pluginIds, listed in plugins.allow, and enabled in entries. A fresh independent autoreview on the guard commit confirmed the fix is at the correct layer (the plan resolver, not the shared slot resolver), does not regress the empty-allowlist or denylist paths, and the two regressions exercise the behavior through the production helper.

Deferred-maintenance task cleanup now forwards the owner agent identity. The owner-scoped task APIs fail closed when they cannot resolve the caller agent id, and a bare (non-agent-scoped) session key yields none on its own; the cancel and supersede cleanup paths in context-engine-maintenance.ts previously passed only the bare session key as callerOwnerKey, so for bare-key sessions the cleanup lookup could silently no-op and leave the maintenance task non-terminal. The cleanup paths now resolve the agent identity from the session key (session-key parse first, config roster only where a config is already in scope) and forward it as callerAgentId, so cancelled and superseded maintenance tasks reach a terminal state reliably. This closes the pre-existing bare-key cleanup gap (upstream main uses the same bare-key pattern); behavior for agent-scoped session keys is unchanged. A regression registers a maintenance task under a bare owner key, drives the supersede path, and asserts the task reaches cancelled with notifyPolicy: silent; removing the identity forwarding fails the regression with the task left queued.

Additional validation:

  • exact-head behavior proof against the real maintenance modules through the production waitForDeferredTurnMaintenanceForSession admission path, at head 0074d2fb81 — passed (bounded release ~1031 ms, timed_out terminal, quarantine→legacy, late host rewrite rejected, successor serialized)
  • bare-key owner cleanup regression (superseded maintenance task under a bare owner key reaches the cancelled terminal state through the forwarded agent identity; identity removal reproduces the silent no-op) — passed (context-engine-maintenance.test.ts)
  • normal-inbound foreground preemption regression (shared admission helper, same-session lane, unrelated session isolated) — passed
  • restrictive-allowlist regression pair (omitted-owner drops to core fallback with allow unchanged; explicitly-allowed owner still loads and force-enables) — passed (runtime-plugin.test.ts)
  • exact-head discovery-mode read-only regression (active registry runtime-safe factory promoted into the prepared handle; private discovery factory throws if constructed — promoted factory called ≥1, throwing discovery factory called 0, no quarantine) — passed (context-engine.test.ts)
  • private-runtime-handle lifecycle regression (a runtime handle's discovery-mode context engine stays readOnlyDiscovery for promotion) — passed (loader.runtime-registry.test.ts)
  • logical-turn disposal lifecycle (owned deferred engines disposed only after their maintenance run finishes; quarantine honored on the next logical turn) — passed (context-engine-maintenance.test.ts, host-param-projection.test.ts)
  • focused maintenance, compaction, prepared-runtime, plugin-selection, and runtime-registry regressions — passed (loader.runtime-registry, context-engine, host-param-projection, context-engine-maintenance suites green)
  • full changed-file gate, including TypeScript (tsgo core + core-test) and lint (oxlint/oxfmt) — passed
  • structured branch autoreview after the restrictive-allowlist fix — clean; no actionable findings
  • git diff --check — passed

Size and cleanup

Every production line maps to the single operational invariant: a wedged or timed-out configured-engine maintenance run must yield to a foreground turn, be bounded, recover onto the default engine, reject its late writes, tell the operator, and not broaden the operator's execution allowlist along the way. The net production delta overstates new logic — a large share of context-engine-maintenance.ts is the abort-signal machinery relocated to a sibling file (counted as a deletion here and an addition there) and the rewriteTranscriptEntries body re-routed through the fence; the genuinely new machinery is the single DeferredTurnMaintenanceRun owner that replaces the previous closure-based pseudo-state machine, consolidating completion, abort, fencing, rerun, timeout, and drain behavior.

Scope maps to the fix, area by area:

  • context-engine-maintenance.ts + context-engine-maintenance-fence.ts + context-engine-maintenance-abort-signal.ts — the fix core: foreground preempt, bounded 1 s grace, timed_out terminal state, and a write fence that drains admitted writes so the preempted run and the fallback cannot both write the transcript.
  • context-engine/registry.ts (quarantine + defaultEngineId plumbing) and the logical-turn resolver — the recovery half: a non-default engine that wedged is skipped for the default on the next turn, and the default engine never self-quarantines.
  • context-engine-maintenance-error.ts + agent-runner-failure-reply.ts + context-engine-logical-turn.ts — turn the blocked admission into visible operator retry/restart guidance with correct quarantined-vs-retried wording (no silent dead-end).
  • context-engine/types.ts — additive, optional abortSignal on the public maintain() host contract; existing engines require no change.
  • compact.queued.ts — applies the same wait/serialize on the manual /compact sibling path so the wedge does not simply relocate.
  • context-engine-maintenance.ts cleanup identity forwarding — resolves and forwards the owner agent identity on the cancel/supersede task-cleanup paths so bare-key sessions reach the task terminal state reliably (pre-existing gap; no behavior change for agent-scoped keys).
  • plugin loader / runtime-registration cluster (loader-*.ts, registry-api.ts, registry-registrars-capabilities.ts, runtime-plugin-load-plan.ts, runtime-plugins.ts) — the reachability precondition for recovery: the selected installed context engine reaches the prepared runtime handle as runtime-usable through promotion of the genuinely full-activated, runtime-safe factory from the active registry, while the private handle still presents discovery to plugins and a discovery-mode registration stays readOnlyDiscovery (so no discovery-only factory is force-constructed). It also honors a restrictive plugins.allow end-to-end for the selected context-engine owner by mirroring the memory-slot guard. Without this reachability the private runtime would fall back to legacy/discovery-only behavior instead of the engine that actually wedged, so it cannot be split out without weakening the fix. The public full activation signal is the sole gate for a runtime context-engine lifecycle, so full-only side-effect branches do not fire during gateway prewarm.

No config, environment variable, command-queue policy, notification policy, or persistent state is added.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Jun 27, 2026
@clawsweeper

clawsweeper Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 20, 2026, 3:25 AM ET / 07:25 UTC.

ClawSweeper review

What this changes

This PR makes deferred context-engine maintenance preemptible, fenced, quarantined on timeout, and able to return visible recovery guidance instead of blocking later messages.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

Keep this PR open for maintainer review: current main still waits unboundedly for deferred maintenance, while the PR adds a tested preemption and recovery boundary. No discrete patch defect was found; acceptance needs an explicit compatibility decision for the expanded context-engine host contract.

Priority: P1
Reviewed head: 0074d2fb81c804b344b8a6524f7abe1c07a97316
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The PR has credible current-head boundary proof and targeted regressions, with a maintainer compatibility decision remaining before merge.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The PR body provides an exact-head container trace through the production maintenance boundary and records bounded recovery, quarantine, late-write rejection, and visible guidance.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body provides an exact-head container trace through the production maintenance boundary and records bounded recovery, quarantine, late-write rejection, and visible guidance.
Evidence reviewed 6 items Current-main gap: Current main’s foreground checkpoint only awaits the active maintenance promise, leaving a wedged maintenance run unbounded.
Task-owner cleanup repair: The new owner resolution derives an agent identity before owner-scoped task cancellation, and the worker forwards it on the abort path.
Regression coverage: The maintenance test creates a bare session owner with requesterAgentId, schedules replacement maintenance, and verifies the prior task becomes cancelled.
Findings None None.
Security None None.

Live Verification

Command: node scripts/run-vitest.mjs src/agents/embedded-agent-runner/context-engine-maintenance.test.ts

Result: PASS (completed)

runner@runnervmzvulz:/tmp/clawsweeper-live-proof-97175-QxFFX0/target$ node scripts/run-vitest.mjs src/agents/embedded-agent-runner/context-engine-maintenance.te
st.ts
[test] starting test/vitest/vitest.agents-embedded-agent.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-97175-QxFFX0/target

node scripts/run-vitest.mjs src/agents/embedded-agent-runner/context-engine-maintenance.test.ts
stderr | src/agents/embedded-agent-runner/context-engine-maintenance.test.ts › runContextEngineMaintenance › keeps fallback serialized behind a quarantined main
tenance run
[context-engine] Context engine "preempt-fallback-engine" owner=test:preempt-fallback-engine failed during maintain: Deferred context-engine maintenance did not
 yield to a waiting foreground turn.; quarantining it for this process and falling back to default engine "legacy".

 ✓  agents-embedded-agent  src/agents/embedded-agent-runner/context-engine-maintenance.test.ts (21 tests) 2701ms
     ✓ defers turn maintenance to a hidden background task when enabled  336ms

 Test Files  1 passed (1)
      Tests  21 passed (21)
   Start at  07:26:49
   Duration  13.69s (transform 8.80s, setup 1.26s, import 9.34s, tests 2.70s, environment 0ms)

[test] passed 1 Vitest shard in 19.87s
runner@runnervmzvulz:/tmp/clawsweeper-live-proof-97175-QxFFX0/target$ node scripts/run-vitest.mjs src/agents/embedded-agent-runner/context-engine-maintenance.te
st.ts



























Assertions:

  • PASS expect_output: Test Files

Live proof recording

Recorded live on the PR head (0074d2fb81c8), 25.067s, terminal surface.

How this fits together

Context engines run optional maintenance after agent turns, sharing a session’s sequencing with later inbound work. The maintenance scheduler, plugin registry, and reply layer together decide whether a foreground turn waits, recovers through the fallback engine, or receives a visible failure.

flowchart LR
A[Completed agent turn] --> B[Deferred maintenance]
B --> C[Session task lane]
D[New message or manual compact] --> E[Foreground preemption]
E --> F[Write fence and grace period]
F --> G[Quarantine and fallback]
G --> H[Visible recovery or next turn]
Loading

Decision needed

Question Recommendation
Should OpenClaw accept abortSignal as an additive host parameter for context engines that omit acceptedHostParams, relying on the established full-host-parameter contract and quarantine fallback? Accept the documented additive contract: Merge with the new signal, retaining the documented requirement that engines needing a narrow shape declare accepted host parameters.

Why: This is a public plugin-contract compatibility choice; source can show the documented existing projection rule but cannot decide the repository’s desired upgrade posture for third-party engines.

Before merge

  • Resolve merge risk (P1) - The PR adds abortSignal to the public context-engine host parameters; undeclared external engines receive all host fields by the documented contract, so maintainers should explicitly accept that compatibility posture.
  • Resolve merge risk (P1) - This bug fix is production-net-positive because it adds cancellation, fencing, quarantine, task-state, and plugin-handle recovery ownership; the added structure needs owner review before merge.
  • Complete next step (P2) - A maintainer must accept the plugin-contract compatibility tradeoff before merge; no narrow automated repair remains.
Agent review details

Security

None.

PR surface

Source +465, Tests +677, Docs +10, Other 0. Total +1152 across 29 files.

View PR surface stats
Area Files Added Removed Net
Source 19 770 305 +465
Tests 8 798 121 +677
Docs 1 16 6 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 29 1585 433 +1152

Review metrics

Metric Value Why it matters
Production versus tests production +712/-301; tests and test support +856/-125; docs +16/-6 The recovery fix materially expands session lifecycle and plugin-loading behavior, so its positive production growth warrants owner-boundary review.

Stored data model

Persistent data-model change detected: persistent cache schema: src/plugins/loader.runtime-registry.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Accept the additive plugin contract (recommended)
    Confirm that existing undeclared context engines intentionally receive new host fields and merge after exact-head checks pass.
  2. Narrow the API before merge
    Require explicit abortSignal acceptance if maintainers do not want undeclared engines to see the new field.

Technical review

Best possible solution:

Keep the scheduler-owned preemption and fence design, but land only after the context-engine owner accepts the public host-parameter compatibility contract and exact-head checks are green.

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

Yes. Current main directly awaits the active maintenance promise; the PR regression drives an abort-ignoring background engine and a same-session foreground admission.

Is this the best way to solve the issue?

Yes, with the stated compatibility decision. The scheduler owns preemption and fencing, while the registry owns quarantine and fallback rather than adding downstream workarounds.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 49cd6009cc08.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides an exact-head container trace through the production maintenance boundary and records bounded recovery, quarantine, late-write rejection, and visible guidance.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides an exact-head container trace through the production maintenance boundary and records bounded recovery, quarantine, late-write rejection, and visible guidance.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: A wedged maintenance task can block an interactive user message until manual intervention.
  • merge-risk: 🚨 compatibility: The PR expands the context-engine host parameter contract and changes prepared plugin-handle behavior.
  • merge-risk: 🚨 session-state: The PR changes maintenance cancellation, transcript rewrite fencing, fallback routing, and task terminal states.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides an exact-head container trace through the production maintenance boundary and records bounded recovery, quarantine, late-write rejection, and visible guidance.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides an exact-head container trace through the production maintenance boundary and records bounded recovery, quarantine, late-write rejection, and visible guidance.

Evidence

What I checked:

Likely related people:

  • Vyctor H. Brzezowski: Current-main blame attributes the existing deferred-maintenance wait and runtime-registry promotion paths to this recent source revision. (role: recent source contributor; confidence: medium; commits: 02be7fea9725; files: src/agents/embedded-agent-runner/context-engine-maintenance.ts, src/context-engine/registry.ts, src/agents/runtime-plugins.ts)

Rank-up moves

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

  • Obtain owner acceptance of the abortSignal plugin contract.
  • Wait for the exact-head required checks to complete successfully.

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 (7 earlier review cycles)
  • reviewed 2026-08-18T07:20:05.273Z sha 70641086b2bcafbd149e825faba9fed88a13d23a :: needs real behavior proof before merge. :: [P1] Forward agent identity to task-owner cleanup
  • reviewed 2026-08-18T13:18:01.656Z sha 725151371f07e9cc017ace844b890b96baed0a6c :: needs real behavior proof before merge. :: [P1] Forward agent identity to task-owner cleanup
  • reviewed 2026-08-18T19:26:55.133Z sha 4440dc026d15d1841f9f77ad8b9b36892cb3f834 :: needs real behavior proof before merge. :: [P1] Forward agent identity to task-owner cleanup
  • reviewed 2026-08-19T01:13:02.001Z sha 19e1ba56d1111bff7a4cc2ef0166335aeb70236c :: needs real behavior proof before merge. :: [P1] Restore agent identity for task-owner cleanup
  • reviewed 2026-08-19T07:31:33.024Z sha e030c53d34cb903f839db447d62521a1bb0d8432 :: needs real behavior proof before merge. :: [P1] Preserve agent identity when cancelling deferred tasks
  • reviewed 2026-08-19T13:19:32.670Z sha 6e3db7a461f9ebe5228ca5853046834116dd2f64 :: needs real behavior proof before merge. :: [P1] Forward agent identity to task-owner cleanup
  • reviewed 2026-08-19T19:14:27.486Z sha 5f593f5451fbd87ce57fd926f2d621c9d08d742d :: needs real behavior proof before merge. :: [P1] Forward agent identity to task-owner cleanup

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. 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. labels Jun 27, 2026
@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Jun 27, 2026
@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Addressed the prior review:

  • Fence after timeout (P1): added a command-queue onTaskTimeout hook that trips a per-run fence synchronously when the per-task timeout fires (plus a defensive trip in the timeout catch). The fence is threaded into the worker and the runtime-owned rewriteTranscriptEntries wrapper (checked at entry, inside the session-manager rewrite lock, and before the runtime-transcript write) and before the worker's terminal completeTaskRunByRunId / failTaskRunByRunId / progress writes. A timed-out maintenance worker can no longer commit a late transcript rewrite or resurrect the cancelled task after the foreground turn has resumed. New unit cases cover: late rewrite fenced, task-not-resurrected, and checkpoint-after-timeout ordering.
  • Real behavior proof: added an end-to-end runtime reproduction (real gateway in a container + a real background-maintenance context-engine plugin that wedges past the timeout). The redacted runtime log in the PR body shows the per-task timeout firing at 5000ms, the queued turn being released at the timeout (not after the 12s wedge nor the ~360s session abort), and the post-timeout rewrite returning the fenced no-op {"reason":"maintenance fenced after timeout"}. Fence scope verified: only timed-out deferred runs are fenced; foreground maintenance is unaffected.
  • Docs (P2): documented agents.defaults.compaction.turnMaintenanceTaskTimeoutMs in the public reference.

CHANGELOG.md left untouched for maintainers.

@clawsweeper

clawsweeper Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@Jerry-Xin
Jerry-Xin force-pushed the fix/turn-maintenance-per-task-timeout branch from fd2268e to 2ec6f1a Compare June 27, 2026 07:05
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 27, 2026
@Jerry-Xin
Jerry-Xin force-pushed the fix/turn-maintenance-per-task-timeout branch from 2ec6f1a to c2bec2d Compare June 27, 2026 08:00
@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Closes the late-persist fence race flagged in the previous review.

What changed:

  • rewriteTranscriptEntriesInRuntimeTranscript now accepts an optional shouldAbort?: () => boolean predicate
  • Two fence checks added inside the helper:
    1. After acquireSessionWriteLock succeeds, before readTranscriptFileState — catches timeout firing while blocked on the lock
    2. After rewriteTranscriptEntriesInState computes the result, before persistRuntimeTranscriptStateMutation — belt-and-suspenders
  • When the fence trips, returns { changed: false, bytesFreed: 0, rewrittenEntries: 0, reason: "rewrite fenced before persist" } without persisting, emitting, or logging; the finally block still releases the lock
  • Caller (context-engine-maintenance.ts runtime path) threads the fence via shouldAbort: () => params.maintenanceFence?.tripped === true

Why this closes the race:
If a deferred maintenance run times out while blocked waiting for the session write lock, it now sees the fence immediately after acquiring the lock and returns a no-op without persisting. The previous PR only checked the fence before calling the helper, so a timeout during the lock wait could still allow a late persist after the foreground turn resumed. This is symmetric with the session-manager path, which already re-checks the fence inside its lock.

Validation:

  • tsgo:core and tsgo:test:src clean
  • transcript-rewrite.test.ts: 7 passed (primary regression flips fence inside acquireSessionWriteLockMock.mockImplementationOnce, asserts on-disk transcript unchanged, lock released, no transcript-update event emitted)
  • context-engine-maintenance.test.ts: 28 passed (wiring assertion confirms fence predicate threaded through)
  • command-queue.test.ts + diagnostic.test.ts: 107 passed
  • oxfmt --check and oxlint clean on all touched files

Scope unchanged:

  • Out of scope (no fenced caller): rewriteTranscriptEntriesInSessionFile, chat.ts foreground caller, descriptor writes
  • Real Docker end-to-end reproduction still valid (fence now tighter: lock-acquire window closed)
  • Single squashed commit, author Jerry-Xin, no AI attribution, CHANGELOG untouched

Squashed to one commit.

@clawsweeper

clawsweeper Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jun 27, 2026
@Jerry-Xin
Jerry-Xin force-pushed the fix/turn-maintenance-per-task-timeout branch 2 times, most recently from f62b2ca to 3dc8dd5 Compare June 28, 2026 04:17
@Jerry-Xin
Jerry-Xin force-pushed the fix/turn-maintenance-per-task-timeout branch from 3dc8dd5 to aba68fd Compare June 28, 2026 10:05
@Jerry-Xin
Jerry-Xin force-pushed the fix/turn-maintenance-per-task-timeout branch from aba68fd to 21952fb Compare June 28, 2026 13:18
@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased onto latest upstream/main (clean, no conflicts, 72 new upstream commits). New head 19e1ba56d1. @clawsweeper re-review

@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased onto latest upstream/main (clean, no conflicts). New head 0233242666. @clawsweeper re-review

@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Fixed the check-dependencies deadcode failure: the ContextEngineRuntimeQuarantine type in src/context-engine/quarantine-state.ts had no production consumers, so it is now module-private (knip production + exports scans pass locally). New head e030c53d34. @clawsweeper re-review

@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased onto latest upstream/main. One conflict in src/agents/runtime-plugins.ts (loadAgentRuntimePluginRegistryHandle) resolved by keeping handleRegistrationMode: "runtime" — loadPluginRegistryHandle already forces activate: false internally, so the redundant upstream activate option would have left the private handle in discovery-only mode; runtime mode registers full runtime capabilities into the caller-owned handle without global activation. New head 6e3db7a461. @clawsweeper re-review

@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased onto latest upstream/main (clean, no conflicts). New head 5f593f5451. @clawsweeper re-review

RomneyDa and others added 20 commits August 20, 2026 15:08
…tivation

Split the plugin registration signal into two axes: the public
registrationMode ('full' only on genuine activation) and a separate
runtime-capability flag. A private runtime handle now registers the
selected context engine with a runtime-usable lifecycle while presenting
'discovery' to plugins, so full-only side-effect branches (provider
broker acquisition, WSL probes, HTTP route registration) no longer fire
during gateway post-ready prewarm for a non-activated handle.
…iring

Move the process-scoped SIGINT/SIGTERM abort-signal fan-out out of
context-engine-maintenance.ts into a self-contained sibling module so the
file stays within the max-lines budget. Pure code move plus import wiring;
preemption, write-fence, serialized maintenance, and per-task timeout
behavior are unchanged.
…orting

Reorder foreground-preemption teardown so the write fence is closed
before the scheduler abort fires. Previously abort ran first, leaving a
narrow window in which a write initiated from a synchronous abort
listener could pass the still-open fence and land a late transcript
rewrite after preemption had begun. Closing the fence first makes any
such late rewrite a guaranteed no-op (fence-closed rejection), with no
change to current execution paths and no ordering dependency between the
two statements.
Normal embedded runs resolve their context engine through
resolveLogicalTurnContextEngines, but that path neither carried the
default-engine metadata needed to record a quarantine nor consulted
existing quarantine state. A wedged or timed-out deferred-maintenance
run therefore failed to quarantine the engine, and the next logical turn
re-resolved the same stuck engine instead of recovering on the fallback.

Thread the default engine id into the configured logical-turn wrapper so
a host-owned maintenance failure can quarantine that slot (the default
engine still never self-quarantines), and skip a quarantined configured
engine in favor of the fallback until process restart or re-registration.
Record the skip as a typed resolution field so the operator warning picks
the correct persistence wording without re-parsing the failure text. Add
successor-turn regressions proving the quarantined turn serves the
fallback without re-running the wedged factory, and that the default
engine is never quarantined.
…nd path

Add a regression proving the normal inbound foreground admission preempts
an in-flight, abort-ignoring deferred turn-maintenance run for the same
session before the successor turn proceeds, via the shared
waitForDeferredTurnMaintenanceForSession helper (the call site used by
run-orchestrator and the CLI next-turn path), and that the preemption is
scoped to the matching session lane and does not abort an unrelated
session's maintenance run.
Clarify that the maintain() abortSignal is an additive, optional host
parameter: declaring it is opt-in and honoring it is a cooperative
optimization, not a correctness obligation. Existing engines remain
compatible without changes because the host bounds a wedged run and
recovers on the fallback engine even when the signal is ignored.
…text-engine owner

resolveSelectedContextEnginePluginIds() previously returned the configured
context-engine slot's owner plugin id whenever the slot resolver produced one,
even when a non-empty plugins.allow explicitly omitted that id. The prepared
runtime path then appended the id through withRuntimePluginIdsAllowed(), which
rewrote plugins.allow to include it, and force-activated it — broadening the
executable plugin surface past the operator's declared allowlist.

Mirror the memory sibling: if the selected plugin id is omitted by a
non-empty allow list, return no owner. The prepared runtime then falls back
to the core context engine without materializing the allowlist, matching how
the memory slot and codex harness paths already treat allowlist omissions.

An empty or absent allow list is nonrestrictive (guard is
allow.length > 0 && !allow.includes(pluginId)), so operators without an
allowlist keep the same custom-vs-core selection they have today.

Flip the runtime-plugin test that encoded the bypass: with allow limited to
an unrelated plugin, the selected custom context engine must be dropped from
plan.pluginIds, plugins.allow must stay ['unrelated-plugin'] (not
materialized), and no forced entry may be added. Add a positive counterpart
that keeps a context-engine owner when the same id is explicitly listed in
plugins.allow, so the guard is proven to fire only on omission.
A private runtime plugin handle presents registrationMode 'discovery' to
plugins while still needing the selected context engine usable at runtime.
The registrar previously marked such discovery-mode registrations
lifecycle 'runtime', which could construct a discovery-conditioned factory
that the read-only-discovery contract says must not be built, and it also
defeated the promotion path that carries a genuinely runtime-safe factory
from the active registry.

Register a runtime context-engine lifecycle only for genuine full
activation (registrationMode === 'full'). A discovery-mode registration
stays read-only, and promoteMatchingRuntimeContextEngineRegistrations
supplies the runtime-safe factory from the active registry when the plugin
is active there, so the selected engine remains usable without
force-constructing a discovery-mode factory.
Switch the runtime-promotion regression to adoptRuntimeContextEngineRegistrations
and resolve through the returned cloned registry via the runtime registry scope,
matching the current copy-on-write adoption contract. Keep the original discovery
handle unmutated and assert the private discovery factory is never constructed.
Extract the runtime quarantine state group from registry.ts into
quarantine-state.ts (registry keeps the public re-export) so the file
stays under the max-lines threshold. Replace the two non-const type
assertions flagged by the assertion-safety ratchet with type-safe
constructs: in-operator narrowing for the maintenance error marker and a
direct NodeJS.Process annotation for the abort-signal fallback. Adjust
the grandfathered baseline for context-engine-maintenance.ts to record
the already-removed assertion.
…ask cleanup

The owner-scoped task APIs fail closed when they cannot resolve the
caller agent id, and a bare (non-agent-scoped) session key yields none
on its own. Resolve the agent identity from the session key (session-key
parse first, config roster only when a config is already in scope) and
forward it as callerAgentId on the cancel/supersede cleanup paths so
deferred-maintenance tasks always reach a terminal state instead of
silently no-op'ing. Closes the pre-existing bare-key cleanup gap; no
behavior change for agent-scoped session keys.
@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Landed the approved hardening: the deferred-maintenance cancel/supersede cleanup paths in context-engine-maintenance.ts now forward the resolved owner agent identity (callerAgentId) to the owner-scoped task APIs, closing the pre-existing bare-key cleanup gap; a regression registers a maintenance task under a bare owner key and asserts the supersede path reaches the cancelled terminal state (fails with the task left queued if the forwarding is removed). Rebased onto current upstream/main and re-ran the exact-head wedge-maint proof at the new head; the PR body Evidence section is updated with the fresh trace.

@clawsweeper

clawsweeper Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@obviyus

obviyus commented Aug 20, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the thoughtful work here. We re-tested this on current main with two same-session messages from a real Telegram user and a deliberately wedged background-maintenance fixture. Both messages received replies; the normal turn path no longer enters that maintenance flow, so the reported failure is not reproducible on main. Closing because the original premise no longer applies. If a currently reachable reproducer emerges, we can revisit it in a focused follow-up.

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 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. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL stale Marked as stale due to inactivity 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.

3 participants