Skip to content

improve(build): cut measured full-build time by 51–59% - #165271

Merged
obviyus merged 5 commits into
openclaw:mainfrom
huntharo:fix/typescript-declarations-once
Oct 6, 2026
Merged

obviyus merged 5 commits into
openclaw:mainfrom
huntharo:fix/typescript-declarations-once

Conversation

@huntharo

@huntharo huntharo commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Full builds repeatedly compile overlapping TypeScript declaration graphs. This PR compiles the full public declaration graph once, while retaining a separate SDK-only program for CI artifact builds.

Changes

  • Consolidate full-build declarations without disabling type checks or publication/input-boundary checks; retain SDK-only declaration selection and distinct cache identities.
  • Normalize OPENCLAW_RUN_NODE_SKIP_DTS_BUILD to "0" or "1" from the resolved declaration choice in resolveTsdownBuildInvocations, so config construction agrees with CLI flags, explicit main-config selections, and watchers. Explicit non-main configs retain their original environment.
  • Correct the memory-floor comment: the current build has four invocations; the 4352 MB floor came from measurements of the former eleven-invocation build's unchanged runtime graph, not a new declaration-memory guarantee.
  • Document that the wrapper must select exactly one of the full and SDK-only declaration groups. No new selection environment variable is introduced.
  • Leave the cache warmer unchanged: adding an SDK-only seed before or after the full build still produced signature-mismatch in fresh CI-artifact consumers. The merge-base 9f4a64d5b1 also misses both SDK partition caches with signature-mismatch after the same full-build-cache-only transfer. There is no demonstrated loss of a working warmer-to-CI cache hit; adding an extra CI-artifact build would add cost and is not included.

Evidence

Contributor measurements (historical revisions and caveats preserved below):

Full build Before After Reduction
M2 Max, two fresh builds per revision 618.00 s 251.88 s 59.2%
Linux ARM64, one expanded-VM run per revision 1204.55 s 595.10 s 50.6% (provisional)
Memory measurement Before After
Historical Linux whole-build cgroup peak 10.60 GiB 9.80 GiB
Historical largest sampled declaration compiler RSS 8.55 GiB 7.94 GiB
Historical GNU time largest-process RSS 8.62 GiB 8.97 GiB
Current isolated 4-CPU / 16-GiB, no-swap cold full build Not repeated for comparison 11,280,527,360 B (10.51 GiB), 303.28 s, exit 0, no OOM

The current cold run used Node 24.16.0 and NODE_OPTIONS=--max-old-space-size=8192. Its cgroup also included dependency setup before the build (setup peak was below the final build peak). This is local ARM64 Docker evidence, not a CI-runner cgroup measurement. Separately, Node 24 CI-runner proof checked out 108fbef92a63f42dcd47963820f554d0cd700caf, ran cold full pnpm build with the same Node heap setting, and passed: full declaration cache record-unavailable, writer 2m35.8s, no OOM. The pushed follow-up changes comments only; no build behavior changed after that CI proof. Historical timings are not measurements of the current rebased head.

  • Eight changed build/declaration test files: 285 passed, 4 skipped, Vitest 141.87 s (wrapper 143.80 s).
  • Real tsgo script and root-test lanes passed; git diff --check passed.
  • Original head 108fbef92a63f42dcd47963820f554d0cd700caf: transferring only the full-build cache into a pristine same-head consumer gives SDK record-unavailable, matching the observed CI run. The attempted SDK-only seeds produce a record but still miss on signature; no zero-compiler cache hit is claimed.
  • Merge-base transfer: cold full build exited 0 in 924.86 s; clean build:ci-artifacts exited 0 in 170.93 s, with both openclaw-dts-plugin-sdk-1 and -2 logging signature-mismatch (SDK writer 1m42.5s). The full and CI profiles have different generated resolution namespaces, including AI declarations/hashed JS and dist-runtime declaration links. This baseline run was for cache provenance, not a controlled performance comparison.
  • listReplaceableTsdownDeclarationOutputs includes all 151/151 emitted SDK entry declarations, so full declaration publication can replace the SDK-only generation.

No overlap with Pash/Sarah changes in the maintainer follow-up files.

Thanks @huntharo for the build optimization, measurements, and detailed original evidence.

Original contributor PR description (preserved in full; historical claims apply to its listed revisions)

Workflow caveat: If this slows down or causes a problem in a workflow the team uses, please send me the workflow or command, relevant logs, and environment details, and revert the change. I’ll investigate and see whether I can address that case.

Thanks for your work on OpenClaw. I ran into long build times while working on the project and investigated the repeated TypeScript declaration compilation.

What Problem This Solves

Full source builds repeatedly compile substantially the same TypeScript declaration graph, extending complete builds to 10–20 minutes on the tested machines.

Related: #98757 (declaration reuse), #157783 (native compiler memory).

User Impact

The complete pnpm build took less than half as long on both tested hosts. Both revisions completed successfully, including runtime bundling, public declarations, UI, and final CLI metadata.

Full build: hardware and conditions Baseline Candidate Observed reduction
Apple M2 Max, 12 CPU cores, 32 GiB RAM; default settings; mean of two fresh-worktree builds per revision 618.00 s / 10m 18s 251.88 s / 4m 12s 59.2%; 2.45Γ— faster
Linux ARM64 VM, six vCPUs, 15.07 GiB RAM, 4 GiB swap; 8192 MB Node heap override; one run per revision 1204.55 s / 20m 05s 595.10 s / 9m 55s 50.6%; 2.02Γ— ratio, provisional

The Mac ran macOS 26.6.2 (25G83); Linux ran kernel 7.0.0-34-generic. Both hosts used Node 24.21.0, pnpm 12.5.1 and native TypeScript 7.1.0-dev.20260920.1. Comparisons are within each host, not between machines. Dependency setup was excluded.

Linux qualification: declaration programs and caches were fresh, but dist-runtime and two generated viewer assets remained between runs. Its full-build timing and aggregate-memory comparisons are provisional. The Mac measurements used genuinely fresh worktrees. Neither result promises the same speedup on other hardware.

No declaration-memory increase was observed in the successful Linux pair. Both revisions failed on the smaller 5.26 GiB and 7.22 GiB VM tiers; this change does not establish support for successful builds at those memory sizes.

Why This Change Was Made

The seven nonempty public declaration programs repeatedly consume overlapping inputs. This change compiles their existing 198 public roots in one program and removes the subsequent SDK writer from full, package and smoke builds. SDK-only and CI artifact builds retain a separately selectable SDK program. Runtime bundling and AI/workspace package builds remain separate.

The speedup comes from eliminating repeated compiler work while retaining type checking and declaration publication checks. The diagnostic categories, compiler settings and tested failure cases are detailed below.

The tradeoff is coarser cache invalidation: a change to any consumed full-program input invalidates the full declaration generation. Full and SDK-only caches remain distinct; default caches remain worktree-local, with opt-in sharing through the existing BUILD_ALL_CACHE_ROOT.

Earlier upstream work deliberately partitioned declarations to address OOMs under a different compiler/source graph. The smaller-builder history and current memory measurements are recorded below.

Evidence

Declaration work removed

These writer stages are included in the total build times above.

Public declaration work Baseline Candidate Observed reduction
M2 Max: combined writers, mean of two cold builds 450.30 s 88.55 s 80.3%; 5.09Γ— faster
Linux: initial writer plus subsequent SDK writer 710.6 + 241.8 = 952.4 s 203.9 s 78.6%; 4.67Γ— ratio
Public writer invocations 8: seven nonempty programs and one empty SDK partition 1 full program Repeated compilation removed
Compiler input memberships across programs, Mac receipts 107,895 18,029 Same physical input union, fewer repeated memberships

Output coverage

Verified property Baseline Candidate
Selected public declaration roots 198 198, identical selection
Distinct physical compiler inputs, Mac receipts 18,029 18,029, identical union
Expected public declaration entrypoints 198/198 198/198
Expected SDK entrypoints, included above 151/151 151/151
Bundled .d.ts files, including shared chunks, Mac 436 440
Expanded Linux exact-head build stamps Both stamps; inputsClean=true Both stamps; inputsClean=true

Entrypoint coverage and tested consumer compatibility are preserved. Bundled chunk layout changes, so this is not a byte-identity claim between baseline and candidate or exhaustive equivalence of every public type.

The separate candidate cross-worktree cache test did establish byte identity: all 440 restored declarations matched the seed generation, with the same 198-root/18,029-input receipt and zero compiler invocations.

Error detection and publication checks retained

This change does not disable type checking or relax the listed declaration checks. The native emitter still collects configuration, program, global, syntax, binding and semantic diagnostics and rejects diagnostic or emit failures. It still forces noCheck: false; the existing strict and skipLibCheck settings are unchanged.

Problem Retained detection or protection Evidence
Invalid types, syntax, configuration or missing exports The same native diagnostic collection and emit-failure handling Existing fixtures reject semantic TS2322, missing-export TS2305, syntax TS1109/TS1110, and invalid configuration
Missing public declarations, incomplete declaration references or absent compiler receipts Required-output checks, relative declaration-closure validation and successful membership receipts before publication Same publisher implementation; missing-entry/declaration/receipt fixtures fail and preserve the previous generation
Source or resolution inputs changing during compilation Before/after input and topology validation; cache identity includes consumed inputs and generator configuration Mutation fixtures reject changed inputs and retain previous output/cache bytes; relevant edits invalidate cached declarations
Inputs escaping the checkout through references, aliases or symlinks The existing declaration filesystem boundary Escaped-input fixtures fail before publication
Invalid SDK consumers or loss of class-private type identity Consumers still typecheck emitted declarations using strict settings Positive assignments across SDK subpaths pass; empty-object impostors are required to fail; external Apache Arrow types retain tested compatibility
Missing SDK exports or invalid CLI bootstrap imports check-plugin-sdk-exports and check-cli-bootstrap-imports remain in full build plans Successful full builds retain these checks; both expanded Linux runs completed bootstrap, SDK export and final metadata checks

Source comparison confirms that the native emitter, diagnostic collector, root TypeScript configuration, input snapshot/boundary, declaration publisher, sanitizer, and SDK/CLI check implementations are unchanged. The focused tests exercise these protections through the existing build and consumer paths. This supports the named protections exercised here; it is not an exhaustive proof that every possible program produces identical diagnostics after graph consolidation.

Validation Result
Focused remote validation, eight files 288 tests passed; three Windows-only skips; harness wall 158.81 s
Independent review No actionable regressions; reported 256 passing tests across seven files and three platform skips; diff checks passed
Full build on Mac Both revisions passed twice from fresh worktrees
Full build on expanded Linux Both revisions passed once; all expected declarations and clean-input stamps present
Linux UI budget report Both printed the same nonfatal startup-JS gzip violation: 365.0 KiB versus 364.7 KiB; full builds exited 0

The benchmark did not add or alter tests. No whole-repository test sweep or Windows build is claimed. The validation above comes from the recorded exact-revision builds and focused tests.

Differential defect-detection campaign

No baseline-rejected defect was accepted by this PR in the eight demonstrated classes below. A bounded campaign compared exact baseline e9edda349faee43c13244cf3f4547fcbcb9c37fe with exact candidate a579a1b15f2a8ce13933294ebb2111e0a2324ad1. It passed 44 observations: 20 intentional rejection executions and 24 valid controls. The harness passes by asserting that defective inputs fail; every counted valid control compiled successfully.

Injected defect Baseline Candidate Boundary exercised
Assign a string to a number Rejects: TS2322 Rejects: TS2322 Full declarations and SDK-only writer
Missing expression Rejects: TS1109 Rejects: TS1109 Full declarations; syntax diagnostics
Rename a transitive export without updating its importer Rejects: TS2305 Rejects: TS2305 Full declarations and SDK-only writer
Export an inferred anonymous class with a private member Rejects: TS4094, related TS9027 Rejects: TS4094, related TS9027 Full declarations; declaration emission
Conflicting global interface property types Rejects: TS2717, related TS6203 Rejects: TS2717, related TS6203 Full declarations; semantic diagnostics
Invalid compiler module option Rejects: TS6046 Rejects: TS6046 Real generator/config admission, before compilation
Introduce an assignment error in a warm cached SDK source Cache miss; rejects: TS2322 Cache miss; rejects: TS2322 Full declarations; cache invalidation and semantic diagnostics
Assign a differently branded private class to a published SDK type Rejects: TS2322, diagnostic chain TS2442 Rejects: TS2322, diagnostic chain TS2442 Strict consumer of published SDK declarations

Each arm used its own unchanged config, grouping, writer, diagnostic, publication and cache owners from immutable Git blobs. Both used physically copied, byte-identical TypeScript 7.1.0-dev.20260920.1 compiler trees under Node 26.10.0. The synthetic graph had the same 157 selected roots: 151 SDK, one base and five plugin roots. The full declaration boundary executed the declaration-writer steps selected by each revision's real resolveBuildAllSteps("full"), through runBuildAllSteps and normal dist ownership: eight baseline invocations/seven nonempty programs versus one candidate program. These are bounded declaration tests, separate from the complete production-build measurements above.

Failed-publication observation: the candidate preserved its complete previous dist/cache generation on every rejected rebuild. Both revisions preserved cache generations. In the stale-SDK case, the baseline's successful non-SDK writer removed prior SDK outputs before its subsequent SDK writer rejected; the consolidated candidate preserved the complete previous generation. No invalid SDK or cache generation was published. This records an existing baseline limitation rather than an additional unrelated fix.

This campaign is PR evidence, not a new revision-pinned recurring CI suite. Its small synthetic contents do not prove every production graph, cross-root ambient/module-augmentation topology, or future compiler behavior. The ambient-conflict case uses declarations within one transitive module. Initial setup/partial-boundary attempts and a base-to-SDK positive control already rejected by baseline were excluded from the 44 counted observations; the counted nominal consumer controls both use the same SDK public type.

GitHub Actions and check routing audit

All 111 tracked workflow files and 35 tracked action files have identical paths, modes and Git blob IDs between the same baseline and candidate. package.json and TypeScript checking configurations are unchanged. Separate production, test and script type-checking/lint routes and the openclaw/ci-gate implementation remain unchanged. The audit did not inspect live GitHub branch-protection settings.

The effective ciArtifacts profile retains its steps, runtime-only bundling override, SDK-only roots, bootstrap checks and SDK export gate. Its declaration grouping consolidates into one SDK program. Full/package/smoke profiles remove the repeated SDK writer because the full program now includes those roots; their export/bootstrap checks remain. Compiler diagnostic collection and publication/input-sealing owners are unchanged. This source audit supports the named retained contracts; the executed negative controls above establish the listed defect detections.

Reproduce the workflow/action identity comparison
BASELINE=e9edda349faee43c13244cf3f4547fcbcb9c37fe
CANDIDATE=a579a1b15f2a8ce13933294ebb2111e0a2324ad1
git diff --exit-code "$BASELINE" "$CANDIDATE" -- .github/workflows .github/actions package.json
git ls-tree -r "$BASELINE" -- .github/workflows .github/actions
git ls-tree -r "$CANDIDATE" -- .github/workflows .github/actions

Both revisions have workflow tree 793776b49ddb8d33fd39d1aa7d436058023c3212 and action tree 550be032e735d2aa1f13868fb07e6dca13652b56. Later unrelated changes on upstream main were excluded from this exact-revision comparison.

Linux memory: aggregate and process measurements

Successful expanded-VM pair Baseline Candidate Interpretation
Whole-build kernel cgroup memory peak 10.60 GiB 9.80 GiB 7.5% lower observed aggregate peak
Initial public declaration stage aggregate RAM, sampled 10.58 GiB 9.80 GiB Declaration stage reached and completed on both
Largest native declaration compiler RSS, sampled 8.55 GiB 7.94 GiB 7.2% lower observed declaration RSS
GNU time largest-process maximum RSS 8.62 GiB 8.97 GiB 4.1% higher; process sampling attributes both maxima to unchanged runtime bundling
Build cgroup swap peak 0 B 0 B No build swap charged
Attributable OOM / OOM kill events 0 / 0 0 / 0 Neither full build failed

The process and aggregate metrics answer different questions. Cgroup accounting includes descendants, charged cache/kernel memory and a small measurement worker; RSS is per process. Stage samples were taken every 250 ms. The single pair, retained generated outputs, natural filesystem cache state and background workload mean these observations do not establish a causal or portable peak-memory reduction. The Mac cold runs recorded largest-process RSS around 8.8–9.3 GiB, not aggregate memory.

Inherited CI dependency audit, resolved from upstream

Prior head 32f47ef4133b149913329a45581f63cbee25fc5d passed build-artifacts but failed the production dependency audit for [email protected], GHSA-68fv-2mgg-jv7q. The current branch is rebased onto upstream main 9f4a64d5b1309fd8190fa92fa2060dc3381bda5a, which includes upstream's merged fix #165902, commit 9c66e8f40532ffb29b658283168f3034f0f06c62. The workspace override and lockfile now pin patched [email protected] with upstream's exact-version release-age exception; the production audit remains enabled.

The actual node scripts/ci-production-audit.mjs entrypoint passed locally on the rebased branch: npm bulk returned no HIGH-or-higher production advisories. Frozen lockfile-only validation passed all 1,710 supply-chain entries; the dependency pin guard checked 716 specs across 198 tracked manifests with zero violations. The lockfile, workspace settings, package scripts and workflows have no PR-specific changes relative to the rebased upstream main. CI for the new head is pending.

Exact revisions

Revision Commit
Baseline for both hosts e9edda349faee43c13244cf3f4547fcbcb9c37fe
Mac measured candidate ba458ece69c6944c96a381a4b7b4be9e93f6b47f
Rebased benchmark candidate (Linux) 85bdef58103068cd0e93f01a4a3dd2e402586ee6
Identical complete tree of both benchmark candidates ab36e67b4db7c5bcbfec791532ced5a5535c1a7c
Post-benchmark test-helper CI repair a579a1b15f2a8ce13933294ebb2111e0a2324ad1
Historical upstream conflict repair 32f47ef4133b149913329a45581f63cbee25fc5d
Current PR head (rebased with upstream audit fix) 108fbef92a63f42dcd47963820f554d0cd700caf
Current upstream rebase target 9f4a64d5b1309fd8190fa92fa2060dc3381bda5a
Upstream main integrated by conflict repair e72e0807acfa8c7ee3fa1fe429cc59e9d6c1c6e4

The rebased benchmark candidate's sole parent is the exact baseline. Rebase changed ancestry without changing measured source: the candidate-to-candidate diff is empty. Dependency manifests, workspace configuration and lockfile match between the baseline and candidate. Local HEAD, the fork branch and the PR head were verified equal; the worktree is clean.

Commit a579a1b15f2a8ce13933294ebb2111e0a2324ad1 added only the CI lint repair in test/scripts/tsdown-declaration-resolution.test.ts: the SDK fixture wrapper keeps its environment argument optional and delegates the default to the existing runWriter helper. That commit left production and build sources unchanged from the benchmarked candidate. The timings remain measurements of the exact benchmark revisions above.

Test-helper repair validation: targeted root-test lint, formatting and diff checks passed. node scripts/run-vitest.mjs test/scripts/tsdown-declaration-resolution.test.ts -t 'uses local explicit references and seals real inputs' --maxWorkers=1 passed both selected SDK/unified cases (23 other cases unselected by the filter); harness wall 13.24 s, Vitest 12.13 s. No test cases or CI commands were added. Full-build benchmarks were not repeated for this test-helper-only change.

Historical upstream conflict repair: commit 32f47ef4133b149913329a45581f63cbee25fc5d merged upstream main e72e0807acfa8c7ee3fa1fe429cc59e9d6c1c6e4. The single textual conflict in scripts/tsdown-build.mts was resolved by retaining both removals: upstream's redundant heap helper and this PR's retired partition-concurrency helper. Upstream's direct memory-budget calls, output scanning and managed-child cleanup remain. The optimization delta still covers the original 18 paths; it introduces no workflow/action, package-script or root TypeScript-configuration changes relative to the integrated main.

An independent review found no merge-repair regressions. The eight focused build-plan, writer, native-resolution and artifact-ownership files passed 286 tests with three Windows-only skips (Vitest shard 342.83 s); targeted script lint, formatting and diff checks passed. No new test cases were added by this repair. Full-build benchmarks and the 44-observation differential campaign were not repeated after integrating upstream; those results remain historical evidence for their listed exact pins.

Current rebase validation: the declaration/build owners and all eight focused test files are byte-identical to the prior head that passed 286 tests with three Windows-only skips. The rebase reapplied the already-reviewed conflict resolution. That focused proof was reused; the live production audit and frozen dependency checks were run for the new lockfile. Full-build benchmarks and the differential campaign remain evidence for their original exact revisions, and were not repeated after rebasing.

Timing protocol, individual runs, cache behavior, and validation command

Hardware: Mac14,6 / Apple M2 Max / 12 CPUs / 32 GiB RAM. /usr/bin/time -l and a monotonic harness recorded each command, with load, memory-pressure, vm_stat, and swap observations before/after. The RSS column is the largest process, not aggregate subprocess memory. Builds, setup, and tests were serialized. No OS caches were flushed, shared pnpm store cleared, unrelated process killed, or build admission/ownership fence bypassed.

All six owned worktrees used pnpm install --frozen-lockfile, identical dependency versions, and lock SHA-256 a5ab3b496b8d21308fa04bf907a0f7eeab38ad055c5abe766becc4a5d7a3f029. Install/setup time was measured separately; the first install took 42.87 s including downloads, and subsequent installs took 5.97–9.27 s. Node 24.21.0 was explicitly selected because the machine's default Node 24.14.1 was below the supported floor.

Cold means a new owned worktree with no dist or build cache. Run order was B1 β†’ C1 β†’ C2 β†’ B2. Every run below exited 0 using the default full pnpm build, without private-QA, runtime-only, or update selectors.

Run Full wall s Full writer s SDK writer s Writer total s AI phase s Packages phase s Largest-process RSS GiB
Baseline 1 648.52 401.6 74.9 476.5 12.7 94.5 8.834
Candidate 1 251.23 88.3 omitted 88.3 12.3 88.8 9.004
Candidate 2, new worktree 252.53 88.8 omitted 88.8 12.4 89.1 8.906
Baseline 2 587.48 358.1 66.0 424.1 12.2 89.6 9.281

AI/packages phases also perform runtime bundling and are separate from the changed public declaration writers. Cold full-build spread was 61.03 s / 9.9% of the baseline mean and 1.30 s / 0.52% of the candidate mean. Paired full-build ratios were 2.58Γ— and 2.33Γ—. Initial baseline load included setup activity (1-minute load 11.89 β†’ 4.25); later cold-run endpoints were 3.14–5.40. Swap usage fell from 2345.81 MiB to 2329.81 MiB, then stayed flat.

Unchanged same-worktree full builds:

Run Full wall s Public declaration behavior
Baseline warm 1 469.25 Recompiled: signature mismatch
Candidate warm 1 171.77 Recompiled: signature mismatch
Baseline warm 2 86.94 Restored caches; zero declaration compilers
Candidate warm 2 70.93 Restored cache; zero declaration compilers

The first warm run is a state transition: AI/package cache hits switch to runtime-only bundling, changing generated JS filenames under workspace aliases and invalidating conservative declaration namespace signatures. Both revisions exhibit it. The second warm run restores correctly. The settled warm comparison is one pair, not repeated-run statistics. Open #138385 targets this separate cache-stability issue.

A genuinely new candidate worktree used its own default .artifacts/build-all-cache, logged record-unavailable, and rebuilt in 252.53 s. Default caching therefore does not automatically reuse another worktree's artifacts.

For explicit sharing, two additional clean candidate worktrees used one task-owned absolute BUILD_ALL_CACHE_ROOT and ran:

node --import ./scripts/tsx.mjs scripts/write-unified-entry-dts.ts

The seed missed and compiled once in 104.50 s. The clean consumer restored the complete generation in 10.84 s, with zero compiler invocations and no copied dist or cache directories. These are standalone declaration-writer times, not full-build times. The baseline timing comparison above includes both its full and SDK writer stages.

Focused validation ran outside measured build intervals:

node scripts/run-vitest.mjs test/package-scripts.test.ts test/scripts/build-all.test.ts test/scripts/dist-artifact-ownership.test.ts test/scripts/tsdown-build.test.ts test/scripts/tsdown-config.test.ts test/scripts/write-plugin-sdk-entry-dts.test.ts test/scripts/write-unified-entry-dts.test.ts test/scripts/tsdown-declaration-resolution.test.ts --maxWorkers=1

Eight files passed: 288 tests passed / three Windows-only skips; harness wall 158.81 s. Coverage includes config/build plans, full/SDK cache selection and invalidation, failure preservation, native declaration consumers/resolution, and output ownership. No tests were added or changed for the benchmark. No whole-repository test sweep or Windows build is claimed. The Linux full-build results and their separate limitations are recorded in the Linux evidence section.

Linux protocol, exact memory accounting, output checks, and smaller-VM results

Host: Linux 7.0.0-34-generic, ARM64, six vCPUs, 16,181,084,160 B (15.07 GiB) physical RAM and 4,294,963,200 B (4.00 GiB) swap. Each exact revision ran once, sequentially, baseline then candidate:

OPENCLAW_TSDOWN_MAX_OLD_SPACE_MB=8192 pnpm build

This explicitly approved Node heap allowance doubles the earlier 4352 MB attempt's allowance; it is not a measurement of default heap settings. GOMEMLIMIT and GOGC remained unset. The Node override does not cap the native Go TypeScript compiler.

Both builds completed final CLI metadata with exit 0. The baseline had eight public writer invocations/receipts (seven nonempty programs, one empty partition); the candidate had one. All 198 public declarations, including 151 SDK entries, were nonempty. Both exact-head stamps recorded inputsClean=true.

The retained dist-runtime directory and two generated viewer assets prevent calling this a perfectly cold full-output comparison. Main declarations and their compiler receipts/cache roots were fresh, and all declaration cache lookups missed.

The exact whole-build cgroup memory peaks were 11,376,349,184 B baseline and 10,525,024,256 B candidate. Stage sampling every 250 ms recorded initial public declaration aggregate peaks of 11,360,845,824 B and 10,523,209,728 B, and native compiler RSS peaks of 9,184,444,416 B and 8,527,298,560 B. Baseline's subsequent SDK stage sampled 9,089,835,008 B aggregate and 6,742,310,912 B native RSS.

GNU time reported largest-process maximum RSS of 9,036,148 KiB and 9,404,684 KiB. The corresponding largest sampled runtime Node children used 9,251,688,448 B and 9,612,697,600 B, identifying runtime bundling as that maximum. User/system CPU time was 1269.72/189.98 s baseline and 566.73/142.84 s candidate.

Each build used a separate task-owned systemd scope. The observer remained outside; a small worker held the scope until final kernel counters were read. Cgroup accounting includes all descendants, charged file cache/kernel memory and that worker. GNU RSS is a largest-process metric; stage samples are lower bounds sampled every 250 ms. Summed RSS was not substituted for aggregate memory. All effective cgroup memory/swap limits were unlimited, both build scopes had zero swap peaks and zero OOM event deltas, and kernel queries found no OOM entries.

Both CLI bootstrap and SDK export checks passed, both exact-head build stamps recorded inputsClean=true, and all 198 public declarations including 151 SDK entries were nonempty. Both builds completed final CLI metadata. Both UI budget reports printed the same startup-JS gzip violation (365.0 KiB versus 364.7 KiB); the default full build continued and exited 0. These are successful builds, not a claim that every budget report was green.

Available RAM at baseline/candidate start was 13,026,013,184 B / 12,809,457,664 B. Normal desktop and background workloads continued; no Gateway was identified. Unchanged package work took 93.1 s / 222.4 s, runtime bundling 34.5 s / 43.5 s, and UI work 55.5 s / 17.0 s. These variations limit full-build timing attribution. No workloads or OS caches were normalized. The tiny system swap changes were outside the build cgroups.

The pair reused the same complete task-owned frozen install, with isolated linking and clone-or-copy imports. No reinstall or dependency upgrade occurred between arms. Separate empty build cache roots were used; main, package and extension outputs, native protocol outputs and compiler receipts were cleared. The retained outputs noted above limit the full-build comparison. Install-generated Kysely inputs were preserved identically; disk capacity was sufficient.

Earlier separately authorized pairs used the same exact revisions:

VM tier and command setting Baseline Candidate
5.26 GiB RAM, two vCPUs; default heap selection Admission refusal at 1725 MB resolved heap Admission refusal at 1532 MB resolved heap
5.26 GiB RAM, two vCPUs; 4352 MB override Global OOM in first public declaration program Global OOM in unchanged runtime bundling, before public declarations
7.22 GiB RAM, four vCPUs; 4352 MB override Native compiler OOM during public declarations Native compiler OOM during public declarations

The default refusals occurred before compilation because both resolved heaps were below the 4352 MB admission floor. On the 5.26 GiB tier, attributed OOMs truncated builds after approximately 1083.90 s / 341.34 s, with cgroup RAM peaks 4.37 / 4.42 GiB and swap peaks 3.34 / 3.07 GiB. Those are independent peak counters, not simultaneous RAM-plus-swap totals. On the 7.22 GiB tier, aggregate OOM-truncated peaks were 6,551,916,544 B / 6,720,172,032 B. Neither smaller tier completed the required outputs; different ambient starting conditions and OOM truncation prevent causal memory ranking or speedup claims. No candidate-only failure occurred against a passing baseline.

Related merged, open, and closed work

The history shows continuing demand for this work, with real memory and declaration-correctness constraints. The original partitioning change documented a Linux OOM at a 6.5 GB cgroup ceiling and a subsequent partitioned build at a 4.8 GiB peak. That historical compiler/source graph differs from the exact revisions benchmarked here:

Related work Relationship
Issue #98757, closed by merged #98758 Canonical SDK declaration reuse already landed in July to eliminate a second package graph. Later staging/cache work evolved the build into the current separate writer programs.
Merged #108790 and #116021 Sequential major build stages and then declaration partitions addressed measured OOMs. This PR preserves major-stage ordering but consolidates the public declaration programs.
Merged #145090 and #149592 Later optimizations overlapped two staged compilers only when sufficient memory was available. This change removes repeated public compiler work instead of overlapping it.
Open issue #157783 and #157992 Native TypeScript children can exhaust roughly 10 GiB-class Linux hosts. The proposed Go memory budget is complementary; this PR does not claim to close the OOM issue.
Open #138385 Separates runtime and declaration config output to fix the first-warm cache miss reproduced by this benchmark.
Open #161731, merged #164374 and #163094 Optimize input validation/discovery and prepared SDK reuse across CI checks. They do not consolidate these full-build declaration programs.
Closed, unmerged #160207 Native output streaming was rejected after matched runs showed only about 1% less peak memory, about 8.5% longer runtime, and no complete byte-parity proof. This PR retains the emitter.
Closed issue #136881, fixed by #137012, and closed issue #109105 Prior failures included an undeclared generated export in published SDK types and host/run-dependent declaration chunk topology. Existing sanitization and output checks remain, and bundle byte identity is not inferred from matching entrypoint counts.

No direct revert of this current native-program consolidation was found in the inspected history. The explicit memory-driven partitioning is the material historical counterexample and remains an unresolved compatibility consideration for smaller builders.

@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

πŸ¦žπŸ‘€
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts size: L labels Oct 5, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: πŸ‘€ ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 5, 2026
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 6, 2026, 3:10 PM ET / 19:10 UTC (Revision 8).

ClawSweeper review

What this changes

The PR compiles public TypeScript declarations once during full builds, retains a separate SDK-only build, and updates build selection, tests, and CI documentation.

Merge readiness

βœ… Ready for maintainer review

This PR remains useful: current main still compiles partitioned declaration graphs. The reviewed changes and preserved real-build evidence support the optimization, with no actionable introduced defect found. The failing dependency-audit gate remains a landing constraint, not a patch finding.

Priority: P2
Reviewed head: 11922ed6303f9775045315899fa852aec0ea4304

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with strong, revision-aware real-build evidence and no concrete correctness finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Recorded full pnpm builds exercise the changed declaration owner through the production build profile, preserve public output coverage, and show improved historical timings; current cold Docker evidence completes without OOM. GitHub comparison verifies that the final follow-up changes comments only. Historical timings remain bound to their listed revisions. Cache identities change without changing the persisted record contract.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): Recorded full pnpm builds exercise the changed declaration owner through the production build profile, preserve public output coverage, and show improved historical timings; current cold Docker evidence completes without OOM. GitHub comparison verifies that the final follow-up changes comments only. Historical timings remain bound to their listed revisions. Cache identities change without changing the persisted record contract.
Evidence reviewed 7 items Pinned introduced changes: Inspected the merge-base-to-head production and test hunks. Full profiles remove the later SDK writer because the unified declaration selection now includes SDK roots; CI artifacts retain their SDK-only writer. The stale test merge was not used to infer removal of current-main behavior.
Still necessary on current main: The fetched main revision retains eight unified declaration groups and separate SDK selections. Related merged optimizations address package duplication or compiler overlap; they do not implement this single-program consolidation.
Real build evidence and captured body identity: Read the preserved body ranges and retrieved omitted evidence with matching SHA-256 88b97ad736a1c9146f65a4e8c23c6ff367ac772dbf327655e696b3c65c77b00b. Historical fresh Mac builds completed with 198 public roots and 151 SDK entries; current Docker evidence reports a cold full build completing in 303.28 seconds on 4 CPUs and 16 GiB without swap or OOM. The discussion positively records baseline cache-transfer misses and does not claim a previously working warmer hit was lost.
Findings None None.
Security None None.

How this fits together

OpenClaw’s build pipeline turns source code into runtime bundles and public type declarations used by package and plugin consumers. The declaration owner selects compiler inputs, validates generated output, and publishes or restores the resulting artifacts.

flowchart TD
  A[Source and public entrypoints] --> B[Build profile selection]
  B --> C[Full declaration program]
  B --> D[SDK-only declaration program]
  C --> E[Compiler and input validation]
  D --> E
  E --> F[Validated artifact publication]
  F --> G[Package and plugin consumers]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Tests -38, Docs 0, Other -72. Total -110 across 18 files.

View PR surface stats
Area Files Added Removed Net
Source 0 0 0 0
Tests 9 134 172 -38
Docs 2 3 3 0
Config 0 0 0 0
Generated 0 0 0 0
Other 7 84 156 -72
Total 18 221 331 -110

Review metrics

Metric Value Why it matters
Declaration compiler work 8 public writer invocations β†’ 1 full program The recorded builds remove repeated checking while preserving all 198 public declaration roots.

Technical review

Best possible solution:

Use one validated full declaration generation and retain the SDK-only profile, with existing diagnostic, publication, and cache safeguards.

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

Not applicable to a runtime bug: source and recorded real builds establish repeated declaration compilation and the measured optimization; no builds were executed during this read-only review.

Is this the best way to solve the issue?

Yes. Consolidating overlapping inputs at the existing declaration owner removes repeated work while retaining SDK-only selection and the established validation boundaries.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a measured developer-build improvement with bounded impact and no demonstrated urgent runtime regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: πŸ‘€ ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): Recorded full pnpm builds exercise the changed declaration owner through the production build profile, preserve public output coverage, and show improved historical timings; current cold Docker evidence completes without OOM. GitHub comparison verifies that the final follow-up changes comments only. Historical timings remain bound to their listed revisions. Cache identities change without changing the persisted record contract.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded full pnpm builds exercise the changed declaration owner through the production build profile, preserve public output coverage, and show improved historical timings; current cold Docker evidence completes without OOM. GitHub comparison verifies that the final follow-up changes comments only. Historical timings remain bound to their listed revisions. Cache identities change without changing the persisted record contract.

Evidence

What I checked:

  • Pinned introduced changes: Inspected the merge-base-to-head production and test hunks. Full profiles remove the later SDK writer because the unified declaration selection now includes SDK roots; CI artifacts retain their SDK-only writer. The stale test merge was not used to infer removal of current-main behavior. (scripts/build-all.mts:194, 11922ed6303f)
  • Still necessary on current main: The fetched main revision retains eight unified declaration groups and separate SDK selections. Related merged optimizations address package duplication or compiler overlap; they do not implement this single-program consolidation. (scripts/lib/tsdown-config-groups.mts:4, cc7e664dfe34)
  • Real build evidence and captured body identity: Read the preserved body ranges and retrieved omitted evidence with matching SHA-256 88b97ad736a1c9146f65a4e8c23c6ff367ac772dbf327655e696b3c65c77b00b. Historical fresh Mac builds completed with 198 public roots and 151 SDK entries; current Docker evidence reports a cold full build completing in 303.28 seconds on 4 CPUs and 16 GiB without swap or OOM. The discussion positively records baseline cache-transfer misses and does not claim a previously working warmer hit was lost. (11922ed6303f)
  • Proof continuity: GitHub’s comparison confirms that the final head differs from the real-build proof revision only in comments in two files. The linked Node 24 compatibility job succeeded. Direct job-log retrieval was blocked by the review environment, so its checkout and compiler observations remain attributed to the preserved PR evidence rather than independently read logs. (scripts/tsdown-build.mts:644, 11922ed6303f)
  • Retained safeguards and cache compatibility: Source inspection retains native diagnostics, noCheck:false, successful compiler receipts, input sealing, complete relative declaration closure, and publication before cache finalization. The introduced delta leaves the emitter, publication owner, cache record format, workflows, manifests, and lockfile unchanged. New group identities regenerate derived caches through the existing signature owner; no stored-data model migration is introduced. (scripts/lib/tsdown-declaration-writer.mts:171, 11922ed6303f)
  • Discussion and review continuity: The previous completed review covered this same head and recorded no findings or rank-up moves. The contributor reports no candidate-only failure on the tested smaller hosts. The follow-up comment documents 285 passing focused tests, four skips, and an identical head/baseline MCP dependency-audit failure; this is not evidence of a supply-chain change introduced by the PR. (11922ed6303f)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • RomneyDa: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S πŸ¦€ challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D πŸ¦ͺ silver shellfish Proof or implementation needs work
1/6 F πŸ§‚ unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (7 earlier review cycles)
  • reviewed 2026-10-05T02:20:43.195Z sha 85bdef58103068cd0e93f01a4a3dd2e402586ee6 :: blocked before merge. :: none
  • reviewed 2026-10-05T02:37:30.324Z sha a579a1b15f2a8ce13933294ebb2111e0a2324ad1 :: blocked before merge. :: none
  • reviewed 2026-10-05T17:59:31.825Z sha a579a1b15f2a8ce13933294ebb2111e0a2324ad1 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-06T02:39:55.757Z sha 32f47ef4133b149913329a45581f63cbee25fc5d :: needs maintainer review before merge. :: none
  • reviewed 2026-10-06T02:54:44.637Z sha 32f47ef4133b149913329a45581f63cbee25fc5d :: needs maintainer review before merge. :: none
  • reviewed 2026-10-06T17:04:45.468Z sha 108fbef :: needs maintainer review before merge. :: none
  • reviewed 2026-10-06T18:45:49.114Z sha 11922ed :: needs maintainer review before merge. :: none

@huntharo

huntharo commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper There is no constrained builder issue: main fails today on a 8 GB Linux machine with 4 GB of swap running Ubuntu with graphical desktop logged in - the OS OOM kills processes including the builds. Only at 16 GB with 4 GB of swap does main pass without OOM kills. This is unchanged by the PR.

There was no difference in GHA build times, as far as I can see, as it appears that GHA handles this different can local builds (skipping the problem).

@clawsweeper

clawsweeper Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

πŸ¦žπŸ‘€
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Oct 5, 2026
@huntharo
huntharo force-pushed the fix/typescript-declarations-once branch from 32f47ef to 108fbef Compare October 6, 2026 16:55
@obviyus

obviyus commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Thanks @huntharo for the build optimization and careful measurement work. The maintainer follow-up at 11922ed6303f9775045315899fa852aec0ea4304 corrects the four-invocation/memory-floor comment and documents mutually exclusive full/SDK declaration selection. The PR body now has a concise summary, with your entire original description preserved.

The warmer remains unchanged. On merge-base 9f4a64d5b1, a cold full build followed by transferring only .artifacts/build-all-cache into a fresh same-base CI-artifact checkout misses both SDK partitions with signature-mismatch (SDK writer 1m42.5s). SDK-only seeds before and after the candidate full build also miss. Both profiles have different generated resolution namespaces, including AI declaration/hashed-JS files and dist-runtime declaration links. There is no demonstrated regression from a previously working warmer-to-CI hit, so no extra CI-artifact build cost was added.

Proof: secretless Docker cold full build on 4 CPUs / 16 GiB with no swap exited 0 in 303.28 s, cgroup peak 11,280,527,360 B, no OOM. Node 24 CI full-profile proof also passed on 108fbef9; the follow-up changes comments only. Real script/root-test tsgo lanes and git diff --check passed. Eight changed build/declaration test files: 285 passed, 4 skipped, 143.80 s wrapper wall.

Exact-head ClawSweeper is terminal/ready, with no actionable findings or before-merge items. Exact-head CI failed security-fast and its aggregate openclaw/ci-gate: npm production audit reports GHSA-6qxp-vccf-f47h for @modelcontextprotocol/client and @modelcontextprotocol/sdk. The same audit failed identically in isolated head and merge-base checkouts; manifests, lockfile, workspace settings, and audit script are unchanged by this PR. CI had zero cancelled jobs; one superseded ClawSweeper dispatch was cancelled separately. No rerun or dependency change was made. Paused for maintainer disposition; nothing merged.

@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

πŸ¦žπŸ‘€
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

Maintainer override for unrelated red CI on exact head 11922ed:

Everything else is green, and the exact-head ClawSweeper review is ready. The full-profile merged declaration compile passed cold on a GitHub-hosted runner in run 37508047355 (job 112422341862, declaration step 2m 35.8s, 8 GB heap) and in a 16 GB / 4-CPU container (11.28 GB peak).

@obviyus
obviyus merged commit b6f94b8 into openclaw:main Oct 6, 2026
130 of 134 checks passed
@obviyus

obviyus commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

Landed as b6f94b8. Thanks @huntharo, a big speedup for every full build!

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 7, 2026
Full builds compiled the public type declarations in seven partitions whose inputs overlap heavily, so most of the program was type-checked seven times. They now compile once across all 198 public entry points. A separate SDK-only declaration compile stays for `build:ci-artifacts` and `build:plugin-sdk:dts`, and the two-compile concurrency logic is removed (net -74 production lines). Build selection rejects choosing both declaration setups, and `resolveTsdownBuildInvocations` now always normalizes `OPENCLAW_RUN_NODE_SKIP_DTS_BUILD` for main-config builds.

Proof: a cold full-profile build passed on a GitHub-hosted runner (run 37508047355, declaration step 2m 35.8s, 8 GB heap) and in a 16 GB / 4-CPU container (exit 0, 11.28 GB peak). The author's measurements show full builds 51-59% faster. A warmed full-build cache never satisfied the CI SDK-only build on main either, so CI's declaration caching is unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: L status: πŸ‘€ ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: published tool-plugin declarations export undeclared __exportAll [Bug]: Plugin SDK declaration budget flakes across clean builds

2 participants