Skip to content

fix(gateway): reduce resident memory on constrained hosts - #198194

Merged
vincentkoc merged 59 commits into
mainfrom
fix/cardputer-resident-memory-20261113
Nov 14, 2026
Merged

vincentkoc merged 59 commits into
mainfrom
fix/cardputer-resident-memory-20261113

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Related: #192547

Problem and change

Gateway startup and the first model turn retain unnecessary code and independent readers on memory-constrained ARM64 hosts.

This change shares bounded store readers; retires idle workers under memory pressure; loads optional runtimes on demand; skips empty-store work; and defers optional background work until memory is available. Token-only CLI requests avoid credential database machinery. Hosts with at most 1 GiB of effective memory use the existing direct-spawn path instead of retaining the optional default broker.

Shutdown leaves idle native writers to the existing reader-first drain. The final active borrower still waits for its native handle and lease to close. The memory guard rejects Node 24's unlimited-memory sentinel while retaining finite-limit pressure deferral.

Internal unused exports are removed. No new configuration options, dependencies or persistent formats. Net added test lines: 400/400; no test-line allocation file.

Validation

  • Rebased onto 989f4a6d, preserving its independent compaction lane and bounded readers. All 52 focused reader, compaction and lifecycle checks pass.
  • Final production shutdown repair: 78 pinned-Bun checks and 13 explicit Node 24 reply/idle checks pass. The four reply cases fail before the repair. Types, scoped lint, formatting and independent P0–P2 review pass.
  • Real Linux ARM64 restart E2E passes with the final production guard in a freshly built native Docker image: clean-close seal, plugin cleanup and process handoff (7.817-second test). The supported prebuilt-runtime route was used after declaration preparation failed before test execution.
  • Earlier import, reader-lane, lifecycle, prewarm, build-graph, restore and backend-custody proofs retain their actual revision labels in native review. The original 50-selector backend replay passed 653 cases with five skips after cleanup repair.
  • Gateway fixtures now preserve worker limits, wait for committed cron state, correlate WebSocket response IDs, and join independently owned background work before cleanup. Worker-budget regression reproduces two requested workers becoming 17; the fix passes 76 config checks and 175 real Gateway cases on Linux ARM64.
  • Latest test-only change retains every 30-second server wait and success assertion, and gives the transport 35 seconds to receive the response. All five subagent cases pass locally. WebSocket correlation has deterministic red/green proof and seven passing cases; the agent-deletion diagnostic group passes 486 cases. These changes do not establish the cause of earlier intermittent hosted delays.
  • Scoped types, lint, formatting, line gates and fresh independent P0–P2 reviews pass. Production code is unchanged after 216ba2e7.
  • Original ARM64 memory acceptance at 523851ff: 916.641 MiB outer peak below 928 MiB, health in 7.345 seconds, a real OpenAI gpt-5.4-mini reply in 19.498 seconds, and a 60.382-second healthy soak. Limits: 768 MiB service, 1 GiB outer/client, one CPU, V8 old/young 256/4 MiB. No OOM, restart or swap.

CI and limits

Current head: 3ba05113eda4f5c037881badd2f43bb61312384e. CI run 43647908332, attempt 1, completed with 139 successful jobs, six failed test jobs, a downstream failing CI gate and 23 skipped jobs. All PostgreSQL jobs and the build-artifact job passed.

Six failed test jobs are attributed to existing baseline behavior; the aggregate gate consequently remains failed:

  • Planner coverage: two cases report 591 entries instead of 590. Exact baseline 0740281e reproduces both; upstream moved a recovery test to an isolated owner without removing it from whole-config inventory. All 12 owner inputs remain unchanged through this run's base and merge.
  • Activity browser test: upstream #199168 removed the browser-local tool feed but left a test waiting for .activity-empty. A fresh browser build on this run's exact base 18a62d6f fails the same case before subscription or event injection. All 22 inspected test, UI, build and dependency inputs match the tested merge.
  • Windows lifecycle: both stop/enable and suspension triage cases reproduce on baseline 27592cd3 (2 failed, 25 passed), with the same Bun-to-Node worker serialization mismatch and missing mocked task operations.
  • Fresh Doctor: the split-root update case reproduces on 27592cd3 (1 failed, 11 passed), with the same deserialization error before pending-recovery reporting.
  • Candidate admission: both deadline cases and fresh-profile authority reproduce on 27592cd3 (3 failed, 13 passed).
  • Model list: the stale account-a-only presentation was reproduced on baseline 2f6061c9; the retained native review records that run, although its raw log was not located. The failing assertion precedes replacement-time dispatch. The inspected owner still returns its retained published list while replacement discovery is pending.

All 73 inspected source inputs are unchanged between the current run's exact base and tested merge. Earlier baseline proofs retain their actual revision labels; they are not reported as new runs on the current head.

The automated failure report and the operator's baseline attribution are separate evidence. Failed CI is not described as green. Native landing must verify current review/security requirements and the exact completed attempt.

Earlier runs and revision-specific evidence remain in native review: e1013f37, a28b821e, 8db1930a, 7d758ade, and 88641423. Passing local replays do not explain historical timeouts.

The memory measurement belongs to 523851ff, not the latest head. The physical Cardputer is offline; physical-device operation and a 512 MiB service are not qualified. Shared queues and first-use imports can add latency, and sustained memory pressure can delay optional work.

@vincentkoc vincentkoc self-assigned this Nov 13, 2026
@clawsweeper

clawsweeper Bot commented Nov 13, 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 gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: L labels Nov 13, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 13, 2026
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR reduces Gateway memory use by sharing readers, retiring idle workers, loading code on demand, and deferring optional work under memory pressure.

Example: Linux ARM64 with a 768 MiB service limit, 1 GiB outer limit, one CPU, and no swap.

  • Before: The linked issue records an OOM during the first request and an approximately 992 MiB outer peak.
  • After: The PR reports a real model reply, a healthy 60-second soak, a 916.641 MiB outer peak, and no OOM on the reviewed head.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The reported runtime improvement has clear value, but upgrade validation remains incomplete and a narrow introduced import cycle blocks CI.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Partial
User problem: A constrained ARM64 Gateway can become ready and then run out of memory before its first model reply.
Reason: The maintainer supplies a concrete acceptance result and accepts the latency and scheduling tradeoffs for this staged improvement.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep open: this maintainer-backed memory reduction addresses a documented ARM64 failure, but introduces a credential import cycle that blocks the architecture check.

Priority: P2
Reviewed head: 523851ff5b0e80638f892d9c8fa8a3bdd4f2fdd8

Before merge

  • Break the new credential type-import cycle (P2) - Importing ClientCredentialResult here closes device-identity-material.ts → client-credential-store.ts → client-credential-operations.ts → device-identity-material.ts. The repository’s Madge guard includes type-only imports, so erasure at runtime does not avoid the failure; the current-head architecture check reports that guard failing. Keep this material module as a leaf by placing the result adapter above it or using an independent shared contract, then update its callers.

Findings

  • [P2] Break the new credential type-import cycle — src/infra/device-identity-material.ts:4

Tests

  • Missing end-to-end proof: The PR owner should provide a v2026.11.3-to-candidate upgrade run preserving settings, credentials, and sessions while completing a real request under the constrained profile; redact secrets and non-public endpoints.
Agent review details

How this fits together

Gateway requests use worker-owned session and credential readers; memory-pressure signals now reclaim idle resources and defer optional maintenance while active requests retain their existing owners.

flowchart TD
  A[Gateway requests] --> B[Session reader owner]
  B --> C[History and search pools]
  B --> D[Shared session store pool]
  E[Memory pressure] --> B
  E --> F[Background schedulers]
  A --> G[Direct or broker spawning]
Loading

Technical review

Best possible solution:

Keep identity material independent of credential operations by moving result adaptation above that leaf while preserving the measured memory reductions.

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

The linked issue supplies a concrete ARM64 OOM profile, and source inspection confirms retained readers and eager imports; this read-only review did not execute the workload.

Is this the best way to solve the issue?

Consolidating existing owners and removing eager work fits the measured problem; the new credential dependency cycle is avoidable without changing runtime behavior.

Full review comments:

  • [P2] Break the new credential type-import cycle — src/infra/device-identity-material.ts:4
    Importing ClientCredentialResult here closes device-identity-material.ts → client-credential-store.ts → client-credential-operations.ts → device-identity-material.ts. The repository’s Madge guard includes type-only imports, so erasure at runtime does not avoid the failure; the current-head architecture check reports that guard failing. Keep this material module as a leaf by placing the result adapter above it or using an independent shared contract, then update its callers.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.93

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • pnpm check:import-cycles
  • pnpm check:madge-import-cycles
  • pnpm test src/infra/device-identity-async.test.ts src/infra/device-identity-worker.test.ts src/infra/client-credential-async.test.ts

What I checked:

PR surface

PR surface statistics unavailable: the file list is incomplete.

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Root-cause cluster

Relationship: partial_overlap
Canonical: #192547
Summary: This PR addresses the canonical issue’s 1 GiB acceptance stage while leaving smaller-host and physical-device qualification open.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: The improvement addresses a documented failure on a specific constrained-host profile, with no evidence of a widespread urgent regression.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

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

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-13T09:35:33.316Z sha e3725b3 :: needs changes before merge. :: [P2] Bound discovery bursts before sharing foreground admission

Reviewed November 13, 2026, 6:07 PM ET / 23:07 UTC (Revision 2).

@clawsweeper clawsweeper Bot removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 13, 2026
@vincentkoc vincentkoc changed the title fix(sessions): reduce resident readers on constrained gateways fix(gateway): reduce resident memory on constrained hosts Nov 13, 2026
@openclaw-barnacle openclaw-barnacle Bot added docker Docker and sandbox tooling commands Command implementations labels Nov 13, 2026
@vincentkoc
vincentkoc force-pushed the fix/cardputer-resident-memory-20261113 branch 2 times, most recently from 0747a02 to 0ac22f8 Compare November 13, 2026 22:33
@vincentkoc
vincentkoc marked this pull request as ready for review November 13, 2026 22:57
@vincentkoc

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 15, 2026
…98194)

* fix(sessions): reduce resident readers for constrained gateways

* test(sessions): exercise shared reader cleanup with queued writers

* fix(workers): retain recently active workers under memory pressure

* fix(workers): reclaim idle workers immediately under critical pressure

* fix(sessions): skip usage scans for empty stores

* fix(models): defer automatic catalog refresh under memory pressure

* fix(worktrees): skip empty session owner census

* fix(sessions): defer RPC-only history imports

* fix(sessions): load history discovery only when needed

* fix(logging): load tail redaction only for readers

* fix(agents): keep collector runtime out of tool preparation

* fix(sessions): retire idle preparation workers under pressure

* refactor(agents): isolate memory flush from coding tools

* perf(agents): avoid session barrel during chat preparation

* perf(runtime): keep session readers independent of delivery imports

* perf(cron): isolate read worker runtime chunks

* perf(cron): defer state engine in read workers

* perf(cron): defer background maintenance under memory pressure

* perf(gateway): stop cache warming under memory pressure

* perf(gateway): defer update discovery under memory pressure

* perf(gateway): defer idle repairs under memory pressure

* perf(ai): load Responses WebSocket SDK on demand

* perf(gateway): defer unused schema and scope runtimes

* fix(state): retire idle SQLite readers under memory pressure

* fix(gateway): preserve memory on small hosts

* perf(gateway): defer local credential runtimes

* perf(cli): load only the current platform service reader

* perf(config): isolate physical database inspection

* perf(process): defer unused spawn broker host

* perf(gateway): defer publication recovery under memory pressure

* fix(credentials): keep result types independent of runtime

* fix(ci): align memory refactors with source guards

* test(gateway): trace guest dictation timeout phases

* fix(state): explain incomplete checkpoint close receipts

* test(gateway): make concurrent admission retry deterministic

* chore(state): identify incomplete checkpoint owners

* perf(gateway): skip unobserved terminal session reads

* test(gateway): publish real transcript in metadata socket proof

* test(gateway): persist blocked placeholders in socket proof

* fix(runtime): ignore unbounded process memory limits

* test(gateway): report auth timeout phases

* test(gateway): prepare guest profile before transport checks

* test(gateway): isolate lifecycle fixture dependencies

* refactor(agents): remove unused runtime exports

* test(agents): release prompt continuity preparations

* test(commands): await profile merge in restore fixture

* fix(state): defer idle writer retirement during shutdown

* refactor(agents): inline single-use compaction values

* fix(state): await active executor retirement during shutdown

* test: prepare route workers and expose fault errors

* test(gateway): retain RPC failure context

* test(gateway): await restarted cron readiness

* fix(test): honor Gateway worker budget

* test(gateway): settle background title before fixture cleanup

* test(gateway): await persisted cron repair settlement

* test(gateway): use fixture test deadline for child startup

* test(gateway): report agent deletion upgrade timeout phase

* test(gateway): correlate compressed replies past presence events

* test(gateway): let transport outlive agent wait deadline
fuller-stack-dev added a commit that referenced this pull request Nov 16, 2026
…PRs (#199882)

The interleaved-reply case starts two inbound runs at once and read
dispatch.mock.calls[0] as the first run. Each run awaits a session-entry
read in a worker before it dispatches. Since #198194 those reads share a
two-worker lane, so either run can reach dispatch first and the case
failed in 12 of 30 local runs.

Find each turn by the message it carries and assert that dispatch ran
twice. The session-key, sender, and per-task reply assertions are
unchanged, and replies are still delivered in reverse order.

Also drop the queuedFinal argument from the two dispatch-result helpers.
Every caller passed false, so the values they return are the same.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 16, 2026
…PRs (openclaw#199882)

The interleaved-reply case starts two inbound runs at once and read
dispatch.mock.calls[0] as the first run. Each run awaits a session-entry
read in a worker before it dispatches. Since openclaw#198194 those reads share a
two-worker lane, so either run can reach dispatch first and the case
failed in 12 of 30 local runs.

Find each turn by the message it carries and assert that dispatch ran
twice. The session-key, sender, and per-task reply assertions are
unchanged, and replies are still delivered in reverse order.

Also drop the queuedFinal argument from the two dispatch-result helpers.
Every caller passed false, so the values they return are the same.
RomneyDa added a commit that referenced this pull request Nov 18, 2026
Backport bounded memory-lifecycle repairs onto the retained release owners:
probe constrained headroom from startup, distinguish moderate and critical
pressure, retire idle read-only workers, and close readers before retained
agent executors during shutdown. Keep current dedicated database lanes.

Adapted-from: c3b3d56 (#191272)
Adapted-from: 67ecf6b (#198194)
Co-authored-by: RomneyDa <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 18, 2026
Keep existing cron, update/catalog, post-ready maintenance and page-cache owners. Parent reviewed cancellation, explicit-check availability and reader cleanup. Reuse 47 passing targeted tests and ten-file typed lint.

Adapted-from: 67ecf6b (#198194)

Co-authored-by: RomneyDa <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 18, 2026
Bounded OpenClaw2026.11.6 adaptation of #198194. Preserve existing worker
custody, native receipt settlement, and independent FIFO lanes.

(cherry picked from commit 67ecf6b)

Co-authored-by: RomneyDa <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 18, 2026
Continue bounded backport of 67ecf6b (#198194): keep optional spawn broker off small hosts, load history and Cron reader dependencies on demand, isolate memory flush from coding tools, and defer API-key Responses WebSocket SDK initialization. Move the intact Cron authority writer to the existing save kernel and migrate all callers.

Parent independent review and 28-file canonical typed lint passed. Reused genuine red/green worker boundary and consumer proof (179 passing checks across the recorded suites); format, whitespace and exact patch checks passed. Remaining legacy entry parsing, physical inspection, tail logging and FIFO consolidation are not claimed complete. Constrained-host RSS/boot qualification and full build remain unproved.

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

Labels

agents Agent runtime and tooling app: web-ui App: web-ui clawsweeper:intake:bug Preliminary submission classification; full source review pending. commands Command implementations docker Docker and sandbox tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. scripts Repository scripts security-sensitive-changed size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant