Repository navigation
Conversation
The write path recursively descended in two places: collectChangedPaths walked both documents one call frame per nesting level, and the platform JSON.stringify recursed again while rendering the stamped document, so a schema-valid deep config that loaded fine could crash any later write with a RangeError. collectChangedPaths now walks on an explicit work stack and the write path serializes through an explicit-stack serializer whose output stays byte-identical to JSON.stringify(value, null, 2); regression coverage pairs the serializer and the path walker against the platform behavior on randomized documents and on 5,000-level nesting. Co-Authored-By: Claude <[email protected]>
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review blockedAutomated review did not run, so no review verdict was produced. Reason: ClawSweeper could not verify the complete source for this revision. Automatic review is on hold, including after source changes. Request a fresh re-review after resolving the failure; maintainers can also release the hold through an intentional scanner-policy update. Next step: No contributor action is requested. Maintainers should inspect the linked workflow run. |
|
Codex review: needs maintainer review before merge. What this changesThe PR replaces recursive configuration-write processing with explicit work stacks so deeply nested settings can be saved without overflowing the call stack. Example: A caller saves a 2,000-level configuration under plugins.entries.probe.config.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR remains useful: current main and the latest release retain the config-write failures, and related read-side repairs do not supersede its work. No blocking patch defect was found. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherOpenClaw’s configuration writer receives requested settings and an authored snapshot, preserves references and explicit values, validates the result, and publishes a configuration file. flowchart TD
A[Requested settings] --> C[Compare and project changes]
B[Authored configuration] --> C
C --> D[Merge and preserve references]
D --> E[Validate configuration]
E --> F[Stack-safe JSON serialization]
F --> G[Publish configuration file]
G --> H[Read configuration]
Technical reviewBest possible solution: Keep one configuration writer that handles deeper JSON trees while preserving authored references, patch semantics, and serialized bytes. Do we have a high-confidence way to reproduce the issue? Yes: current-main source retains depth-proportional recursion, and the contributor records an isolated real-filesystem writer differential. This read-only review did not independently execute that reproduction. Is this the best way to solve the issue? Yes: replacing traversal within the existing owners repairs the documented failure without new settings or competing persistence paths; the recovery claim appropriately excludes unchanged depth limits. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against d0fc39e87290. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +1031, Tests +533, Other +1. Total +1565 across 15 files. Added test files: 5. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (18 earlier review cycles; latest 8 shown)
Reviewed October 9, 2026, 4:50 PM ET / 20:50 UTC (Revision 19). |
…ratchet The fast baseline ratchet counts non-const type assertions per file and config-json-serialize.ts shipped four new ones. Three are removable without any behavior change: isPlainContainer already narrows to Record<string, unknown> at the two toJSON probes, and the aliased const narrows to Function via the existing typeof check before its call. The remaining object-vs-record cast in collectEntries keeps a single-line SAFETY comment documenting why the non-array remainder is a plain record. Co-Authored-By: Claude <[email protected]>
The write chain resolves and restores ${VAR} references over the whole
parsed document, and those traversals kept call frames proportional to
document depth, so a schema-valid deep config crashed with a RangeError
before the writer serialized it. The comparison resolve, the authored
restore walk with its escape mutation check, the map-based restore
walk, and the authored-template probes now carry their work on explicit
stacks, so document nesting costs heap rather than call frames. Deep
object keys settle in document order and id-keyed array matching is
unchanged.
Co-Authored-By: Claude Code <[email protected]>
createMergePatch, applyMergePatch, mergePatchConflicts, and the runtime-source projection recursed over the documents they diffed, and they cloned values with structuredClone, whose own traversal overflows the call stack on schema-valid deep configs before the write path commits. The patch build, patch apply, conflict detection, and projection now run on explicit work stacks with keys settling in document order, the value clone walks containers iteratively, and tree-level equality uses an explicit-stack comparison. Co-Authored-By: Claude Code <[email protected]>
The iterative merge-patch, patch-apply, and projection walkers passed the full frame union to their settle helpers, but the key-resolution variants carry no container slot, so the plugin-sdk boundary dts emit rejected the frame.container access. The helpers only ever settle enter and exit frames; type them with Extract. The conflict walk also widened its record guards through boolean locals, which the checker cannot flow through; inline the guards where the narrowed record is consumed. Co-Authored-By: Claude Code <[email protected]>
The iterative clone assigned keys through plain bracket writes, so an authored own __proto__ key invoked the inherited setter: the clone lost the key as own data and grafted the value onto its prototype, where the platform clone had kept it inert. Prototype keys now settle through defineProperty, preserving the own-property shape that merge-patch additions and retained projection values carry into serialization. Co-Authored-By: Claude Code <[email protected]>
Merging main pushed env-preserve.test.ts past the 1000-line cap and orphaned the EnvRefArrayMutationError import plus its re-export. Move the authored own-__proto__ regressions and the stack-safe deep-restoration suite into coherent sibling test files, drop the unused import and re-export, and reflow the merged explicitSetPaths condition. Co-Authored-By: Claude <[email protected]>
…pshot Co-Authored-By: Claude <[email protected]>
The 2026-09-22 f7d6123 run failed four compact-large shards on four distinct signatures, none touching the config-write surface this PR changes: - compact-large-8: gateway/embeddings-http.test.ts close-count race (25 vs 26 inside vi.waitFor) plus a cascading state-db borrower leak - compact-large-10: cron/service.heartbeat-busy-poll.test.ts vi.waitFor heartbeat request never observed (0 of 1) - compact-large-14: cli/resume-cli.test.ts bootstrap-credential retire helloCount 1 vs 2 inside vi.waitFor (5s budget) - compact-large-18: gateway/server.sessions.archive-worker-placement drainStarted never observed, session history read revoked All four are timing-sensitive waits on saturated shard runners. This empty commit re-runs the matrix. Co-Authored-By: Claude <[email protected]>
SIGINT staging-close ordering in test/scripts/docker-all-harness.test.ts is outside this PR's config-write surface. Co-Authored-By: Claude <[email protected]>
compact-large-30/31 (residual registry roots teardown cross-talk across agentic-gateway-methods-hosted shards), compact-large-32 (tasks.list performance timing), and changed-extensions-bundle-31 (matrix active-turn steering timeout) all fail outside the config-write surface this PR touches. Same pattern passed on the prior head's shards. Co-Authored-By: Claude <[email protected]>
Resolve the env-preserve/merge-patch fusion against main's in-place array-matching refactor: keep main's unified matchAuthoredTemplateArrayItems semantics and the resolveWriteEnvSnapshotForPath updates, and rebuild the stack-safe iterative walks (env-ref restore, merge patch, serialization, change-path collection, authored template probes) on top of them.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Thanks for the work here. We're closing this: it doesn't show a real user-facing problem (no report from an affected user and no natural reproduction), and it follows a pattern of small, speculative or duplicate changes split across many PRs. Please open an issue with a reproduction of real harm first; a fix can follow once the problem is confirmed. |
What Problem This Solves
Fixes #153668. Fixes #154264.
The config write chain has five recursive stages that overflow on schema-valid deeply nested documents, in the order they engage during
writeConfigFileFromContext:collectChangedPaths()(src/config/config-change-paths.ts) - the recursive diff walk consumed atio.write.ts:189/313/586overflows at ~4,500 levels in this sandbox (the [Bug]: Deeply nested config change path collection crashes with RangeError #153668 reporter observed ~4,000 on Windows), and also servesmanagement-mutations.projectRuntimeChangesOntoSource()(src/config/source-value-projection.ts) - the runtime-changes projection walks the document recursively and clones via nativestructuredClone, which overflows at ~1,600 levels on the full-chain probe below.createMergePatch/applyMergePatch/mergePatchConflictsinsrc/config/merge-patch.ts) plus its internal clone helper, which recursed and also delegated to nativestructuredClone.resolveEnvVarRefsForComparison/restoreEnvVarRefsFromResolved/restoreEnvRefsFromMapinsrc/config/env-preserve.ts, plus the twocontainsAuthored*EnvTemplateprobes insrc/config/env-preserve-authored.ts) - recursive walks over the authored document.JSON.stringify(stampedOutputConfig, null, 2)atsrc/config/io.write.ts:354- the platform serializer recurses one call frame per nesting level and overflows at ~4,400 levels (bisected: 4,457 serialize, 4,458 crash in this sandbox).All of these stages now walk on explicit work stacks, so document nesting costs heap rather than call frames on the stages this PR repairs. The full-chain differential below verifies this at runtime-basis inputs, but the write (save) leg is not recursion-free without qualification: two retained limits stay on it - the source-input branch of
projectConfigWriteSourcestill clones with nativestructuredClonebefore publication (io.write-prepare.ts:1590), and the array-identity/escaped-reference accounting helpers retain recursive literal-path collection and native whole-row equality (the recursivecollectLiteralArrayIdentityPathswalk inenv-preserve.ts) plus recursive escape-counting visits (env-preserve-authored.ts). Those are pre-existing main behavior, outside the five repaired stages. The remaining ceilings on deeply nested documents sit outside the write leg: the read chain's include resolver and include pre-scan (the repair surfaces of #152889 and #153711), and the CLI mutation runner's own tree clone (see accounting below).What Changed
src/config/config-json-serialize.ts(new):serializeConfigJson(value)- a byte-identical reimplementation ofJSON.stringify(value, null, 2)on an explicit work stack. It covers the platform semantics this document class exercises:toJSONre-application (bounded, like the platform's own cycle path), object members withundefined/function/symbol values vanishing while array items collapse tonull,String(number)formatting with non-finite numbers asnull, lone-surrogate escaping, and cycle detection (TypeError, matching the platform).src/config/config-change-paths.ts:collectChangedPaths()walks both documents on an explicit work stack instead of recursion. The visited path set and its order are unchanged (asserted against a recursive reference implementation).src/config/source-value-projection.ts:projectRuntimeChangesOntoSource()walks on explicit enter/exit frames; nativestructuredCloneis replaced by the shared stack-safe clone. Sentinel semantics (UNCHANGED/ABSENT), the delete-on-projection behavior, and the allowed-key checks are unchanged.src/config/merge-patch.ts:createMergePatch(),applyMergePatch(), andmergePatchConflicts()walk on explicit frames (key-list frames preserve DFS key order; an exit frame preserves the skip-when-empty patch semantics; array-by-id merging keeps its slot boxes). The internal recursive clone is replaced by an exported stack-safecloneUnknown, which is also what removes the nativestructuredClonecall insidemergeObjectArraysById.src/config/env-preserve.ts: all three env-ref passes walk on explicit frames.restoreEnvVarRefsFromResolvedkeeps document key order for newly-inserted keys, keeps the template-match/escape-check ordering, and keepsEnvRefArrayMutationErrorfail-closed behavior;restoreEnvRefsFromMapkeeps its return-original-reference-when-unchanged semantics.src/config/env-preserve-authored.ts: the twocontainsAuthored*EnvTemplateprobes share one iterative deep-search helper.src/config/merge-patch.ts+src/config/env-preserve.ts(review follow-up): the rebuilt trees settle child values through one sharedsettleContainerValuehelper, which settles an authored own__proto__key as inert own data (the way the replacedObject.fromEntries/structuredClonewalks kept it) instead of invoking the inherited setter through plain assignment.src/config/deep-equal-stack-safe.ts(new):deepEqualStackSafe(a, b)- the stack-safe tree equality used wherever these modules previously reached forisDeepStrictEqualon whole documents (leaf comparison still usesisDeepStrictEqual, so leaf semantics are unchanged).src/config/io.write.ts:354: the write emitsserializeConfigJson(stampedOutputConfig)instead of the platform call. The bytes are identical.Evidence
Component level (this sandbox, Node 24 stack)
JSON.stringify, 4,500 levelsJSON.stringify, 5,000 levelscollectChangedPaths, 4,500-level leaf changecollectChangedPaths, 5,000-level leaf / array growthFull chain through
writeConfigFileFromContext(save + reread)Real entry point, isolated state dir, no test harness:
createConfigIOfromsrc/config/io.factory.ts, thenio.writeConfigFile(...)followed byio.readConfigFileSnapshot(). The deep document rides underplugins.entries.probe.config(the schema's free-form record slot), so it passes schema validation and reaches the whole write chain - diff, projection, env-ref passes, merge patch, validation, serialization, publish - and then the read chain on reread. main is checked out at103115f2f0b(current origin/main), this head is53c0774cb93.structuredCloneviacloneUnknowninsidecreateMergePatch(merge-patch.ts:16/40)IncludeProcessor.processObject(includes.ts:222) - read-chain include resolver, the #152889 surfacecontainsConfigIncludeDirective(io.read-helpers.ts:90) - the #153711 surfaceAt this head the five repaired stages complete with zero tree-deep recursion on them at every depth up to the read-chain ceiling (the differential uses runtime-basis inputs, so the retained source-input and array-identity limits above are not exercised by it); both remaining failure frames are in the read chain, outside this PR's surface.
Real CLI subprocess matrix (
config set+config get)node --import scripts/tsx.mjs src/entry.ts config set plugins.entries.probe.config.leaf '"touched"' --strict-jsonagainst a pre-seeded deep document in an isolated$OPENCLAW_STATE_DIR, thenconfig geton the same path. Each run is a fresh subprocess and state dir.Maximum call stack size exceededAccounting for the CLI ceiling: the CLI's ceiling is below the write chain's because
config setengages the mutation runner before the write chain:runConfigOperationsclones the whole resolved document with nativestructuredClone(src/cli/config-cli-runner.ts:315), which overflows around 1,200 levels on both main and this head. That stage is not on the write chain and is not part of the issues this PR fixes, so the CLI boundary is unchanged by this PR; the write-chain recovery is proven at thewriteConfigFileFromContextboundary in the table above. Beyond that, the read chain carries its own untouched recursions (include resolver atincludes.ts:222, pre-scan atio.read-helpers.ts:90) which bound the reread leg independently - those are the repair surfaces of #152889 and #153711. One further limit sits inside the write leg itself: when the write runs on a source basis,projectConfigWriteSourceclones with nativestructuredClone(io.write-prepare.ts:1590), so source-basis deep documents overflow there on both main and this head, and the array-identity/escaped-reference accounting keeps its pre-existing recursive and native-equality paths. These are main behavior, unchanged by this PR, noted so the recovery claim stays scoped to the five repaired stages.Serialized-byte equivalence is pinned two ways: the 400-case fuzz compares
serializeConfigJsonagainstJSON.stringify(value, null, 2)directly, and the fullio.writesuites (361 tests) pass unchanged at this head - those suites assert written bytes through the config hash chain and reread snapshots, so any byte drift would fail them.Authored own
__proto__key preservation (own-property compat)The iterative rebuilds settle child values into freshly built containers. Plain assignment invokes the inherited
__proto__setter: the own key is lost and the value is grafted onto the tree's prototype, and array identity matching over the comparison tree can consequently reject unchanged rows.settleContainerValue(shared by the stack-safe clone and all three env-ref settlements) defines such keys as inert own data instead. Repros inenv-preserve.test.ts(authored key built viaJSON.parse), pre-fix red to post-fix green at this head:The previously requested unchanged-array regression is now pinned: an untouched two-row array whose rows carry a JSON-parsed own
__proto__: nulldata key. The comparison tree must settle that key as inert data, or neither row equals its resolved counterpart (matchesArrayElementAtSameIndexinenv-preserve.ts) and both array identities go unmatched. Pre-fix (parent49cd9710ccf) the restore output dropped the rows' own key —{ providers: [{…(2)}, {…(2)}] }against the expected three-key rows — and the test fails; at this head it passes.__proto__key (Object.fromEntriesbaseline)checks-node-compact-large-10diagnosis (recorded owning repair, not this PR's surface)The 2026-09-21T21:00Z run's single failure is
src/state/openclaw-agent-db-module-identity.test.ts("shares agent ownership, worker publication, reclamation queues, and commit observers across transformed SDK modules") at line 271:AssertionError: spawnSync <toolchain node> ETIMEDOUT: expected null to be +0. That test spawns a fresh Node child with a fixedtimeout: 30_000andJITI_FS_CACHE: "0"(source transforms re-run on every spawn); the shard executed 2,492 tests over 467s; the likely cause - inferred from the timing, not verified - is a saturated runner pushing the child past its fixed budget, which returnsresult.statusasnull. The test file is byte-identical on main and outside this PR's config-write surface, and a spawn timeout is purely load-sensitive. A plausible owning repair - proposed, not verified - would be a more generous child budget (or a spawn retry) in that test; recorded here per the review request instead of retrying for green, and this head's CI run re-runs the shard.The 2026-09-22T12:35Z run on
f7d6123142failed the same shard on a second, unrelated signature:src/cron/service.heartbeat-busy-poll.test.tsat line 247,expected "vi.fn()" to be called once, but got 0 timesinsidevi.waitForaftervi.advanceTimersByTimeAsync— the heartbeat request was never observed within the wait budget (runner saturation is inferred, not verified). That file is byte-identical on main and equally outside this PR's config-write surface. Two distinct load-sensitive signatures in one shard (aspawnSyncchild budget on the first signature, avi.waitForbudget on the second) are consistent with saturated-runner flake as seen from the shard's own test files; plausible owning repairs - proposals, not verified - live in those test files on main, and this PR documents them instead of retrying for green. The same run also failed compact-large-8 (gateway/embeddings-http.test.tsclose-count race insidevi.waitFor, 25 vs 26, plus a cascading state-db borrower leak from the failed cleanup), compact-large-14 (cli/resume-cli.test.tsbootstrap-credential retire,helloCount1 vs 2 inside a 5svi.waitFor), and compact-large-18 (gateway/server.sessions.archive-worker-placement.test.ts,drainStartednever observed plus a revoked session-history read) — four shards, four signatures, allvi.waitFor-family timing waits, none in the diff.Merge with current main (reference-intent/file-ownership landing)
Main landed
#147440(reference intent + file ownership) and#152490(value-traversal isolation) while this PR was under review, so the branch was merged at headadd3c594(merge of54c312971a4intobe48a677367). The conflicts resolved:containsUnaccountedActiveEscapedEnvRef.restoreEnvRefsFromMapand the wholeenvRefMapcollection in the writer); the merge follows that removal, so restoration flows through the one iterativerestoreEnvVarRefsFromResolvedwith explicit intent paths.resolveStableArrayIdentityMatchis now exported fromenv-preserve-array-identity.ts(its body is byte-identical to main's) for the escape-check pass. (Superseded by the round-2 merge below: that module is gone and main's in-place helpers are used directly.)containsAuthored*walkers inenv-preserve-authored.tsare kept on top of main's explicit-intent additions to that module.io.write.tskeepsserializeConfigJsonon top of main's write-topology refactor), and main'sio.write-values.tsrestore entry (which passesexplicitSetPaths) is kept.Verification at the merge head:
node scripts/run-tsgo.mjs -p tsconfig.core.jsonis clean (checked out in a dependency-installed worktree at the merge tree; the primary sandbox carries stalepackages/*/distdeclarations that produce unrelated symbol-inference noise), and the merged test face is green:env-preserve.test.ts95/95 (main's explicit-intent suite plus this PR's stack-safe and authored own__proto__suites),merge-patch+config-json-serialize+config-change-paths+source-value-projection26/26, andio.write-config+io.write-prepare+io.write-reread+io.write-effects409/409, plusio.write-lockgreen.Merge with current main (round 2: array-matching unification landing)
While this PR waited on review, main unified the escaped-template matcher into
matchAuthoredTemplateArrayItems(arrays, "substitution" | "escaped", claimedIncomingIndexes?)and moved the array-identity helpers back intoenv-preserve.ts, so the branch was re-merged at heade814cf0406a(merge of main68d49169a53into the prior head). The conflicts resolved:restoreEnvVarRefsFromResolvedframes are kept and now call main's unified matcher with the mode parameter; the standaloneenv-preserve-array-identity.tsmodule is dropped (main keeps the helpers in place), and the stack-safesettleContainerValuestays exported frommerge-patch.tsfor both the merge-patch builders and the env-ref restore frames.resolveEnvVarRefsForComparisonand the authored-template probes stay on their iterative walks;resolveWriteEnvSnapshotForPathand the retained-limit recursion (collectLiteralArrayIdentityPaths, the escape-counting visits) follow main verbatim.merge-patch.tskeeps the stack-safe builders on top of main's cleanups (inlined array-entry path formatting, the redundant pre-loop id-guard removal, and theapplyMergePatchbase passthrough, which is behavior-identical because a non-object base is normalized to an empty result either way).config-json-serialize.tsanddeep-equal-stack-safe.ts.Verification at the merge head:
node scripts/run-tsgo.mjs -p tsconfig.core.jsonis clean in a dependency-installed worktree at the merge tree (a first cut of the merge left the escape-check frames carryingreadonly unknown[]into main's mutableEnvRefArrays; TS4104 caught it in CI atenv-preserve.ts536/537 and the frames are narrowed tounknown[]at the fix head), and the merged test face is green:merge-patch+config-json-serialize+config-change-paths+source-value-projection25/25,env-preserve+ the stack-safe and authored own__proto__suites 51/51, andio.write-config+io.write-reread+io.write-prepare182/182.Test timings
node scripts/run-vitest.mjs src/config/config-change-paths.test.ts src/config/config-json-serialize.test.ts- 2 files / 10 tests pass, 1.59s wall.src/config/env-preserve.test.ts(86 tests, including the 5,000-level round-trips, the three authored own__proto__repros, and the unchanged two-row array repro),src/config/merge-patch.test.ts(13 tests including the 5,000-level diff/apply pair), and the newsrc/config/source-value-projection.test.ts(2,000-level edit + unchanged-clone) all pass, plus the full config write face (io.write-config.test.ts+io.write-reread.test.ts+io.write-prepare.test.ts, 377 tests) in 266s.How Was This Tested
node scripts/run-vitest.mjs src/config/io.write-config.test.ts src/config/io.write-reread.test.ts src/config/io.write-prepare.test.ts- all pass at this head (182 across the three files at the round-2 merge head; main reorganized the suites since the first stage).node scripts/run-vitest.mjs src/config/env-preserve.test.ts src/config/merge-patch.test.ts src/config/source-value-projection.test.ts src/config/config-json-serialize.test.ts src/config/config-change-paths.test.ts- all pass.node scripts/run-vitest.mjs src/config/env-preserve.test.ts- the three authored own__proto__repros are red before the settlement fix and green at this head, and the unchanged two-row array repro is red at the pre-fix parent49cd9710ccf(rows drop their own key, identities unmatched) and green at this head.writeConfigFileFromContextentry.config set+config getmatrix above at depths 600-2,400, main vs this head.node_modules/.bin/oxlint -c .oxlintrc.jsonand the repo formatter are clean on touched files.Compatibility
Written bytes are unchanged (differential-tested reimplementation of the exact platform call it replaces, plus hash/reread assertions), change detection returns the same paths in the same order, merge-patch key ordering and skip-when-empty semantics are preserved, env-ref restore keeps document key order and its fail-closed error behavior, and projection keeps its sentinel/delete semantics. No schema, state, or public contract changes. The settlement fix changes one observable behavior: an authored own
__proto__key now survives the env-ref restore and map-restore output as inert own data instead of being silently dropped by the inherited setter (main dropped it as well; the replacedstructuredClone/fromEntrieswalks kept it), and the comparison tree keeps main's own-property semantics. Documents deep enough to crash any of the five repaired stages now complete the entire write leg (runtime-basis inputs); the remaining ceilings - CLI mutation-runner clone, read-chain include resolver and pre-scan, and the retained source-inputstructuredCloneplus array-identity/escaped-reference recursion noted above - are outside the five repaired stages and unchanged by this PR.