Repository navigation
fix(catalog): release per-turn worker state and attribute worker memory - #158323
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. Reviewed September 26, 2026, 3:40 AM ET / 07:40 UTC (Revision 5). ClawSweeper reviewWhat this changesThe branch reuses the catalog worker’s current plugin context for each loader workspace and adds direct-worker memory measurements to Gateway warnings and exported diagnostic bundles. Regression provenancePossible regression — probable (reproduction; failure trace). No predecessor PR is attributed. Merge readiness⛔ Blocked before merge - 2 items remain Current main still has the worker-context churn and lacks external-memory attribution, so this PR remains useful. Its scoped behavior has strong proof, but the closing reference would resolve a broader memory incident whose reported trigger remains unverified after this fix. Priority: P0 Review scores
Verification
How this fits togetherThe Gateway sends agent configuration, workspace metadata, and request-local credentials to a model-catalog worker, which returns available models. A shared worker registry feeds memory measurements into Gateway diagnostics and stability bundles. flowchart LR
A[Agent and workspace facts] --> B[Catalog worker]
B --> C[Available models]
B --> D[Worker memory samples]
D --> E[Worker registry]
E --> F[Memory diagnostics]
F --> G[Warnings and bundles]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +282, Tests +446, Docs +22, Other +2. Total +752 across 20 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Land the bounded catalog and diagnostic repairs with a related issue link, then keep the original incident open for same-agent isolated-turn evidence and an owner-level retirement repair if growth persists. Do we have a high-confidence way to reproduce the issue? Yes for the narrower defect: current main’s single context slot recaptures native modules when unchanged workspaces alternate, and the submitted parent-API negative control demonstrates that path. The reporter’s same-agent isolated-turn growth has not been reproduced by the PR’s cron fixture. Is this the best way to solve the issue? Yes for the scoped worker reuse and memory attribution, which extend their existing owners. The evidence does not support treating this patch as complete resolution of the broader incident. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against f63fea56a7b2. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (4 earlier review cycles)
|
The factory already declares the exact generic return type. Constructor inference removes the redundant annotation without changing emitted runtime behavior.
fca2e3d to
c86d7f5
Compare
Backport the catalog native ESM retention repair and worker memory attribution from #158323 to release/2026.9.7. (cherry picked from commit 5e4b43c) Conflicts: keep the release worker's exact-generation fingerprint and release custody while retaining one current generation per loader workspace. Port memory sampling, native fallback, coverage, and bundle import through the release registry. Exclude main-only catalog/lifecycle refactors and preserve the release atomic writer. No prerequisite commits are required.
Merge the already-landed release/2026.9.7 history at 7bd08b5 into the reviewed prepared branch without re-cherry-picking external sources. Preserve canonical native admission, companion namespaces, exact-generation fingerprints, worker publication and atomic index ownership alongside the parent's legacy census, cleanup and live lease repairs. Resolve four conflicts and retain both test inventories. A damaged native instance is not tokenless legacy scratch: keep its published payload when the coordinator disappears. Add the existing Doctor journal-history helper to the extracted-wrapper manifest; no database source changes. Canonical provenance remains in the merged history: - #158770 / source #157565 (PollyBot13, landed by Peter Steinberger) - #158808 / source #158323 (Peter Steinberger) - #158910 / sources #158414 and #158769 (Peter Steinberger) Verified 1,019 exact-parent, 82 exact-canonical and nine combined postimages. Two composition regressions reproduced and corrected. 157 focused owner cases and two wrapper closure checks pass, as do production/test types, lint, formatting and all frozen eb377ac ratchets. Full build passed in 262 seconds. Independent P0-P2 review completed all three passes clean. Compilation is not installed-driver qualification. Normal built integration preflight still refused runtime-artifact-publication/systemd-competing-managers. The separate coupled database backport and its bound fixture hunk remain unapplied. Version and dependencies are unchanged; public size-policy hold remains active. Implementation and verification: https://team.openclaw.ai/chat/roboclaw/subagent/69c28824-7ae8-4692-9037-6998b58bc7f4 Discussion, review and integration: https://team.openclaw.ai/chat/roboclaw/dashboard/db4d78ac-b19b-4f64-adfb-0ca7973a62e4 Co-authored-by: RomneyDa <[email protected]> Co-authored-by: vyctorbrzezowski <[email protected]> Co-authored-by: steipete <[email protected]> Co-authored-by: jalehman <[email protected]>
…ry (openclaw#158323) * fix(catalog): release per-turn worker state and attribute worker memory * fix(scripts): include worker diagnostics in wrapper source snapshots * refactor(workers): infer pool retirement type The factory already declares the exact generic return type. Constructor inference removes the redundant annotation without changing emitted runtime behavior.
Closes #157842
Refs #157575, #158183, #158201
What Problem This Solves
Fixes retained catalog-worker memory when requests alternate between unchanged loader workspaces, and makes worker heap and buffer usage visible in memory-pressure diagnostics.
User Impact
Long-lived workers reuse each workspace's current plugin context. Task-worker diagnostics report real heap, external, and ArrayBuffer measurements with sample age and coverage; unavailable measurements are no longer reported as zero. Exported diagnostic bundles preserve these measurements.
No configuration, dependencies, database schema, stored data, service heap policy, or update/rollback procedure changes. Native ESM graphs created by actual source/configuration changes still live until worker retirement. Native-only workers expose heap/external readings with unavailable ArrayBuffer coverage; nested workers remain outside the parent registry. Node does not provide a hard worker cap for external/native memory.
Why This Change Was Made
The worker's single current-context slot evicted workspace A when workspace B ran. Returning to A captured another native ESM graph. Disposing callbacks and capture files cannot remove Node's
ModuleLoader.loadCacheentries. The existing inventory-owned worker now retains the latest exact context per loader workspace; fingerprint validation, current request credentials, failed-candidate cleanup, and replacement ordering remain intact.Memory collection stays with the existing worker registry. Task pools negotiate a dedicated channel for isolate-local
process.memoryUsage()samples, preserving custom-parent protocols. Native heap interrupts remain available when a busy worker cannot service that channel, and delayed native replies cannot replace newer full samples. Missing/stale coverage and the external-memory limit are explicit in pressure warnings.Thanks @highfly-hi for the retention report, @zl0nline for the native ESM investigation, and @oleagui for the attribution evidence. The earlier #157459 repair already made ordinary catalog observation passive; this change fixes the remaining workspace-context churn rather than duplicating that renewal repair.
Evidence
Catalog owner: same-rig negative control and repair
Linux x64, Node 24.19.0, Blacksmith run, lease
tbx_01m3d0dvxedz81k24k3nvvy8rs. Twenty calls use the canonicalcreatePreparedModelCatalogWorker(...).loadCatalog()parent API, alternating two actual workspace metadata views of the same inventory in one worker. Each result verifies the current agent's credentials. The synthetic provider has a native ESM dependency with 100,000 row objects and a 1 MiB buffer. This bounded fixture identifies a retaining owner; it does not reproduce the reported 70–80 MB per-turn amplitude.Callbacks plateau at two in both versions. The regression fails before the repair (
20retained payloads instead of2) and passes three times afterward. Heap snapshots after requests 5 and 20 identify:ModuleLoader.loadCache → LoadCache.table → entry.javascript → ModuleJobSync.module → ModuleWrap → SourceTextModule → Cell.value → CatalogWorkspacePayloadThe payload owns its row array and
buffer → Uint8Array.buffer → ArrayBuffer.backing_store → JSArrayBufferData. Snapshot retained-graph growth falls from 77,197,824 to 1,294,112 bytes, with zero new candidate payloads. External and ArrayBuffer counters are exactly flat after warmup. RSS is process-wide; ArrayBuffers are included in external and must not be added to it. Raw heaps were kept private; only sanitized findings are reported.Real cron flow and prior repair
The release comparison, lease
tbx_01m3cy5xzctgm72417nydmpmjr, runs 20 real cronagentTurns with a mock provider and three agents through an isolated Gateway. Exact release baseline:v2026.9.6,eb377ac59e6c9fd6c7705028034812becf00271b.The already-landed #157459 renewal repair explains the absence of per-turn catalog work on current main. A current-main control is likewise flat before this PR. A native-dependency variation retains only one payload even on the release because the Gateway publication keeps one shared loader context. These cron runs therefore do not establish the operator's exact retention trigger; the new repair's failing/passing evidence is the canonical-parent alternating-workspace case above.
The manual cron probes take about 34–39 seconds for 20 serial real turns plus GC/snapshots; they are not added to per-PR CI. The initial probe's ~103-second test cost came from forcing GC every turn and separately publishing each agent; using the canonical publication path and sampling GC at 1/5/20 removed that fixture cost. No test timeout or retry was increased.
Worker attribution and validation
Both attribution regressions fail on the original code: the live worker omits its buffer measurements, and bundle import drops worker fields. The busy-worker regression also fails on the intermediate cooperative-only sampler: no native heap request occurs while the worker's JavaScript loop is held. The repaired sampler obtains real heap/external measurements through a V8 interrupt, marks unavailable buffer coverage honestly, and rejects a late native reply after full sampling recovers. The fixture uses an event/SAB barrier without sleeps or polling.
The touched suites pass three times. The new catalog regression takes 2.867 / 3.742 / 2.948 s of test time (18.62 / 20.55 / 21.97 s Vitest wall); its expected-red baseline takes 3.300 s. The final busy-worker regression takes 101 / 106 / 113 ms. Snapshot-instrumented owner runs take 9.480 s before / 5.814 s after, without timeout changes. The broader first pass passed 86 files / 3,235 tests; the subsequent ownership/typing repair passed 14 affected files / 199 tests.
Final
node scripts/check-changed.mjs -- <all 19 changed paths>passed on leasetbx_01m3d2waqxzqz1bv19hghky0kp(run): 1,906.80 s, including core typing, all 25 test-type shards, lint, and the repository guards.pnpm build: passed, 557.02 s (build phases 9m16.6s). The complete native command envelope succeeded with exit 0; Crabbox emitted a portal-sync warning after recording that result.The additional direct/one-barrel consumer batch used
node scripts/run-vitest.mjs <220 paths in captured original order>on leasetbx_01m3d3310kfcanrd9ycaqg09sm(run): 219 files / 5,692 tests passed, 57 existing platform skips, zero failures, exit 0. Test-runner wall was 1,473.99 s, including 612.3 s of prerequisite build; the complete command envelope was 25m59s. No individual test exceeded 30 seconds or file exceeded 120 seconds of test time.Across both consumer batches, all 306 selected paths reconcile to 305 exercised files / 8,927 passing tests, 57 existing skips, and one unexecuted live opt-in file:
src/gateway/gateway-models.profiles.live.test.ts. No live credentials or opt-in flags were enabled. Existing skips comprise 48 Windows-only MXC cases, one Windows git-null-config case, one Windows PATHEXT case, and seven POSIX-process fallback cases excluded on Linux. The 14-file follow-up and catalog 3× runs are additional proof, not included again in those totals.Independent Codex review reports no actionable P0–P2 findings on the final production/test repair. Initial changed-file gates caught source-size growth and two relocated assertions; the decoder now has a shared typed reader owner, the pool delegates telemetry validation, and the assertion baseline only shrinks from 11 to 9. No suppressions or relaxed assertions were added. Testbox Actions links can show cancellation after native lease cleanup; command exits above are the proof outcomes.
Production: +377 / −89 (net +288); tests/support: +462 / −16; docs: +24 / −2; baseline: one shrink-only line replacement. The retention repair itself is +9 / −4 (net +5). Most production growth implements the requested telemetry, explicit coverage, and safe bundle import through existing owners.
Adjacent heap policy evidence
#158201 removes automatic heap sizing for fresh managed services while preserving explicit/stored heap flags. This PR does not duplicate that service-policy change.
The standalone Node probe, lease
tbx_01m3ctpzvh791ee2k5gyxc9krh, requested 512 MiB old space in every worker. Clearing workerexecArgvand its environment did not change these measured total V8 ceilings:--max-old-space-size=8192--max-old-space-size=4096NODE_OPTIONS=--max-old-space-size=8192These ceilings include young-generation space. Explicit worker
execArgv: ["--max-old-space-size=512"]throwsERR_WORKER_INVALID_EXEC_ARGV; a separate process consistently gets 704 MiB. Enforcing the smaller budget under a larger parent flag needs a process boundary. That remains a follow-up only if the repaired retained working set still needs it.CI follow-up: extracted wrapper dependencies
The updated PR head
7c68236d444e5177bd0767544f68849695bc8903fails four cases intest/scripts/eager-import-closure.test.ts; current-main control91b8f103cbed9339e643982301c1da9cbd30da0apasses all 15. The materialized wrapper source inventory omitted the two modules added by this PR. Its CLI import path isworktree-provision → allocation → state lease → lease heartbeat → worker-cpu → worker-diagnostic-script. The script-name sanitizer is shared pure code;worker-memoryremains outside the CLI eager graph and is required by already-included worker entrypoints.The owning
wrapper-components.txtnow includes both modules. This is +2 tooling lines, zero production/test changes; no runtime imports or lazy boundaries change. The existing regression passes all 15 cases 3× (27.57 / 26.95 / 26.83 seconds Vitest wall), and fresh Codex autoreview reports no actionable P0–P2 findings.pnpm check:import-cyclespassed with 0 runtime value cycles, andnode scripts/check-changed.mjs -- scripts/pr-lib/wrapper-components.txtpassed with 0 lint warnings/errors on Testboxtbx_01m3dx44qfkbyfv5ympdk9bvqk(run); combined remote command 189.939 seconds, exit 0. A portal-sync warning followed the successful native result. Auto-merge remains off.