Skip to content

refactor(agents): simplify runtime publication bookkeeping - #168981

Merged
steipete merged 10 commits into
mainfrom
deslop/p06-agents-core-20261010
Oct 11, 2026
Merged

steipete merged 10 commits into
mainfrom
deslop/p06-agents-core-20261010

Conversation

@steipete

@steipete steipete commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Agent runtime bookkeeping repeatedly restarted otherwise valid work when configuration, plugin, or catalog metadata changed during an asynchronous operation. This maintainer-requested simplification removes that speculative retry machinery.

User Impact

Normal model selection, tool execution, credential checks, FIFO scheduling, and shutdown settlement remain. A request racing a reload may fail visibly and be retried by the caller; passive metadata may remain at its captured version until the next refresh. No configuration, protocol, SDK, schema, durability, retention, or permission contract changes.

Why This Change Was Made

Prepared runtime acquisition and remote catalog adoption now take one preparation path rather than repeatedly rebinding and rebuilding. Admission still handles the concrete drain, retirement, and failed-activation recovery stages. Cache publication keeps its final currentness check; tool and credential effects keep their authority checks. Steering and Tool Search retain their actual owner, FIFO, and settlement contracts without comparing unrelated metadata.

Production: 519 net lines removed. Tests that exclusively required the removed synthetic interleavings were removed with them. Open-parent borrowing, pending-auth cancellation, explicit MCP acquisition config, and queued-tool implementation checks remain. No new lint suppressions, timeouts, retries, or skips were added.

Scope proof also caught two nearby correctness issues: an earlier MCP reload could overwrite a new caller's explicit configuration, and snapshot reconciliation could prepend a separator to a later text block. Both are fixed with their existing boundary tests. Bootstrap fixtures now test the no-clobber fallback already shipped by the pinned fs-safe version; no dependency or storage policy changed.

Best-effort tradeoffs accepted

Removed guard Provenance and accepted result
Per-batch context projection cancellation #119607 measured the value of cooperative yielding; its mid-batch cancellation callbacks were synthetic coverage. Yielding and the final publication check stay; obsolete pure computation may finish unused.
Mixed-version module/cache repair #119607 seeded an old global singleton inside a synthetic process. Normal upgrades restart the process; unsupported mixed-version module replacement no longer repairs that marker.
Runtime acquisition retry/rebind loop #128138/#127217 exercised forced reload timing. A racing request now returns a visible supersession error; the next request uses the current owner. The actual no-spin incident in #153313 remains addressed.
Configured-generation re-admission 171df4e / #168410 adds re-admission for a gated Docker reproduction with a catalog publication 0.3s after admission, not a human-user incident. A superseded request now fails visibly. Parent confinement remains fail-closed, with its security test retained. The retry-only WeakSet and two retry-specific tests are removed.
Repeated passive owner selection a718c1c / #162484 added recursion alongside the real self-drain fix; that incident did not require recursive reselection. The self-drain refusal stays. Reads use one captured owner or fail visibly, rather than recursively trying later publications.
Remote catalog config reread/per-attempt cancellation #158000 used synthetic config/auth churn. Adoption reads once and prepares once; an overlapping change can defer adoption until the next normal catalog check.
Parent-generation cancellation subscriptions during adoption 504d290 / #158000 used the same synthetic churn. Parent replacement may leave bounded preparation running until its final owner/config check rejects it. Shutdown cancellation, candidate-retirement aborts, cleanup, and the final serialized effect check remain.
Three-attempt catalog adoption settlement recovery The same synthetic churn caused a second retry protocol around owner publication. One attempt remains, with one final checked atomic rows/pricing commit.
Duplicate early publication checks/error relabeling Same-tick checks and concurrent-change relabeling did not guard an effect. The final effect check stays; failures retain their actual reason.
Auth-batch sibling retry after supersession f3c52bd / #152467 used synthetic tests that superseded one owner during a sibling build. The operation now settles with its original error instead of selectively rebuilding siblings. Credential authority checks remain.
Post-await cache-stale generation check No human incident supports fencing this metadata flag. A config/auth change during discovery can let the older load clear a reused owner's stale marker; discovery may remain stale until another explicit refresh/reload. This does not grant credentials or execution authority.
Passive harness catalog cancellation #134524 fixed the actual availability report #134460; replacement/closure guards were additional synthetic hardening. Completed discovery rows are retained, and later discovery observes replacement.
Native binding clock-only rechecks after worker waits #158396 used clock-jump fixtures. An expired but unreplaced exact row can finish its prepared bookkeeping mutation; CAS takeover detection and current mutation authority still gate commit. One exact, unexpired lease check gates protected callback entry, and live effect assertions remain.
Tool Search ancestor reentrancy tracking #140767 covered synthetic nested control calls, not a reachable production control target. FIFO/exclusion and real implementation settlement remain.
Complete steering metadata fingerprint #163195 recorded a real production ordering/ownership incident. Its owner, pending-row, result-authority, and lease checks stay; metadata-only edits no longer invalidate already-captured prompt bytes.
Repeated MCP acquisition/reload replay #138694 used synthetic crossed-publication choreography. A new runtime catches up once; later reloads target the published owner. A racing creation can fail and reconnect on the next acquisition.
MCP tools/list invalidation generations and replay #125541/#125564 describe isolated protocol stress fixtures. A notification inside tools/list no longer triggers immediate replay; the next notification or explicit refresh replaces the inventory. Normal exit/reconnect, bounds, validation, and cleanup remain.
Failed-start replay crossed by config publication #158088's test forces a config publication into an in-flight failed initialization. That request may now report its first failure; ordinary backoff and explicit-refresh retry remain.

Evidence

Candidate head: d72afea0c17a45c677977e23937049d7c7fc43ec (tree 51daca08d7288e906188bc25ec3d1896bf841349).

Final exact-head CI: run 38132644989 completed successfully; all 82 jobs terminal with no failed or cancelled jobs. Full head-bound check census also confirms the CI gate and applicable security checks passed. Earlier failed/cancelled attempts are described below, not represented as passing proof.

  • Independent P2 reviews completed. The catalog-staleness, duplicate steering metadata fingerprint, and auth-sibling retry findings are explicitly accepted tradeoffs listed above; steering result facts and destination eligibility remain checked at their owners. The latest native-lease callback-entry finding was accepted and fixed with one live lease check instead of restoring per-write expiry callbacks. Its new fake-clock regression failed before the fix by entering the protected callback after expiry.
  • Conflict-only integration kept main's three repaired test fixtures byte-for-byte. All 22 conflict tests passed (cursor, sandbox, bootstrap publication, lint suppressions); affected root/tools test graphs, core types, typed lint and both cycle checks passed. Runtime and Madge cycles remain 0.
  • The native callback-entry fix passed fresh P2 review and 24 focused tests (21 native binding tests plus 3 lint-suppression tests), wrapper 212.01s; native test project 164.77s including 113.11s compiled-worker preparation. The added fake-clock case performs no real wait; the existing native suite exercises authority and worker settlement. Final affected types and typed lint are checked before push.
  • CI run 38125430266 found one owned stale expectation: the remote-catalog integration still forced config/auth replacement while pricing was paused and demanded the removed immediate retry. Only that scenario was removed; both schema variants retain normal publication, pinned pricing, input validation, worker recovery and disable coverage and pass locally (141.35s project), with gateway test types, typed lint, lint suppressions (3/3), and fresh P2 review passing.
  • The other root failure, checks-node-changed-compact-small-11, independently reproduced on clean main fd1fd2ce0ef8cb7e9c4074c8f855eff8992a54c2: embedded-agent-runner.prompt-cache.test.ts responses and in-history both raised SqliteTranscriptMutationConflictError in the session actor append path (2 failed / 2 passed). Investigation found a cold actor snapshot prevented the existing implicit-watermark retry. Fixed directly on main as e65bd3be4134f1453bb4ab26e68704c678086b58 and integrated here: all 4 prompt-cache cases and 35 session-manager siblings plus lint-suppressions pass, including explicit stale rewrite refusal. The repair passed types, typed lint and fresh P2 review.
  • Follow-up CI 38127338915 reached one more synthetic-only case: compaction's mutate=input row changes an internal selection object after starting acquisition. Removed only that row/branch under the campaign rule; five remaining compaction cases pass, along with lint-suppressions, affected types, typed lint and fresh P2 review. Its provenance is c131ec041e1 / fix(agents): derive compaction targets after runtime admission #139429, not a human report of post-call input mutation. The final conflict repair keeps main's equivalent streaming/steering refactors, removes the obsolete retry predicate, and passes 49 owner tests plus lint-suppressions. Cancelled jobs are not counted as passing; final-head hosted CI remains the gate. No CI job was rerun.
  • CI 38130432441 had one inherited fixture failure: three sessions-mutations.catalog-queue cases selected their configured default while expecting override fields, after fix(sessions): keep fallbacks when selecting the default model #169030 intentionally made that selection a default reset. Integrated main's existing fixture-only correction 194a08e59632, retaining all assertions. The corrected file passes all 14 cases on clean main under Node and Bun; the three affected cases also pass under Bun on this branch (249.87s project, mostly transformation). Exact-head hosted CI remains the final gate.
  • Focused effects suites: 43 passed across inbound-registry, remote-publication, hot-reload-dispatch and tool-search-scheduling. This includes cancellation, parent confinement, ordinary rollback/failed-activation recovery, and queued implementation replacement. Single-worker wrapper 752.15s including 142.017s compiled-worker preparation; infra 432.15s and agents-core 115.09s. Final restored remote-publication file: 7 passed, including first reply crossing catalog adoption and exact derived-parent confinement; wrapper 372.77s (184.30s worker preparation; 131.87s Vitest). These loaded-host timings are not a performance claim.
  • Integrated native-binding suites: 20 passed, including exact token cleanup, successor protection, and revocation. The same command passed all 3 lint-suppression tests. Single-worker wrapper 354.47s including 145.31s worker preparation.
  • Current core types and native-binding test graph passed; runtime cycles 0, Madge cycles 0; changed-file typed lint passed. The full changed-check run reached an old-base UI duplicate-import error already fixed on main by 48588a65222; that fix was integrated and the affected UI graph passed. Remaining type graphs and static guards were completed separately without changing baselines.
  • Isolated Linux scope run and canonical remaining projects exercised 19,900 passing tests. Eight failures were investigated: three pinned removed synthetic retry paths and were deleted; five exposed the correctness/fixture issues described above and were repaired with focused proof. Existing platform skips were unchanged. This is combined incremental proof, not a claim that one final-head all-scope invocation was green.
  • Final repair suites: 71 passed across passive runtime, SSE recovery, startup backoff, bootstrap, stream reconciliation/markup/phase coverage; 12 passed across sandbox/cursor coverage, followed by 2 passed for the real-append cursor fixture. Final MCP regression retained stdio-exit recovery and HTTP failure semantics; it passed 64 cases but hit two unchanged local child-start deadlines (1s/2s). Those initial-start paths passed on the isolated Linux run; no timeout, retry, or skip was changed to mask the local failures.
  • Full-core Linux lint passed with 13 existing max-lines warnings, none in changed files. Deadcode identified and drove removal of the unused owner-publication helper. Remaining findings were in unmodified config/state/Gateway/UI files. A separate fresh current-main checkout (f4d601a006) passed production deadcode and failed full-tree deadcode only on the unrelated readActiveGatewayLockPortMock export. The PR does not change any deadcode baseline.
  • Blacksmith Testbox did not admit a runner within 15 minutes; AWS quota pressure supplied an undersized instance, which was released. The authorized Hetzner fallback supplied the Linux proof above. All owned remote leases are stopped. Hosted CI on the exact final head remains the landing gate; no CI jobs were rerun.
Audit coverage ledger and retained boundaries
Mechanism (base lines) Scenario and provenance Decision
context-cache-projection.ts:145-213, context.ts:87-109,146-169 Cancellation/replacement during pure batched metadata computation. bf7840f / #119607 fixed a measured multi-second RPC stall by yielding and atomic publication. Mid-batch authority callbacks were extra cancellation machinery; no effect occurs in projection. REMOVE repeated projection/early checks; KEEP cooperative yields and the caller's check immediately before publication.
context-runtime-state.ts:33-38 bf7840f / #119607 seeds an old global singleton and new cache module in a synthetic child process; no human report of mixed code versions within one live process. REMOVE old-module/cache-pair normalization, its only reuse flag, and the synthetic migration test. Ordinary process startup and same-version bundled singleton sharing remain.
prepared-model-runtime-lease.ts:149-164 8720fbf / #153386. Human report #153313 by stackingrockss includes the deployed Docker version, profiler samples, and repeated boot-loop observations. Its infinite retry was caused by non-idempotent runtime selection normalization. KEEP normalized owner selection and a visible error when a settled replacement never published; REMOVE the acquisition retry loop entirely, so it cannot spin.
prepared-model-catalog-worker.ts:71-220 349aef7 / #150354. Human report #149538 by 609NFT describes copied production fleet state, 632 agents, 504 failed health probes and growing RSS. #161738 by matthematics1137 reports 92 worker lifetimes, OOMs and 1.285 TB written. KEEP one bounded shared worker, borrower cleanup, failure logging, and ordinary crash recovery. These are measured resource and real concurrency contracts, not permission to retain unrelated reload fences.
prepared-model-runtime.refresh-scope.ts:240 d56279c / #151597 by obviyus describes a controlled worker crash and synthetic Gateway regression, not a human production report. Later #161738 independently establishes actual recurring worker failures. KEEP source-bound failure reporting and bounded recovery to avoid reintroducing the observed restart/discovery amplification. The #151597 PR alone is not accepted incident evidence.
prepared-model-runtime.resources.ts:30-127 73b4086 / #143109 contains native regressions and synthetic compiled CLI/Gateway proof, no linked human incident. KEEP physical resource claims until ordinary concurrent borrowers settle and shutdown joins their cleanup; these are required cleanup mechanics, not a blanket historical-incident exemption. Inspected the complete resource owner; no extra reload retry protocol lives here.
prepared-model-runtime.plugin-lifetime.ts:230-319 382c987 / #159448 links #157842 by highfly-hi: five-agent Linux deployment with catalog-worker heap increasing 70-80 MB per scheduled turn, watchdog restarts and before/after version evidence. KEEP final registry-reference release, current execution authority, and ordinary borrowed-resource settlement. Retained memory claims are scoped to physical lifecycle, not all historical publication machinery.
prepared-model-runtime.lifecycle.ts:101-164 a718c1c / #162484 by jalehman records actual lossless-claw maintenance calls stuck about 45 minutes during reload until restart. a3e4005 / #162301 explicitly says synthetic Gateway, no production deployment. KEEP refusal of plugin work waiting on its own drain and process-close settlement. #162301 is synthetic evidence, not an independent incident exemption.
prepared-model-runtime-lease.ts acquisition loop and borrowed-generation branch 79e6755 / #128138 and related #127217 describe synthetic QA-channel/config replacement tests; #127217 explicitly reports that its pre-fix real-Gateway run still delivered replies. Retained inbound-registry tests exposed ordinary nested selected-parent borrowing as a distinct contract. REMOVE retry/rebind loop. KEEP exact open-parent borrowing and selection confinement; a reload during new acquisition may fail that request visibly.
prepared-model-runtime.published-owner.ts:91-203 a718c1c / #162484 added retry/recursive rereads alongside the real plugin-drain repair. That incident justifies self-drain refusal and ordinary settlement, not recursive passive owner reselection. REMOVE repeated rereads/retries; wait once, then project or activate once. Pure catalog-stale bookkeeping no longer revalidates generation after its await.
prepared-model-runtime.configured-refresh.ts remote catalog adoption 504d290 / #158000 has explicitly synthetic config/auth churn and fixture-provider proof; no human incident cited for the reread loop, per-attempt controllers or three-attempt owner settlement recovery. REMOVE those race-specific retries, plus early duplicate currentness checks/error relabeling. KEEP the final owner/authority check, atomic rows/pricing commit, current catalog ordering, and ordinary cancellation/disposal.
prepared-model-runtime.configured-refresh.ts:396-430 parent subscriptions 504d290 / #158000; same synthetic churn proof. Parent-generation subscriptions duplicate the final owner/generation/config check. REMOVE parent-generation early cancellation listeners. KEEP shutdown and candidate-retirement cancellation, bounded work, cleanup, and the final serialized effect check.
prepared-model-runtime.owner.ts:612-631 batch supersession retry f3c52bd / #152467. Tests force one auth owner to supersede while a sibling is building. No independent human incident identified for sibling retry. REMOVE retry of the surviving batch; retain source-bound credential/current-owner checks and report the original publication failure.
prepared-model-runtime.owner.ts:124-134 unused publication probe dd2d66c / #130856 introduced a helper returning matching/pending publication facts for acquisition retries. Its callers are gone; full-repository search finds only the definition. REMOVE the dead helper/export. Credential-refresh cancellation remains supported by the direct, abortable configured-owner wait and its unchanged regression tests.
sandbox/registry.kernel.ts:396,420; sandbox/registry.ts:295 2889a99 / #151172 is not treated as an incident report. Read-only admission accepts older schemas; tableExists consumes admitted schema.tables facts, not repeated SQL/format validation. KEEP the existing absent-table empty/null contract. No runtime foreign-commit or repeated validation probe exists in these calls.
harness/native-session/binding-leases.ts cfef174 / #158396 moved writes to workers; elapsed-time rechecks were covered by synthetic clock-jump tests. 283d5e6 / #164197 supplies native successor authority behavior, not a blanket exemption. REMOVE prepared callback plumbing and post-worker wall-clock-only rechecks. KEEP exact-row CAS, token/phase/failure checks, current mutation authority, bounded acquisition, renewal, and write settlement.
harness/context-engine-logical-turn.ts #143491/#140023 supply synthetic lifecycle tests, not qualifying human incident evidence. The owner actually holds resources used by outstanding context-engine work. KEEP ordinary work completion and deferred disposal until implementation settlement; no extra synthetic reload retry was retained here.
harness/model-catalog.ts:168-177,242-284,353 6c44634 / #134524 repairs human availability report #134460. Passive replacement/closure branches were additional maintainer hardening and synthetic variants, not that report's failure. REMOVE passive isCurrent callbacks and ambient registry replacement checks. KEEP exact owned registry/config, provider outcomes, discovery, selection and the actual availability repair.
auth-profiles/oauth-refresh-peers.ts #166183/#167002/#166659 are not claimed as human incident evidence. Refresh credentials rotate/revoke and carry account identity; copied historical peers must not replay spent tokens or inherit another account. KEEP these credential/identity effect boundaries and ordinary uncertain-write settlement. No auth-profile schema, secrets, permissions or durability changes.
worktrees lifecycle/removal Audited run-lease-owner.ts, service-preparation.ts, eviction.runtime.ts and gc-removal.ts. They coordinate destructive removal of user artifacts with live checkout/source handles, exact refs and ordinary parallel sessions. No PR title is treated as incident evidence. KEEP current-row removal/exclusive source checks and rollback/cleanup custody for writes and deletion. Removing them would risk user artifacts, independently prohibited by the data-loss boundary.
tool-search-scheduling.ts 9b93fc8 / #140767 adds ancestry reentrancy and queued object/mode identity checks with automated interactive/headless regressions. Production catalogs exclude control tools; recursive calls using the same runtime were synthetic only. REMOVE unreachable nested-call ancestry. KEEP one exact queued implementation/mode check at the effect, catalog-ID authorization, FIFO/exclusion, abort and implementation settlement.
agent-steering-queue.ts:194-263 3f761a8 / #163195 records Peter's actual three-day production errors. The incident justifies owner/FIFO repair, not a fingerprint of every result label/task/time/outcome/origin/transcript field. REMOVE full payload fingerprints and deep-equality invalidation. KEEP run-owner identity, prepared result authority, current requester store, pending-row effect checks, FIFO, exact lease/status acknowledgment and release.
agent-bundle-mcp-manager.ts and manager-install.ts 89c1a09 / #138694 reports synthetic fail-before/real-transport proof but no cited actual-use incident for repeated crossed-publication acquisition/reload. REMOVE the acquisition retry/rebind loop and repeated reload replay. KEEP the runtime-key queue, ordinary cleanup, one postcreation config catchup, requester credentials/authorization and live tool effect checks.
agent-bundle-mcp-runtime.ts catalog generations 1cf8ea4 / #125564 and follow-up 1d03e5d / #167642 have synthetic notifications/listing interleavings, not human reports for replaying tools/list during its own response. REMOVE catalog invalidation generations, replay of a notification arriving inside tools/list, and the impossible repeated replacement-retirement loop. KEEP listing single-flight, caching, bounds, diagnostics, normal reconnect, one retry for an actually exited previously healthy server, and execution authority.
prepared-model-runtime-lease.ts / plugin-lifetime.ts configured-generation re-admission 171df4e / #168410, landed during this lane, describes a gated Docker reproduction with catalog publication 0.3s after admission, not an actual human-user incident. REMOVE configured-generation retry and its now-unused WeakSet plus the two retry-only tests. KEEP fail-closed superseded-generation rejection and the new derived-parent confinement security test.

@clawsweeper

clawsweeper Bot commented Oct 11, 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 agents Agent runtime and tooling size: XL labels Oct 11, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR simplifies runtime publication bookkeeping and fixes explicit MCP configuration capture and separators between streamed reply blocks.

Example: Catalog generation 300 replaces generation 200 during runtime acquisition.

  • Before: Acquisition can restart preparation and re-admit the request on generation 300.
  • After: The racing request can return a visible supersession error; a subsequent request uses the current generation.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, coherent simplification with no identified defect; proof is chiefly through in-process boundaries and exact-head validation is still pending.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored PR is outside the ordinary contributor proof gate; recorded validation uses runtime, subscription, transport, and SQLite worker boundaries rather than a supplied shipped-entry-point demonstration.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes · Fix scope: Complete
User problem: Reloads can restart preparation, explicit MCP configuration can be displaced, and later streamed reply blocks can acquire an extra separator.
Reason: Maintainer direction explicitly accepts the simpler reload behavior, and the patch preserves the stated authority and lifecycle boundaries.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: the maintainer-approved simplification remains distinct from main, prior review concerns are resolved, and no new actionable defect was found.

Priority: P3
Reviewed head: d72afea0c17a45c677977e23937049d7c7fc43ec

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: No supplied Telegram Test Server capture exercises the changed separator behavior between native reply blocks.
Agent review details

How this fits together

Agent runtime owners consume configuration, plugin generations, and model catalogs to publish snapshots, admit execution, and settle retained resources.

flowchart TD
  A[Configuration and catalogs] --> B[Runtime publication owner]
  B --> C[Prepared snapshots]
  C --> D[Run admission]
  D --> E[Tools and model execution]
  E --> F[Reply reconciliation]
  D --> G[Resource settlement]
Loading

Technical review

Best possible solution:

Retain the simpler existing owners with their final effect checks and explicitly accepted best-effort reload behavior.

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

The refactor has no single bug reproduction; source inspection and recorded boundary tests establish its scenarios, and this read-only review ran no target tests.

Is this the best way to solve the issue?

The approach follows the repository's preference for simpler ownership and final-effect checks, with the changed retry semantics explicitly accepted by the maintainer.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit 504d290 adds src/agents/prepared-model-runtime.configured-refresh.ts:147 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 504d2905d69c; files: src/agents/prepared-model-runtime.configured-refresh.ts)

PR surface

Source -519, Tests -778. Total -1297 across 36 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 19 305 824 -519
Tests 17 206 984 -778
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 36 511 1808 -1297

Review metrics

Metric Value Why it matters
Production versus tests Production +305/-824; tests +206/-984 The reduction removes accepted retry machinery and its retired scenarios while preserving execution, cancellation, authority, and settlement coverage.

Labels

Label changes:

  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P3: This is a maintainer-directed internal simplification with focused nearby corrections.
  • merge-risk: 🚨 availability: Racing acquisitions may now fail visibly and overlapping catalog adoption may defer; the maintainer explicitly accepts these outcomes in this PR.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. The shared reply reconciliation change affects separators in Telegram-visible multi-block replies.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (5 earlier review cycles)
  • reviewed 2026-10-11T07:45:12.692Z sha fd6003d :: needs changes before merge. :: none
  • reviewed 2026-10-11T07:58:20.756Z sha fd6003d :: needs changes before merge. :: none
  • reviewed 2026-10-11T08:55:16.532Z sha d2b9f5a :: needs changes before merge. :: [P2] Update the Gateway catalog test for single-attempt adoption
  • reviewed 2026-10-11T09:19:14.588Z sha a48afed :: needs changes before merge. :: [P2] Capture explicit runtime selections before admission waits
  • reviewed 2026-10-11T10:09:48.453Z sha c87b83a :: needs changes before merge. :: none

Reviewed October 11, 2026, 6:46 AM ET / 10:46 UTC (Revision 6).

@steipete
steipete marked this pull request as ready for review October 11, 2026 07:51
@steipete
steipete force-pushed the deslop/p06-agents-core-20261010 branch from fd6003d to d2b9f5a Compare October 11, 2026 08:36
@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Oct 11, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 11, 2026
Let pure context projections complete cooperatively without per-batch cancellation callbacks. Retain generation and cancellation checks immediately before publishing cache state, and prove cancellation at that owning boundary.

Best-effort tradeoff: a superseded projection may finish unused work. Cooperative yields, atomic publication, and current-generation checks remain. Net production reduction: 30 lines.
Use one prepared owner acquisition and one catalog adoption attempt instead of retrying config and plugin publication races. Keep bounded drain, retirement, and activation-recovery admission, final publication checks, security authority, FIFO settlement, and measured resource retention.

Treat metadata changes during passive discovery, steering preparation, and queued tool admission as best effort. Remove the synthetic retry and clock-jump tests for those paths while retaining execution, credential, successor, and shutdown coverage.
@steipete
steipete force-pushed the deslop/p06-agents-core-20261010 branch from a48afed to c87b83a Compare October 11, 2026 10:00
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Oct 11, 2026
Keep explicit model persistence assertions meaningful: the selected model must differ from the fixture's default. The three failures reproduce on current main; the full 14-case file and suppression guard pass after this fixture-only correction.
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 11, 2026
@steipete
steipete merged commit f36240c into main Oct 11, 2026
143 checks passed
@steipete
steipete deleted the deslop/p06-agents-core-20261010 branch October 11, 2026 10:56
obviyus added a commit that referenced this pull request Oct 12, 2026
…mpaction V2) (#168401)

Closes #168088. Related: #168164.

## What Problem This Solves

With ChatGPT sign-in, every automatic compaction in OpenClaw ran a client-side summary: separate summarization requests with 0 cached tokens, and a lossy text summary in place of the conversation. Codex compacts the same route server-side ("remote compaction V2"): the next normal model request carries a trailing `{"type":"compaction_trigger"}` item, and the provider returns one opaque `compaction` item that stands in for the history.

## Fix

- **Request:** automatic compaction on the ChatGPT route (preflight before a turn, and mid-turn between tool rounds) sends V2 as the next normal request, through the same attempt pipeline and native ChatGPT stream, with `compaction_trigger` appended last. Tools, instructions, parameters, cache key and the full input prefix are the turn's own, so the compaction request reads the warm prompt cache.
- **Result:** exactly one non-empty `compaction` item is accepted, only after a successful terminal response and never after an abort. Collection resets for each provider attempt.
- **Checkpoint:** real user messages are retained newest-first within 64k tokens, plus the item, matching Codex `compact_remote_v2.rs`. Users retained from an earlier window stay eligible, so repeated compactions keep them.
- **Fallback:** every fallback to client compaction logs a WARN with its reason. Overflow recovery, `/compact <focus>` and manual `/compact` stay client-side; manual V2 needs session-writer ownership work and is a follow-up.
- **Fixed during live testing** (each with a regression that fails on the defect):
  1. V2 never ran: the compact request was checked before the async provider adapter dispatched it.
  2. V2 ran only in the managed client; real ChatGPT turns use the native stream. V2 now runs there.
  3. Replay normalization dropped the checkpoint turn as an empty failed turn, so the next request grew back to full history. It now keeps successful compaction checkpoints; error turns and suppression markers are still dropped.

## User Impact

ChatGPT sign-in sessions compact server-side with no extra summarization requests. Compaction reads 87–100% of its input from cache, and later turns stay at about 14–22k input tokens instead of about 91k. `params.responsesCompactEndpoint: false` turns it off.

## Evidence

Live, real ChatGPT OAuth login, `openai/gpt-6-astra`, isolated Gateway, synthetic corpus, three facts seeded before compaction. The host was loaded, so wall times are upper bounds.

| Compaction | Compaction input / cached / output | Wall | Input before → after | Next user turn input / cached | Recall |
|---|---:|---:|---:|---:|---:|
| Preflight | 90,999 / 73,856 / 885 | 20.2 s | 90,999 → 22,308 | 22,439 / 22,144 | 3/3 |
| Mid-turn, first | 91,075 / 82,560 / 575 | 12.3 s | 91,075 → 13,904 | 14,121 / 12,928 | 3/3 |
| Mid-turn, second | 76,486 / 58,880 / 716 | 17.4 s | 76,486 → 14,476 | 14,709 / 14,336 | 3/3 |

Request parity, compaction request vs the preceding normal turn:

| Compaction | Tools | Instruction chars | Input prefix | Cached vs previous input |
|---|---|---|---|---:|
| Preflight | 6 → 6 | 35,857 → 35,857 | 26/26 items identical | 89.3% |
| Mid-turn, first | 6 → 6 | 35,855 → 35,855 | 26/26 items identical | 99.8% |
| Mid-turn, second | 6 → 6 | 35,855 → 35,855 | 39/39 items identical | 86.7% |

The tool schemas, instructions, parameters and cache-key hashes were identical in all three. The final head sent exactly 3 `compaction_trigger` requests, all HTTP 200, and no client-summary requests.

**Client comparison (same route, before this change):** one client compaction of a 117.9k-token session took two summary calls (9,777 input, 0 cached, 961 output, 24.4 s). The next turn read 33,967 input with 12,800 cached. Trigger points were not matched to the V2 runs, so this is a reference, not a head-to-head benchmark.

**Tests:** fetch-boundary regressions across the managed and native ChatGPT streams cover:
- request parity;
- failed, cancelled and incomplete terminal responses;
- aborts;
- duplicate or empty items;
- multilingual retention;
- two consecutive persisted compactions;
- the async-dispatch case and replay normalization through the real `SessionManager`.

Negative controls fail on each defect. tsgo core/src/packages pass; `check-changed` passes.


## Release-landing follow-ups (2026.10.2)

- **ClawSweeper P2 fix (budget anchor), commit e902124:** V2 used to price the outgoing request with the conservative preflight estimator. That estimator counts unchanged instructions twice, because measured usage already includes them. The V2 boundary now uses the same accounting as the mid-turn precheck it replaces:
  - The shared code is `resolveProjectedRequestPressure`, split out of `checkMidTurnPrecheck`.
  - The stream guard's request observation now returns the matching measured predecessor. The foreground request is observed before V2 decides, so both price the same anchor. A checkpoint request is then observed again as its own request.
  - Requests with no anchor keep the conservative estimate.
  - Regression test: `chatgpt-v2-compaction.test.ts` "prices a matching measured prefix once before deciding to compact". It uses the 15,000-token / 12,000-char / 24,576 numbers from `attempt-midturn-precheck.test.ts`. It fails on the previous head (the boundary throws `MidTurnPrecheckSignal`) and passes now.
  - Production LOC: +45/-27. Most of that is the function split plus contract comments.
- **Test-only fixture fix, commit 018c9bc:** three Gateway e2e fixtures counted the labeled `OpenClaw runtime context:` carrier as a user turn: `gateway-rpc-chat`, `gateway-provider-review-product-proof` and `gateway-completion-replay`. These fail the same way on `main` (#168843; same fix as #168961).
- **Rollback to v2026.10.1:** that release's replay normalization drops the empty, zero-usage V2 checkpoint carrier. The raw transcript is never rewritten, so v2026.10.1 replays the full raw history, and its own client compaction applies if that history is too large. Rollback loses no data; it just loses the provider checkpoint. The stored checkpoint format already shipped in v2026.10.1, and its reader ignores the added optional `outputTokens` (details in the compatibility comment).

### Unrelated failures that also happen on `main` (proof scoped to the tests involved)

Both failures reproduce on a clean `origin/main` checkout at `ce5b795128e` with no PR code. Checking out commits around one change shows that both start at 5843d60 (#168539, "route transcript appends through the session actor"):

| Test | `5843d60c^` | `5843d60c` | `origin/main` `ce5b795128e` |
|---|---|---|---|
| `src/agents/embedded-agent-runner.prompt-cache.test.ts` | 4/4 pass | 2 fail (`SqliteTranscriptMutationConflictError` from `appendSessionManagerActor`) | 2 fail |
| `test/gateway-steer-fifo.e2e.test.ts` | 7/7 pass | 3 fail (1 model request where 2 are expected) | 3 fail |

- #168981 independently reports the prompt-cache failure on clean main.
- #169006 (steering diagnostics) landed and did not fix the steer-fifo failures.
- CI selects these tests for this PR only through the shared embedded-runner files. Neither failing path is touched here.

### Local proof on the current head

All runs below were local and focused on the touched files:
- `chatgpt-v2-compaction`: 13/13.
- The other affected `src/agents/embedded-agent-runner/run/` unit files: 208/208. These are `attempt-midturn-precheck`, `attempt-prompt-submit.*`, `attempt-stream-*`, `preemptive-compaction*`, `attempt-execution-phase`, `attempt-prompt-preflight` and `attempt-context-guards`.
- `agent-runner.runreplyagent.e2e`: 231/231.
- The 3 repaired Gateway e2e files: all passed.
- `node scripts/check-changed.mjs -- <touched files>` exited 0. That run includes `tsgo` for core and core tests.
- Codex protocol check (read directly in `../codex`): `codex-rs/core/src/compact_remote_v2_attempt.rs:70-84` and `compact_remote_v2.rs:65,398-450`.


### Unrelated failures on the current head (b3a7405, which merges `origin/main` at `ff6f58a8c32`)

The two failures above (prompt-cache and steer-fifo) no longer fail on this head; main has since landed actor-append fixes. Two other unrelated failures remain:

1. **`src/agents/embedded-agent-runner/run.harness-auth-failover.test.ts`** (5 tests, `checks-node-changed-compact-large-4`):
   - Fails the same way on a clean `origin/main` checkout at `ff6f58a8c32`, and passes at `bdcbb2d8870` (10/10).
   - `git bisect` names `e63b5a01cf26` as the first bad commit: #168992, "perf(agents): reduce repeated SQLite work during agent preparation".
   - This PR does not touch native harness auth.
2. **`extensions/codex/src/app-server/run-attempt.steering-settlement.test.ts`** (`checks-node-changed-extensions-bundle-3`, 180s hook timeout):
   - Also fails on the unrelated PR #169026 (CI run 38137511377).
   - Passes locally (2/2) on this head, on clean `origin/main` `ff6f58a8c32`, and on this branch merged with that main.
   - This PR touches no `extensions/codex` files.

Two other failures were flaky: `build-artifacts` (`sqlite-sessions-transcripts-flip-proof.built-cli`) and `gateway-completion-replay`. Each passed on rerun, and each passes locally after `pnpm build` on this head.

Co-authored-by: roboclaw-bot <[email protected]>
Co-authored-by: Dallin Romney <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…168981)

## What Problem This Solves

Agent runtime bookkeeping repeatedly restarted otherwise valid work when configuration, plugin, or catalog metadata changed during an asynchronous operation. This maintainer-requested simplification removes that speculative retry machinery.

## User Impact

Normal model selection, tool execution, credential checks, FIFO scheduling, and shutdown settlement remain. A request racing a reload may fail visibly and be retried by the caller; passive metadata may remain at its captured version until the next refresh. No configuration, protocol, SDK, schema, durability, retention, or permission contract changes.

## Why This Change Was Made

Prepared runtime acquisition and remote catalog adoption now take one preparation path rather than repeatedly rebinding and rebuilding. Admission still handles the concrete drain, retirement, and failed-activation recovery stages. Cache publication keeps its final currentness check; tool and credential effects keep their authority checks. Steering and Tool Search retain their actual owner, FIFO, and settlement contracts without comparing unrelated metadata.

Production: **519 net lines removed**. Tests that exclusively required the removed synthetic interleavings were removed with them. Open-parent borrowing, pending-auth cancellation, explicit MCP acquisition config, and queued-tool implementation checks remain. No new lint suppressions, timeouts, retries, or skips were added.

Scope proof also caught two nearby correctness issues: an earlier MCP reload could overwrite a new caller's explicit configuration, and snapshot reconciliation could prepend a separator to a later text block. Both are fixed with their existing boundary tests. Bootstrap fixtures now test the no-clobber fallback already shipped by the pinned fs-safe version; no dependency or storage policy changed.

## Best-effort tradeoffs accepted

| Removed guard | Provenance and accepted result |
| --- | --- |
| Per-batch context projection cancellation | openclaw#119607 measured the value of cooperative yielding; its mid-batch cancellation callbacks were synthetic coverage. Yielding and the final publication check stay; obsolete pure computation may finish unused. |
| Mixed-version module/cache repair | openclaw#119607 seeded an old global singleton inside a synthetic process. Normal upgrades restart the process; unsupported mixed-version module replacement no longer repairs that marker. |
| Runtime acquisition retry/rebind loop | openclaw#128138/openclaw#127217 exercised forced reload timing. A racing request now returns a visible supersession error; the next request uses the current owner. The actual no-spin incident in openclaw#153313 remains addressed. |
| Configured-generation re-admission | 8b13535 / openclaw#168410 adds re-admission for a gated Docker reproduction with a catalog publication 0.3s after admission, not a human-user incident. A superseded request now fails visibly. Parent confinement remains fail-closed, with its security test retained. The retry-only WeakSet and two retry-specific tests are removed. |
| Repeated passive owner selection | d92dc37 / openclaw#162484 added recursion alongside the real self-drain fix; that incident did not require recursive reselection. The self-drain refusal stays. Reads use one captured owner or fail visibly, rather than recursively trying later publications. |
| Remote catalog config reread/per-attempt cancellation | openclaw#158000 used synthetic config/auth churn. Adoption reads once and prepares once; an overlapping change can defer adoption until the next normal catalog check. |
| Parent-generation cancellation subscriptions during adoption | 27a0f6d / openclaw#158000 used the same synthetic churn. Parent replacement may leave bounded preparation running until its final owner/config check rejects it. Shutdown cancellation, candidate-retirement aborts, cleanup, and the final serialized effect check remain. |
| Three-attempt catalog adoption settlement recovery | The same synthetic churn caused a second retry protocol around owner publication. One attempt remains, with one final checked atomic rows/pricing commit. |
| Duplicate early publication checks/error relabeling | Same-tick checks and concurrent-change relabeling did not guard an effect. The final effect check stays; failures retain their actual reason. |
| Auth-batch sibling retry after supersession | 4616d20 / openclaw#152467 used synthetic tests that superseded one owner during a sibling build. The operation now settles with its original error instead of selectively rebuilding siblings. Credential authority checks remain. |
| Post-await cache-stale generation check | No human incident supports fencing this metadata flag. A config/auth change during discovery can let the older load clear a reused owner's stale marker; discovery may remain stale until another explicit refresh/reload. This does not grant credentials or execution authority. |
| Passive harness catalog cancellation | openclaw#134524 fixed the actual availability report openclaw#134460; replacement/closure guards were additional synthetic hardening. Completed discovery rows are retained, and later discovery observes replacement. |
| Native binding clock-only rechecks after worker waits | openclaw#158396 used clock-jump fixtures. An expired but unreplaced exact row can finish its prepared bookkeeping mutation; CAS takeover detection and current mutation authority still gate commit. One exact, unexpired lease check gates protected callback entry, and live effect assertions remain. |
| Tool Search ancestor reentrancy tracking | openclaw#140767 covered synthetic nested control calls, not a reachable production control target. FIFO/exclusion and real implementation settlement remain. |
| Complete steering metadata fingerprint | openclaw#163195 recorded a real production ordering/ownership incident. Its owner, pending-row, result-authority, and lease checks stay; metadata-only edits no longer invalidate already-captured prompt bytes. |
| Repeated MCP acquisition/reload replay | openclaw#138694 used synthetic crossed-publication choreography. A new runtime catches up once; later reloads target the published owner. A racing creation can fail and reconnect on the next acquisition. |
| MCP tools/list invalidation generations and replay | openclaw#125541/openclaw#125564 describe isolated protocol stress fixtures. A notification inside tools/list no longer triggers immediate replay; the next notification or explicit refresh replaces the inventory. Normal exit/reconnect, bounds, validation, and cleanup remain. |
| Failed-start replay crossed by config publication | openclaw#158088's test forces a config publication into an in-flight failed initialization. That request may now report its first failure; ordinary backoff and explicit-refresh retry remain. |

## Evidence

Candidate head: `d72afea0c17a45c677977e23937049d7c7fc43ec` (tree `51daca08d7288e906188bc25ec3d1896bf841349`).

Final exact-head CI: [run 38132644989](https://github.com/openclaw/openclaw/actions/runs/38132644989) completed successfully; all 82 jobs terminal with no failed or cancelled jobs. Full head-bound check census also confirms the CI gate and applicable security checks passed. Earlier failed/cancelled attempts are described below, not represented as passing proof.

- Independent P2 reviews completed. The catalog-staleness, duplicate steering metadata fingerprint, and auth-sibling retry findings are explicitly accepted tradeoffs listed above; steering result facts and destination eligibility remain checked at their owners. The latest native-lease callback-entry finding was accepted and fixed with one live lease check instead of restoring per-write expiry callbacks. Its new fake-clock regression failed before the fix by entering the protected callback after expiry.
- Conflict-only integration kept main's three repaired test fixtures byte-for-byte. All **22 conflict tests** passed (cursor, sandbox, bootstrap publication, lint suppressions); affected root/tools test graphs, core types, typed lint and both cycle checks passed. Runtime and Madge cycles remain **0**.
- The native callback-entry fix passed fresh P2 review and **24 focused tests** (21 native binding tests plus 3 lint-suppression tests), wrapper 212.01s; native test project 164.77s including 113.11s compiled-worker preparation. The added fake-clock case performs no real wait; the existing native suite exercises authority and worker settlement. Final affected types and typed lint are checked before push.
- CI run `38125430266` found one owned stale expectation: the remote-catalog integration still forced config/auth replacement while pricing was paused and demanded the removed immediate retry. Only that scenario was removed; both schema variants retain normal publication, pinned pricing, input validation, worker recovery and disable coverage and pass locally (141.35s project), with gateway test types, typed lint, lint suppressions (3/3), and fresh P2 review passing.
- The other root failure, `checks-node-changed-compact-small-11`, independently reproduced on clean main `8d45488ae2075bd14a50c881aff6e18c32182538`: `embedded-agent-runner.prompt-cache.test.ts` responses and in-history both raised `SqliteTranscriptMutationConflictError` in the session actor append path (2 failed / 2 passed). Investigation found a cold actor snapshot prevented the existing implicit-watermark retry. Fixed directly on main as `0fa340c21f484740ec7b4ed1169b7b02439aa970` and integrated here: all 4 prompt-cache cases and 35 session-manager siblings plus lint-suppressions pass, including explicit stale rewrite refusal. The repair passed types, typed lint and fresh P2 review.
- Follow-up CI `38127338915` reached one more synthetic-only case: compaction's `mutate=input` row changes an internal selection object after starting acquisition. Removed only that row/branch under the campaign rule; five remaining compaction cases pass, along with lint-suppressions, affected types, typed lint and fresh P2 review. Its provenance is `44d905388f9` / openclaw#139429, not a human report of post-call input mutation. The final conflict repair keeps main's equivalent streaming/steering refactors, removes the obsolete retry predicate, and passes 49 owner tests plus lint-suppressions. Cancelled jobs are not counted as passing; final-head hosted CI remains the gate. No CI job was rerun.
- CI `38130432441` had one inherited fixture failure: three `sessions-mutations.catalog-queue` cases selected their configured default while expecting override fields, after openclaw#169030 intentionally made that selection a default reset. Integrated main's existing fixture-only correction `a8ef16f77650`, retaining all assertions. The corrected file passes all 14 cases on clean main under Node and Bun; the three affected cases also pass under Bun on this branch (249.87s project, mostly transformation). Exact-head hosted CI remains the final gate.
- Focused effects suites: **43 passed** across inbound-registry, remote-publication, hot-reload-dispatch and tool-search-scheduling. This includes cancellation, parent confinement, ordinary rollback/failed-activation recovery, and queued implementation replacement. Single-worker wrapper 752.15s including 142.017s compiled-worker preparation; infra 432.15s and agents-core 115.09s. Final restored remote-publication file: **7 passed**, including first reply crossing catalog adoption and exact derived-parent confinement; wrapper 372.77s (184.30s worker preparation; 131.87s Vitest). These loaded-host timings are not a performance claim.
- Integrated native-binding suites: **20 passed**, including exact token cleanup, successor protection, and revocation. The same command passed all **3 lint-suppression tests**. Single-worker wrapper 354.47s including 145.31s worker preparation.
- Current core types and native-binding test graph passed; runtime cycles **0**, Madge cycles **0**; changed-file typed lint passed. The full changed-check run reached an old-base UI duplicate-import error already fixed on main by `ef175b247c9`; that fix was integrated and the affected UI graph passed. Remaining type graphs and static guards were completed separately without changing baselines.
- Isolated Linux scope run and canonical remaining projects exercised **19,900 passing tests**. Eight failures were investigated: three pinned removed synthetic retry paths and were deleted; five exposed the correctness/fixture issues described above and were repaired with focused proof. Existing platform skips were unchanged. This is combined incremental proof, not a claim that one final-head all-scope invocation was green.
- Final repair suites: **71 passed** across passive runtime, SSE recovery, startup backoff, bootstrap, stream reconciliation/markup/phase coverage; **12 passed** across sandbox/cursor coverage, followed by **2 passed** for the real-append cursor fixture. Final MCP regression retained stdio-exit recovery and HTTP failure semantics; it passed 64 cases but hit two unchanged local child-start deadlines (1s/2s). Those initial-start paths passed on the isolated Linux run; no timeout, retry, or skip was changed to mask the local failures.
- Full-core Linux lint passed with 13 existing max-lines warnings, none in changed files. Deadcode identified and drove removal of the unused owner-publication helper. Remaining findings were in unmodified config/state/Gateway/UI files. A separate fresh current-main checkout (`401216ac50`) passed production deadcode and failed full-tree deadcode only on the unrelated `readActiveGatewayLockPortMock` export. The PR does not change any deadcode baseline.
- Blacksmith Testbox did not admit a runner within 15 minutes; AWS quota pressure supplied an undersized instance, which was released. The authorized Hetzner fallback supplied the Linux proof above. All owned remote leases are stopped. Hosted CI on the exact final head remains the landing gate; no CI jobs were rerun.

<details>
<summary>Audit coverage ledger and retained boundaries</summary>

| Mechanism (base lines) | Scenario and provenance | Decision |
| --- | --- | --- |
| context-cache-projection.ts:145-213, context.ts:87-109,146-169 | Cancellation/replacement during pure batched metadata computation. 0dd154f / openclaw#119607 fixed a measured multi-second RPC stall by yielding and atomic publication. Mid-batch authority callbacks were extra cancellation machinery; no effect occurs in projection. | REMOVE repeated projection/early checks; KEEP cooperative yields and the caller's check immediately before publication. |
| context-runtime-state.ts:33-38 | 0dd154f / openclaw#119607 seeds an old global singleton and new cache module in a synthetic child process; no human report of mixed code versions within one live process. | REMOVE old-module/cache-pair normalization, its only reuse flag, and the synthetic migration test. Ordinary process startup and same-version bundled singleton sharing remain. |
| prepared-model-runtime-lease.ts:149-164 | 9505286 / openclaw#153386. Human report openclaw#153313 by stackingrockss includes the deployed Docker version, profiler samples, and repeated boot-loop observations. Its infinite retry was caused by non-idempotent runtime selection normalization. | KEEP normalized owner selection and a visible error when a settled replacement never published; REMOVE the acquisition retry loop entirely, so it cannot spin. |
| prepared-model-catalog-worker.ts:71-220 | 9d58cf2 / openclaw#150354. Human report openclaw#149538 by 609NFT describes copied production fleet state, 632 agents, 504 failed health probes and growing RSS. openclaw#161738 by matthematics1137 reports 92 worker lifetimes, OOMs and 1.285 TB written. | KEEP one bounded shared worker, borrower cleanup, failure logging, and ordinary crash recovery. These are measured resource and real concurrency contracts, not permission to retain unrelated reload fences. |
| prepared-model-runtime.refresh-scope.ts:240 | 3e7ca30 / openclaw#151597 by obviyus describes a controlled worker crash and synthetic Gateway regression, not a human production report. Later openclaw#161738 independently establishes actual recurring worker failures. | KEEP source-bound failure reporting and bounded recovery to avoid reintroducing the observed restart/discovery amplification. The openclaw#151597 PR alone is not accepted incident evidence. |
| prepared-model-runtime.resources.ts:30-127 | d70d026 / openclaw#143109 contains native regressions and synthetic compiled CLI/Gateway proof, no linked human incident. | KEEP physical resource claims until ordinary concurrent borrowers settle and shutdown joins their cleanup; these are required cleanup mechanics, not a blanket historical-incident exemption. Inspected the complete resource owner; no extra reload retry protocol lives here. |
| prepared-model-runtime.plugin-lifetime.ts:230-319 | 1233536 / openclaw#159448 links openclaw#157842 by highfly-hi: five-agent Linux deployment with catalog-worker heap increasing 70-80 MB per scheduled turn, watchdog restarts and before/after version evidence. | KEEP final registry-reference release, current execution authority, and ordinary borrowed-resource settlement. Retained memory claims are scoped to physical lifecycle, not all historical publication machinery. |
| prepared-model-runtime.lifecycle.ts:101-164 | d92dc37 / openclaw#162484 by jalehman records actual lossless-claw maintenance calls stuck about 45 minutes during reload until restart. 1f3038b / openclaw#162301 explicitly says synthetic Gateway, no production deployment. | KEEP refusal of plugin work waiting on its own drain and process-close settlement. openclaw#162301 is synthetic evidence, not an independent incident exemption. |
| prepared-model-runtime-lease.ts acquisition loop and borrowed-generation branch | 1977a39 / openclaw#128138 and related openclaw#127217 describe synthetic QA-channel/config replacement tests; openclaw#127217 explicitly reports that its pre-fix real-Gateway run still delivered replies. Retained inbound-registry tests exposed ordinary nested selected-parent borrowing as a distinct contract. | REMOVE retry/rebind loop. KEEP exact open-parent borrowing and selection confinement; a reload during new acquisition may fail that request visibly. |
| prepared-model-runtime.published-owner.ts:91-203 | d92dc37 / openclaw#162484 added retry/recursive rereads alongside the real plugin-drain repair. That incident justifies self-drain refusal and ordinary settlement, not recursive passive owner reselection. | REMOVE repeated rereads/retries; wait once, then project or activate once. Pure catalog-stale bookkeeping no longer revalidates generation after its await. |
| prepared-model-runtime.configured-refresh.ts remote catalog adoption | 27a0f6d / openclaw#158000 has explicitly synthetic config/auth churn and fixture-provider proof; no human incident cited for the reread loop, per-attempt controllers or three-attempt owner settlement recovery. | REMOVE those race-specific retries, plus early duplicate currentness checks/error relabeling. KEEP the final owner/authority check, atomic rows/pricing commit, current catalog ordering, and ordinary cancellation/disposal. |
| prepared-model-runtime.configured-refresh.ts:396-430 parent subscriptions | 27a0f6d / openclaw#158000; same synthetic churn proof. Parent-generation subscriptions duplicate the final owner/generation/config check. | REMOVE parent-generation early cancellation listeners. KEEP shutdown and candidate-retirement cancellation, bounded work, cleanup, and the final serialized effect check. |
| prepared-model-runtime.owner.ts:612-631 batch supersession retry | 4616d20 / openclaw#152467. Tests force one auth owner to supersede while a sibling is building. No independent human incident identified for sibling retry. | REMOVE retry of the surviving batch; retain source-bound credential/current-owner checks and report the original publication failure. |
| prepared-model-runtime.owner.ts:124-134 unused publication probe | e56f825 / openclaw#130856 introduced a helper returning matching/pending publication facts for acquisition retries. Its callers are gone; full-repository search finds only the definition. | REMOVE the dead helper/export. Credential-refresh cancellation remains supported by the direct, abortable configured-owner wait and its unchanged regression tests. |
| sandbox/registry.kernel.ts:396,420; sandbox/registry.ts:295 | 5c7e44c / openclaw#151172 is not treated as an incident report. Read-only admission accepts older schemas; tableExists consumes admitted schema.tables facts, not repeated SQL/format validation. | KEEP the existing absent-table empty/null contract. No runtime foreign-commit or repeated validation probe exists in these calls. |
| harness/native-session/binding-leases.ts | b272376 / openclaw#158396 moved writes to workers; elapsed-time rechecks were covered by synthetic clock-jump tests. ffd0759 / openclaw#164197 supplies native successor authority behavior, not a blanket exemption. | REMOVE prepared callback plumbing and post-worker wall-clock-only rechecks. KEEP exact-row CAS, token/phase/failure checks, current mutation authority, bounded acquisition, renewal, and write settlement. |
| harness/context-engine-logical-turn.ts | openclaw#143491/openclaw#140023 supply synthetic lifecycle tests, not qualifying human incident evidence. The owner actually holds resources used by outstanding context-engine work. | KEEP ordinary work completion and deferred disposal until implementation settlement; no extra synthetic reload retry was retained here. |
| harness/model-catalog.ts:168-177,242-284,353 | 01fd244 / openclaw#134524 repairs human availability report openclaw#134460. Passive replacement/closure branches were additional maintainer hardening and synthetic variants, not that report's failure. | REMOVE passive isCurrent callbacks and ambient registry replacement checks. KEEP exact owned registry/config, provider outcomes, discovery, selection and the actual availability repair. |
| auth-profiles/oauth-refresh-peers.ts | openclaw#166183/openclaw#167002/openclaw#166659 are not claimed as human incident evidence. Refresh credentials rotate/revoke and carry account identity; copied historical peers must not replay spent tokens or inherit another account. | KEEP these credential/identity effect boundaries and ordinary uncertain-write settlement. No auth-profile schema, secrets, permissions or durability changes. |
| worktrees lifecycle/removal | Audited run-lease-owner.ts, service-preparation.ts, eviction.runtime.ts and gc-removal.ts. They coordinate destructive removal of user artifacts with live checkout/source handles, exact refs and ordinary parallel sessions. No PR title is treated as incident evidence. | KEEP current-row removal/exclusive source checks and rollback/cleanup custody for writes and deletion. Removing them would risk user artifacts, independently prohibited by the data-loss boundary. |
| tool-search-scheduling.ts | 49f8d29 / openclaw#140767 adds ancestry reentrancy and queued object/mode identity checks with automated interactive/headless regressions. Production catalogs exclude control tools; recursive calls using the same runtime were synthetic only. | REMOVE unreachable nested-call ancestry. KEEP one exact queued implementation/mode check at the effect, catalog-ID authorization, FIFO/exclusion, abort and implementation settlement. |
| agent-steering-queue.ts:194-263 | 94acbe6 / openclaw#163195 records Peter's actual three-day production errors. The incident justifies owner/FIFO repair, not a fingerprint of every result label/task/time/outcome/origin/transcript field. | REMOVE full payload fingerprints and deep-equality invalidation. KEEP run-owner identity, prepared result authority, current requester store, pending-row effect checks, FIFO, exact lease/status acknowledgment and release. |
| agent-bundle-mcp-manager.ts and manager-install.ts | 1d60d3d / openclaw#138694 reports synthetic fail-before/real-transport proof but no cited actual-use incident for repeated crossed-publication acquisition/reload. | REMOVE the acquisition retry/rebind loop and repeated reload replay. KEEP the runtime-key queue, ordinary cleanup, one postcreation config catchup, requester credentials/authorization and live tool effect checks. |
| agent-bundle-mcp-runtime.ts catalog generations | 140dbbd / openclaw#125564 and follow-up 0818bcb / openclaw#167642 have synthetic notifications/listing interleavings, not human reports for replaying tools/list during its own response. | REMOVE catalog invalidation generations, replay of a notification arriving inside tools/list, and the impossible repeated replacement-retirement loop. KEEP listing single-flight, caching, bounds, diagnostics, normal reconnect, one retry for an actually exited previously healthy server, and execution authority. |
| prepared-model-runtime-lease.ts / plugin-lifetime.ts configured-generation re-admission | 8b13535 / openclaw#168410, landed during this lane, describes a gated Docker reproduction with catalog publication 0.3s after admission, not an actual human-user incident. | REMOVE configured-generation retry and its now-unused WeakSet plus the two retry-only tests. KEEP fail-closed superseded-generation rejection and the new derived-parent confinement security test. |

</details>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…mpaction V2) (openclaw#168401)

Closes openclaw#168088. Related: openclaw#168164.

## What Problem This Solves

With ChatGPT sign-in, every automatic compaction in OpenClaw ran a client-side summary: separate summarization requests with 0 cached tokens, and a lossy text summary in place of the conversation. Codex compacts the same route server-side ("remote compaction V2"): the next normal model request carries a trailing `{"type":"compaction_trigger"}` item, and the provider returns one opaque `compaction` item that stands in for the history.

## Fix

- **Request:** automatic compaction on the ChatGPT route (preflight before a turn, and mid-turn between tool rounds) sends V2 as the next normal request, through the same attempt pipeline and native ChatGPT stream, with `compaction_trigger` appended last. Tools, instructions, parameters, cache key and the full input prefix are the turn's own, so the compaction request reads the warm prompt cache.
- **Result:** exactly one non-empty `compaction` item is accepted, only after a successful terminal response and never after an abort. Collection resets for each provider attempt.
- **Checkpoint:** real user messages are retained newest-first within 64k tokens, plus the item, matching Codex `compact_remote_v2.rs`. Users retained from an earlier window stay eligible, so repeated compactions keep them.
- **Fallback:** every fallback to client compaction logs a WARN with its reason. Overflow recovery, `/compact <focus>` and manual `/compact` stay client-side; manual V2 needs session-writer ownership work and is a follow-up.
- **Fixed during live testing** (each with a regression that fails on the defect):
  1. V2 never ran: the compact request was checked before the async provider adapter dispatched it.
  2. V2 ran only in the managed client; real ChatGPT turns use the native stream. V2 now runs there.
  3. Replay normalization dropped the checkpoint turn as an empty failed turn, so the next request grew back to full history. It now keeps successful compaction checkpoints; error turns and suppression markers are still dropped.

## User Impact

ChatGPT sign-in sessions compact server-side with no extra summarization requests. Compaction reads 87–100% of its input from cache, and later turns stay at about 14–22k input tokens instead of about 91k. `params.responsesCompactEndpoint: false` turns it off.

## Evidence

Live, real ChatGPT OAuth login, `openai/gpt-6-astra`, isolated Gateway, synthetic corpus, three facts seeded before compaction. The host was loaded, so wall times are upper bounds.

| Compaction | Compaction input / cached / output | Wall | Input before → after | Next user turn input / cached | Recall |
|---|---:|---:|---:|---:|---:|
| Preflight | 90,999 / 73,856 / 885 | 20.2 s | 90,999 → 22,308 | 22,439 / 22,144 | 3/3 |
| Mid-turn, first | 91,075 / 82,560 / 575 | 12.3 s | 91,075 → 13,904 | 14,121 / 12,928 | 3/3 |
| Mid-turn, second | 76,486 / 58,880 / 716 | 17.4 s | 76,486 → 14,476 | 14,709 / 14,336 | 3/3 |

Request parity, compaction request vs the preceding normal turn:

| Compaction | Tools | Instruction chars | Input prefix | Cached vs previous input |
|---|---|---|---|---:|
| Preflight | 6 → 6 | 35,857 → 35,857 | 26/26 items identical | 89.3% |
| Mid-turn, first | 6 → 6 | 35,855 → 35,855 | 26/26 items identical | 99.8% |
| Mid-turn, second | 6 → 6 | 35,855 → 35,855 | 39/39 items identical | 86.7% |

The tool schemas, instructions, parameters and cache-key hashes were identical in all three. The final head sent exactly 3 `compaction_trigger` requests, all HTTP 200, and no client-summary requests.

**Client comparison (same route, before this change):** one client compaction of a 117.9k-token session took two summary calls (9,777 input, 0 cached, 961 output, 24.4 s). The next turn read 33,967 input with 12,800 cached. Trigger points were not matched to the V2 runs, so this is a reference, not a head-to-head benchmark.

**Tests:** fetch-boundary regressions across the managed and native ChatGPT streams cover:
- request parity;
- failed, cancelled and incomplete terminal responses;
- aborts;
- duplicate or empty items;
- multilingual retention;
- two consecutive persisted compactions;
- the async-dispatch case and replay normalization through the real `SessionManager`.

Negative controls fail on each defect. tsgo core/src/packages pass; `check-changed` passes.


## Release-landing follow-ups (2026.10.2)

- **ClawSweeper P2 fix (budget anchor), commit e902124:** V2 used to price the outgoing request with the conservative preflight estimator. That estimator counts unchanged instructions twice, because measured usage already includes them. The V2 boundary now uses the same accounting as the mid-turn precheck it replaces:
  - The shared code is `resolveProjectedRequestPressure`, split out of `checkMidTurnPrecheck`.
  - The stream guard's request observation now returns the matching measured predecessor. The foreground request is observed before V2 decides, so both price the same anchor. A checkpoint request is then observed again as its own request.
  - Requests with no anchor keep the conservative estimate.
  - Regression test: `chatgpt-v2-compaction.test.ts` "prices a matching measured prefix once before deciding to compact". It uses the 15,000-token / 12,000-char / 24,576 numbers from `attempt-midturn-precheck.test.ts`. It fails on the previous head (the boundary throws `MidTurnPrecheckSignal`) and passes now.
  - Production LOC: +45/-27. Most of that is the function split plus contract comments.
- **Test-only fixture fix, commit 018c9bc:** three Gateway e2e fixtures counted the labeled `OpenClaw runtime context:` carrier as a user turn: `gateway-rpc-chat`, `gateway-provider-review-product-proof` and `gateway-completion-replay`. These fail the same way on `main` (openclaw#168843; same fix as openclaw#168961).
- **Rollback to v2026.10.1:** that release's replay normalization drops the empty, zero-usage V2 checkpoint carrier. The raw transcript is never rewritten, so v2026.10.1 replays the full raw history, and its own client compaction applies if that history is too large. Rollback loses no data; it just loses the provider checkpoint. The stored checkpoint format already shipped in v2026.10.1, and its reader ignores the added optional `outputTokens` (details in the compatibility comment).

### Unrelated failures that also happen on `main` (proof scoped to the tests involved)

Both failures reproduce on a clean `origin/main` checkout at `02040ecbc92` with no PR code. Checking out commits around one change shows that both start at 9657a374 (openclaw#168539, "route transcript appends through the session actor"):

| Test | `9657a374^` | `9657a374` | `origin/main` `02040ecbc92` |
|---|---|---|---|
| `src/agents/embedded-agent-runner.prompt-cache.test.ts` | 4/4 pass | 2 fail (`SqliteTranscriptMutationConflictError` from `appendSessionManagerActor`) | 2 fail |
| `test/gateway-steer-fifo.e2e.test.ts` | 7/7 pass | 3 fail (1 model request where 2 are expected) | 3 fail |

- openclaw#168981 independently reports the prompt-cache failure on clean main.
- openclaw#169006 (steering diagnostics) landed and did not fix the steer-fifo failures.
- CI selects these tests for this PR only through the shared embedded-runner files. Neither failing path is touched here.

### Local proof on the current head

All runs below were local and focused on the touched files:
- `chatgpt-v2-compaction`: 13/13.
- The other affected `src/agents/embedded-agent-runner/run/` unit files: 208/208. These are `attempt-midturn-precheck`, `attempt-prompt-submit.*`, `attempt-stream-*`, `preemptive-compaction*`, `attempt-execution-phase`, `attempt-prompt-preflight` and `attempt-context-guards`.
- `agent-runner.runreplyagent.e2e`: 231/231.
- The 3 repaired Gateway e2e files: all passed.
- `node scripts/check-changed.mjs -- <touched files>` exited 0. That run includes `tsgo` for core and core tests.
- Codex protocol check (read directly in `../codex`): `codex-rs/core/src/compact_remote_v2_attempt.rs:70-84` and `compact_remote_v2.rs:65,398-450`.


### Unrelated failures on the current head (b3a7405, which merges `origin/main` at `3dc543d9ee8`)

The two failures above (prompt-cache and steer-fifo) no longer fail on this head; main has since landed actor-append fixes. Two other unrelated failures remain:

1. **`src/agents/embedded-agent-runner/run.harness-auth-failover.test.ts`** (5 tests, `checks-node-changed-compact-large-4`):
   - Fails the same way on a clean `origin/main` checkout at `3dc543d9ee8`, and passes at `596e31d1764` (10/10).
   - `git bisect` names `70e895e21606` as the first bad commit: openclaw#168992, "perf(agents): reduce repeated SQLite work during agent preparation".
   - This PR does not touch native harness auth.
2. **`extensions/codex/src/app-server/run-attempt.steering-settlement.test.ts`** (`checks-node-changed-extensions-bundle-3`, 180s hook timeout):
   - Also fails on the unrelated PR openclaw#169026 (CI run 38137511377).
   - Passes locally (2/2) on this head, on clean `origin/main` `3dc543d9ee8`, and on this branch merged with that main.
   - This PR touches no `extensions/codex` files.

Two other failures were flaky: `build-artifacts` (`sqlite-sessions-transcripts-flip-proof.built-cli`) and `gateway-completion-replay`. Each passed on rerun, and each passes locally after `pnpm build` on this head.

Co-authored-by: roboclaw-bot <[email protected]>
Co-authored-by: Dallin Romney <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 19, 2026
First-parent upstream 069a5b8..75df19c (17 commits, including
openclaw#169043 entry lifecycle queries, openclaw#169034, openclaw#169058 memory index facts,
openclaw#168950, openclaw#169019 telegram queued history replies, openclaw#168790/openclaw#168756/
openclaw#168759/openclaw#168739 Solid UI ports, openclaw#168813 codex metadata/startup
lifecycles, openclaw#168981, openclaw#168992 agent preparation SQLite work).

Only conflict: worker-access inventory, regenerated (631 files, 2436
calls). Auto-merged files carrying our overlay, reviewed: snapshot.ts
(upstream's block-reply reconcile reads through index-1; our per-part
continuation-marker strip in extractAssistantStreamSnapshot unchanged),
codex side-question.ts (upstream's request-scoped client lease; our
disableContinuationTools and the extracted dynamic-tool-call helper
unaffected), subagent-registry-restore.ts, session-sharing-store.native.ts.

Refs #1475

Co-Authored-By: Claude Opus 5.5 <[email protected]>
obviyus added a commit that referenced this pull request Nov 20, 2026
…turns (#202583)

## What Problem This Solves

Changing `models.catalogRefresh.url` (or `.enabled`) on a running Gateway waited up to six hours for the next scheduled catalog check, so a model the new catalog describes stayed unlisted and its turns were priced at $0.

The obvious fix, re-arming the catalog check from the config listener (part 3 of #202490, reverted), broke worse. The check ran inside the hot reload that published the config. The Gateway scheduler keeps the async context of whoever schedules a job, and the reload runs inside a plugin lifecycle operation with its own plugin cache, which retires when the reload ends. The catalog adoption then built its plugin generation from that short-lived inventory:

- inventory retired during the build: `PluginInventoryRetiredError` ("check failed") or a rejected candidate ("superseded"), then a 6-hour wait;
- inventory retired after the adoption committed: the published owner was retired with it, and every later turn failed with `UNAVAILABLE: prepared reply dispatch runtime owner was not published for main` until restart;
- every later scheduled check chained from the same retired context and failed again. In the reverted branch this showed up as the 10-second retry failing with an `AbortError`.

## Timeline of one wedged run

Probe build (main plus the naive re-check), one Gateway, URL change at t=10.49 s:

| t (s) | Step | Source (main 569c60b) |
|---|---|---|
| 10.49 | The `config.patch` reload runs in the plugin lifecycle lease, which installs an operation-scoped plugin cache | `gateway/config-reload.ts:1007`, `plugins/plugin-lifecycle-lease.ts:356` |
| 10.498 | The runtime config is set and `sessionChanges.emit` fires inside that context. The update owner's listener re-arms the catalog check. `GatewayScheduler` snapshots the registrant's context | `config/runtime-snapshot.ts:272`, `infra/update-startup-scheduler.ts:90`, `infra/gateway-scheduler.ts:190` |
| 10.499 / 10.504 | Reload commit marks prepared runtimes stale (R1), then its refresh supersedes R1 with R2 | `gateway/server-reload-hot.ts:280`, `:596` → `agents/prepared-model-runtime.ts:519` |
| 11.197 | The fetch is done; the adoption waits for R2 | `agents/prepared-model-runtime.configured-refresh.ts:97-101` |
| 11.271 | The reload commits R2 and reply dispatch publishes `main` (generation 5) | `agents/prepared-model-runtime.ts:580` |
| 11.272 | The adoption claims generation 5 and builds candidates. Their plugin metadata belongs to the reload's operation cache | `configured-refresh.ts:256-298`, `plugins/plugin-cache.ts:315` |
| 12.791 | The reload operation ends; its cache retires | `gateway/config-reload.ts:470`, `plugins/plugin-lifecycle-lease.ts:128` |
| 14.336 | The adoption commits generation 6: "remote model catalog applied" | `configured-refresh.ts:363-373` |
| after | Cache retirement retires the published owner (needs refresh, no plugin generation). No recovery runs, because it was not a Gateway loan | `agents/prepared-model-runtime.plugin-lifetime.ts:390`, `:407-425` |
| 41.858 | Turn: owner mismatch → `UNAVAILABLE ... runtime owner was not published for main` | `agents/prepared-reply-dispatch-runtime.ts:179-188` |

The stale mark and the pending replacement were not the cause. The adoption waited correctly for R2 and claimed fresh owners. What broke it was where the check ran, not when.

## Fix

One owner: the update-check scheduler.

- When `models.catalogRefresh` changes, the config listener re-arms the existing catalog check. It does not add a second scheduler.
- Re-arms from the listener run in the update owner's own context, taken from `AsyncLocalStorage.snapshot()` at `start()`, not in the publishing reload's context. The catalog check and every later re-arm use the Gateway's plugin inventory, the same one the startup check uses.

No change to the adoption, the stale mark or reply dispatch. The four symptom patches from #202490 (10-second superseded retry, `PluginInventoryRetiredError` → superseded, captured cancel signal, docs) stay reverted. None of them is needed, and none was added back.

Accepted edge case: an unrelated model-affecting reload that lands while an adoption is building still defers that adoption to the next scheduled check, as on `main` (#168981 removed adoption retries on purpose). A further `catalogRefresh` change re-arms at once.

## Evidence

Regression tests (`src/agents/prepared-model-runtime.catalog-source-change.test.ts`) run the real update owner, the real scheduler and the real adoption. The config notification fires inside a reload-style plugin operation, and each test retires that operation's inventory at the point where production failed. Explicit gates, no sleeps.

| Case | main | main + naive re-check | this PR |
|---|---|---|---|
| reload operation ends during the build | red: no re-check | red: `superseded` | green |
| reload operation ended before the check ran | red: no re-check | red: `Plugin inventory has retired; begin a new plugin operation.` | green |
| reply dispatch after the operation ends | red: no re-check | red: `prepared reply dispatch runtime owner was not published for default` | green |
| next scheduled check after the operation ends | red: no re-check | red: `superseded` | green |

Real Gateway (isolated state, loopback catalog and Together mock, `cadence2`: Gateway running on catalog A, then the URL is changed to catalog C, which describes `together/zz-lab/zz-day0-live`):

**This PR** (exact head `11ac3c2d`), 20 of 20 runs: the catalog was adopted 0.6–13.9 s after the URL change (host load average around 70), the new row was listed, every turn succeeded with a price, and no run showed `UNAVAILABLE`.

| run | URL change → outcome (s) | catalog check | Together listing | turn | cost | UNAVAILABLE |
|---|---|---|---|---|---|---|
| 1 | 2.5 | remote model catalog applied | listed | ok | $0.00006 | no |
| 2 | 2.1 | remote model catalog applied | listed | ok | $0.00006 | no |
| 3 | 13.9 | remote model catalog applied | listed | ok | $0.00006 | no |
| 4 | 1.8 | remote model catalog applied | listed | ok | $0.00006 | no |
| 5 | 1.3 | remote model catalog applied | listed | ok | $0.00006 | no |
| 6 | 2.9 | remote model catalog applied | listed | ok | $0.00006 | no |
| 7 | 8.6 | remote model catalog applied | listed | ok | $0.00006 | no |
| 8 | 5.0 | remote model catalog applied | listed | ok | $0.00006 | no |
| 9 | 3.4 | remote model catalog applied | listed | ok | $0.00006 | no |
| 10 | 3.5 | remote model catalog applied | listed | ok | $0.00006 | no |
| 11 | 0.7 | remote model catalog applied | listed | ok | $0.00006 | no |
| 12 | 0.7 | remote model catalog applied | listed | ok | $0.00006 | no |
| 13 | 0.6 | remote model catalog applied | listed | ok | $0.00006 | no |
| 14 | 0.9 | remote model catalog applied | listed | ok | $0.00006 | no |
| 15 | 0.7 | remote model catalog applied | listed | ok | $0.00006 | no |
| 16 | 0.7 | remote model catalog applied | listed | ok | $0.00006 | no |
| 17 | 6.8 | remote model catalog applied | listed | ok | $0.00006 | no |
| 18 | 0.8 | remote model catalog applied | listed | ok | $0.00006 | no |
| 19 | 1.3 | remote model catalog applied | listed | ok | $0.00006 | no |
| 20 | 1.1 | remote model catalog applied | listed | ok | $0.00006 | no |

**main** (`569c60bc`), 5 runs: no check after the URL change; the next check comes in 6 h. The row stayed unlisted and turns cost $0.

| run | URL change → outcome (s) | catalog check | Together listing | turn | cost | UNAVAILABLE |
|---|---|---|---|---|---|---|
| 1 | - | no check within 120 s (next check in 6 h) | "NOT LISTED (count=2)" | ok | $0.00000 | no |
| 2 | - | no check within 120 s (next check in 6 h) | "NOT LISTED (count=2)" | ok | $0.00000 | no |
| 3 | - | no check within 120 s (next check in 6 h) | "NOT LISTED (count=2)" | ok | $0.00000 | no |
| 4 | - | no check within 120 s (next check in 6 h) | "NOT LISTED (count=2)" | ok | $0.00000 | no |
| 5 | - | no check within 120 s (next check in 6 h) | "NOT LISTED (count=2)" | ok | $0.00000 | no |

**main + naive immediate re-check** (the reverted approach), 5 runs: 2 of 5 runs wedged every later turn; the other 3 deferred the change by 6 h.

| run | URL change → outcome (s) | catalog check | Together listing | turn | cost | UNAVAILABLE |
|---|---|---|---|---|---|---|
| 1 | 0.7 | remote model catalog check failed | "NOT LISTED (count=2)" | ok | $0.00000 | no |
| 2 | 1.7 | remote model catalog check superseded; deferred to the next check | "NOT LISTED (count=2)" | ok | $0.00000 | no |
| 3 | 4.6 | remote model catalog applied | "NOT LISTED (count=0)" | failed | - | yes |
| 4 | 3.6 | remote model catalog applied | "NOT LISTED (count=0)" | failed | - | yes |
| 5 | 3.9 | remote model catalog check failed | "NOT LISTED (count=2)" | ok | $0.00000 | no |

Live service PID and config hash were unchanged before and after every batch.


Gates: `tsgo:core`, `tsgo:core:test`, `tsgo:test:root`, `tsgo:extensions:test`; oxlint and oxfmt on changed files; consumer suites (`update-startup*`, `server-startup-update-check`, `server-startup-post-attach`, `prepared-model-runtime`, `models-list.remote-catalog.integration`). Under host load, `models-list.remote-catalog.integration` timed out once and `update-startup.test.ts` failed once. Both pass on rerun, and on base.

## Merge danger and blast radius

- New behavior: a `models.catalogRefresh` edit triggers one immediate catalog GET.
- Config-driven re-arms of `update.check` also run in the update owner's context now, instead of the reload's. That is the same context as their startup and scheduled runs.
- No config, schema, protocol, SDK or storage change.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 21, 2026
…turns (openclaw#202583)

## What Problem This Solves

Changing `models.catalogRefresh.url` (or `.enabled`) on a running Gateway waited up to six hours for the next scheduled catalog check, so a model the new catalog describes stayed unlisted and its turns were priced at $0.

The obvious fix, re-arming the catalog check from the config listener (part 3 of openclaw#202490, reverted), broke worse. The check ran inside the hot reload that published the config. The Gateway scheduler keeps the async context of whoever schedules a job, and the reload runs inside a plugin lifecycle operation with its own plugin cache, which retires when the reload ends. The catalog adoption then built its plugin generation from that short-lived inventory:

- inventory retired during the build: `PluginInventoryRetiredError` ("check failed") or a rejected candidate ("superseded"), then a 6-hour wait;
- inventory retired after the adoption committed: the published owner was retired with it, and every later turn failed with `UNAVAILABLE: prepared reply dispatch runtime owner was not published for main` until restart;
- every later scheduled check chained from the same retired context and failed again. In the reverted branch this showed up as the 10-second retry failing with an `AbortError`.

## Timeline of one wedged run

Probe build (main plus the naive re-check), one Gateway, URL change at t=10.49 s:

| t (s) | Step | Source (main ab79858) |
|---|---|---|
| 10.49 | The `config.patch` reload runs in the plugin lifecycle lease, which installs an operation-scoped plugin cache | `gateway/config-reload.ts:1007`, `plugins/plugin-lifecycle-lease.ts:356` |
| 10.498 | The runtime config is set and `sessionChanges.emit` fires inside that context. The update owner's listener re-arms the catalog check. `GatewayScheduler` snapshots the registrant's context | `config/runtime-snapshot.ts:272`, `infra/update-startup-scheduler.ts:90`, `infra/gateway-scheduler.ts:190` |
| 10.499 / 10.504 | Reload commit marks prepared runtimes stale (R1), then its refresh supersedes R1 with R2 | `gateway/server-reload-hot.ts:280`, `:596` → `agents/prepared-model-runtime.ts:519` |
| 11.197 | The fetch is done; the adoption waits for R2 | `agents/prepared-model-runtime.configured-refresh.ts:97-101` |
| 11.271 | The reload commits R2 and reply dispatch publishes `main` (generation 5) | `agents/prepared-model-runtime.ts:580` |
| 11.272 | The adoption claims generation 5 and builds candidates. Their plugin metadata belongs to the reload's operation cache | `configured-refresh.ts:256-298`, `plugins/plugin-cache.ts:315` |
| 12.791 | The reload operation ends; its cache retires | `gateway/config-reload.ts:470`, `plugins/plugin-lifecycle-lease.ts:128` |
| 14.336 | The adoption commits generation 6: "remote model catalog applied" | `configured-refresh.ts:363-373` |
| after | Cache retirement retires the published owner (needs refresh, no plugin generation). No recovery runs, because it was not a Gateway loan | `agents/prepared-model-runtime.plugin-lifetime.ts:390`, `:407-425` |
| 41.858 | Turn: owner mismatch → `UNAVAILABLE ... runtime owner was not published for main` | `agents/prepared-reply-dispatch-runtime.ts:179-188` |

The stale mark and the pending replacement were not the cause. The adoption waited correctly for R2 and claimed fresh owners. What broke it was where the check ran, not when.

## Fix

One owner: the update-check scheduler.

- When `models.catalogRefresh` changes, the config listener re-arms the existing catalog check. It does not add a second scheduler.
- Re-arms from the listener run in the update owner's own context, taken from `AsyncLocalStorage.snapshot()` at `start()`, not in the publishing reload's context. The catalog check and every later re-arm use the Gateway's plugin inventory, the same one the startup check uses.

No change to the adoption, the stale mark or reply dispatch. The four symptom patches from openclaw#202490 (10-second superseded retry, `PluginInventoryRetiredError` → superseded, captured cancel signal, docs) stay reverted. None of them is needed, and none was added back.

Accepted edge case: an unrelated model-affecting reload that lands while an adoption is building still defers that adoption to the next scheduled check, as on `main` (openclaw#168981 removed adoption retries on purpose). A further `catalogRefresh` change re-arms at once.

## Evidence

Regression tests (`src/agents/prepared-model-runtime.catalog-source-change.test.ts`) run the real update owner, the real scheduler and the real adoption. The config notification fires inside a reload-style plugin operation, and each test retires that operation's inventory at the point where production failed. Explicit gates, no sleeps.

| Case | main | main + naive re-check | this PR |
|---|---|---|---|
| reload operation ends during the build | red: no re-check | red: `superseded` | green |
| reload operation ended before the check ran | red: no re-check | red: `Plugin inventory has retired; begin a new plugin operation.` | green |
| reply dispatch after the operation ends | red: no re-check | red: `prepared reply dispatch runtime owner was not published for default` | green |
| next scheduled check after the operation ends | red: no re-check | red: `superseded` | green |

Real Gateway (isolated state, loopback catalog and Together mock, `cadence2`: Gateway running on catalog A, then the URL is changed to catalog C, which describes `together/zz-lab/zz-day0-live`):

**This PR** (exact head `11ac3c2d`), 20 of 20 runs: the catalog was adopted 0.6–13.9 s after the URL change (host load average around 70), the new row was listed, every turn succeeded with a price, and no run showed `UNAVAILABLE`.

| run | URL change → outcome (s) | catalog check | Together listing | turn | cost | UNAVAILABLE |
|---|---|---|---|---|---|---|
| 1 | 2.5 | remote model catalog applied | listed | ok | $0.00006 | no |
| 2 | 2.1 | remote model catalog applied | listed | ok | $0.00006 | no |
| 3 | 13.9 | remote model catalog applied | listed | ok | $0.00006 | no |
| 4 | 1.8 | remote model catalog applied | listed | ok | $0.00006 | no |
| 5 | 1.3 | remote model catalog applied | listed | ok | $0.00006 | no |
| 6 | 2.9 | remote model catalog applied | listed | ok | $0.00006 | no |
| 7 | 8.6 | remote model catalog applied | listed | ok | $0.00006 | no |
| 8 | 5.0 | remote model catalog applied | listed | ok | $0.00006 | no |
| 9 | 3.4 | remote model catalog applied | listed | ok | $0.00006 | no |
| 10 | 3.5 | remote model catalog applied | listed | ok | $0.00006 | no |
| 11 | 0.7 | remote model catalog applied | listed | ok | $0.00006 | no |
| 12 | 0.7 | remote model catalog applied | listed | ok | $0.00006 | no |
| 13 | 0.6 | remote model catalog applied | listed | ok | $0.00006 | no |
| 14 | 0.9 | remote model catalog applied | listed | ok | $0.00006 | no |
| 15 | 0.7 | remote model catalog applied | listed | ok | $0.00006 | no |
| 16 | 0.7 | remote model catalog applied | listed | ok | $0.00006 | no |
| 17 | 6.8 | remote model catalog applied | listed | ok | $0.00006 | no |
| 18 | 0.8 | remote model catalog applied | listed | ok | $0.00006 | no |
| 19 | 1.3 | remote model catalog applied | listed | ok | $0.00006 | no |
| 20 | 1.1 | remote model catalog applied | listed | ok | $0.00006 | no |

**main** (`ab798580`), 5 runs: no check after the URL change; the next check comes in 6 h. The row stayed unlisted and turns cost $0.

| run | URL change → outcome (s) | catalog check | Together listing | turn | cost | UNAVAILABLE |
|---|---|---|---|---|---|---|
| 1 | - | no check within 120 s (next check in 6 h) | "NOT LISTED (count=2)" | ok | $0.00000 | no |
| 2 | - | no check within 120 s (next check in 6 h) | "NOT LISTED (count=2)" | ok | $0.00000 | no |
| 3 | - | no check within 120 s (next check in 6 h) | "NOT LISTED (count=2)" | ok | $0.00000 | no |
| 4 | - | no check within 120 s (next check in 6 h) | "NOT LISTED (count=2)" | ok | $0.00000 | no |
| 5 | - | no check within 120 s (next check in 6 h) | "NOT LISTED (count=2)" | ok | $0.00000 | no |

**main + naive immediate re-check** (the reverted approach), 5 runs: 2 of 5 runs wedged every later turn; the other 3 deferred the change by 6 h.

| run | URL change → outcome (s) | catalog check | Together listing | turn | cost | UNAVAILABLE |
|---|---|---|---|---|---|---|
| 1 | 0.7 | remote model catalog check failed | "NOT LISTED (count=2)" | ok | $0.00000 | no |
| 2 | 1.7 | remote model catalog check superseded; deferred to the next check | "NOT LISTED (count=2)" | ok | $0.00000 | no |
| 3 | 4.6 | remote model catalog applied | "NOT LISTED (count=0)" | failed | - | yes |
| 4 | 3.6 | remote model catalog applied | "NOT LISTED (count=0)" | failed | - | yes |
| 5 | 3.9 | remote model catalog check failed | "NOT LISTED (count=2)" | ok | $0.00000 | no |

Live service PID and config hash were unchanged before and after every batch.


Gates: `tsgo:core`, `tsgo:core:test`, `tsgo:test:root`, `tsgo:extensions:test`; oxlint and oxfmt on changed files; consumer suites (`update-startup*`, `server-startup-update-check`, `server-startup-post-attach`, `prepared-model-runtime`, `models-list.remote-catalog.integration`). Under host load, `models-list.remote-catalog.integration` timed out once and `update-startup.test.ts` failed once. Both pass on rerun, and on base.

## Merge danger and blast radius

- New behavior: a `models.catalogRefresh` edit triggers one immediate catalog GET.
- Config-driven re-arms of `update.check` also run in the update owner's context now, instead of the reload's. That is the same context as their startup and scheduled runs.
- No config, schema, protocol, SDK or storage change.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant