Skip to content

perf: reduce large-session compaction and indexing allocations - #174433

Merged
steipete merged 1 commit into
mainfrom
dbasync/mainheap
Oct 16, 2026
Merged

steipete merged 1 commit into
mainfrom
dbasync/mainheap

Conversation

@steipete

@steipete steipete commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Large text sessions allocate unnecessary copies on the Gateway main thread during compaction and memory indexing.

User Impact

Reduces transient compaction allocations and text transferred from the memory preparation worker. Transcript contents, duplicate-retry handling, embedding inputs, and stored results are preserved. No configuration, schema, or public SDK change.

Why This Change Was Made

Text-only memory preparation returned both chunk.text and chunk.embeddingInput.text; structured cloning copies both strings. Drop the redundant input after provider-size splitting, using the existing plain-text consumer contract. Multimodal preparation is separate and unchanged.

Compaction normalized and serialized each user message even when the next assistant immediately discarded that retry signature. Skip that work only when the retry map is empty and the next entry is an assistant or the transcript ends. Existing duplicate, sender, media, and timestamp rules remain unchanged. Singleton users separated from a reply by system/tool-result entries still normalize; the narrower fast path avoids new pending state.

Evidence

A 60,000-message synthetic session was seeded offline in a separate process before Gateway startup (142,957,994 serialized bytes). The Gateway then ran real compaction and memory indexing. This establishes a product allocation path, not seeding memory retained by the Gateway.

Allocation sampling through compaction attributes approximately 908 MiB of cumulative allocations to duplicate-user normalization/signatures. These are allocated bytes, not retained heap. The diagnostic run completed compaction and sent all 120,000 embedding inputs in 24,000 requests, but exceeded the initial shutdown deadline; it is attribution evidence, not a passing lifecycle or latency result. A main-isolate heap snapshot was captured during indexing drain. The snapshot contains 120,000 prepared chunks and 120,000 redundant plain-text embedding inputs: each text-field family references about 157 MiB of strings. The exported source remains reachable through embedding candidates (about 119 MiB). These are snapshot reference totals, not additive dominator sizes.

Four counter-only controls passed compaction, both shutdowns, restart, and continuation, each producing 120,000 embedding inputs/chunks in 24,000 embedding requests and 162,740,680 indexed text characters. Their compaction summary hash and token counts match. One baseline control made one fewer model response request; total provider request counts are not identical. Initial MAIN peaks were 1,473.34 → 1,943.67 MiB in the first pair and 2,313.01 → 1,610.58 MiB in the extra ambiguity pair. Restart MAIN peaks were 487.61 → 383.70 MiB and 376.70 → 436.67 MiB. The direction reverses: no whole-process peak reduction or retained-memory reduction is claimed. All four runs reported the indexing-drain shutdown warning. Two-second samples can miss synchronous peaks, and these are not matched post-collection retention checkpoints. Whole-source preparation and publication still scale with transcript size; this patch removes avoidable copies and signature allocations without changing publication ownership.

Measurement Base Candidate
64 KiB plain-text preparation, serialized bytes 131,350 65,785
Same source with provider-size splitting, serialized bytes 134,153 68,169
Turn-caused warm all-thread statements, median [min–max] 70 [70–76] 70 [70–85]
Turn-caused warm worker requests, median [min–max] 23 [23–25] 23 [23–26]
Turn-caused warm MAIN statements 0 [0–0] 0 [0–0]
Raw warm all-thread statements, median [min–max] 70 [70–104] 70 [70–101]
Raw warm worker requests, median [min–max] 23 [23–26] 23 [23–28]
Raw warm MAIN statements, median [min–max] 0 [0–13] 0 [0–4]
Turn-caused first-turn statements, median [min–max] 217 [215–221] 224 [217–249]
Turn-caused first-turn requests, median [min–max] 61 [60–62] 62 [62–66]
Turn-caused first-turn MAIN statements 0 0
Whole-workload statements, median [min–max] 3,969 [3,963–4,227] 3,980 [3,960–4,010]
Whole-workload requests, median [min–max] 1,009 [1,009–1,009] 1,011 [1,001–1,011]
Whole-workload MAIN statements, median [min–max] 229 [228–229] 228 [228–228]
Compaction helper sampled allocations, 60k alternating messages 1,085,126,016 bytes 6,446,800 bytes
T1 calls in touched owners 0 0

The two changed functions issue zero database statements/requests on both sides. No SQL saving is claimed. All six alternating shared-harness v3 runs passed (M,C,M,C,M,C), with 30 warmed turns per side. Raw and turn-caused warmed medians are unchanged. Whole-workload medians increased by 11 statements and two requests; first-turn causal medians increased by seven statements and one request. These totals do not establish all-phase SQL non-regression. The matched compaction-helper probe preserves all 60,000 message identities/order and reduces sampled allocations by about 99.4%. Measurements compare base 0dc31f5f643 with candidate 9d28e1275b0 using the unchanged shared v3 harness and Node 26.12.0 / SQLite 3.54.0. The compile cache is disabled. The loaded host does not support latency claims.

The raw warmed MAIN outliers are background state_leases.expires_at reads from the unchanged lease owner; none is turn-caused. The huge-session controls use a separate bounded-observer harness copy: its protocol and hashes match across those four controls, while the six standard runs all share the unchanged v3 protocol and hashes. Results from these two protocols are not pooled.

Raw phase counts below are median [min–max] across three runs. Each cell is statements / requests / MAIN statements; phase placement includes background work.

Phase Base Candidate
Boot 397 [386–404] / 89 [86–91] / 104 [104–105] 386 [386–395] / 86 [86–91] / 104 [104–104]
Connect 66 [38–325] / 17 [14–26] / 0 294 [67–349] / 21 [15–28] / 0
First turn 869 [636–901] / 148 [141–160] / 0 [0–9] 713 [683–886] / 155 [150–160] / 13 [9–13]
Second session / spawn 536 [536–540] / 155 [154–156] / 0 535 [530–537] / 155 [153–155] / 0
Cron 349 [344–368] / 84 [83–92] / 0 350 [350–353] / 85 [84–85] / 0
Compaction 95 [61–96] / 30 [22–30] / 0 95 [95–96] / 30 [30–30] / 0
Shutdown 34 [34–35] / 6 / 9 35 [35–35] / 6 / 9
Restart boot 445 [437–626] / 112 [107–127] / 93 [93–94] 429 [429–430] / 106 [105–106] / 93
Restart connect 69 [68–212] / 31 [30–36] / 0 77 [70–87] / 32 [30–37] / 0
Restart first turn 296 [244–317] / 83 [73–92] / 0 315 [304–320] / 88 [84–90] / 0
Restart shutdown 28 [28–42] / 6 [6–8] / 9 28 / 6 / 9

All six runs report successful compaction. Compaction medians are unchanged; the first baseline window contains 61 statements/22 requests, while the other five contain 95–96 statements/30 requests. In that first baseline, memory-indexing writes land in the following settle window: combined compaction + settle is 113 statements/30 requests versus 97/30 in the first candidate. Eight requests visibly shift between windows, but the entire 34-statement compaction difference is not a pure shift. Across all three runs, combined medians are 97/30 → 96/30. No decrease or increase in SQL is attributed to the allocation-only changes.

Compaction owner: 10 tests pass. Memory preparation serialization and native worker/publication coverage: 12 tests pass. Changed-file format/lint and diff checks pass; isolated Codex review is scoped-clean (one round). Exact-head CI passed, including types, lint, source contracts, Madge, PostgreSQL conformance and T1/dialect ratchets; the explicit Knip scan reports only the same three production and four full-tree findings independently reproduced on the exact main baseline, with identical source/config/runner/lockfile bytes; scripts report zero. The inherited findings are recorded with the main repair owner. Update-driver proof is not applicable.

No authority, freshness, or admission checks are removed. The omitted compaction signature is internal bookkeeping with no consumer before reset/end; duplicate user retries before a reply are still compared. The worker payload change removes a redundant representation, not validation.

Production: +12 net lines. Tests: +20 net lines. Total: +35/−3 across three files.

@clawsweeper

clawsweeper Bot commented Oct 16, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-16T16:39:54.198355Z 9d28e12 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added extensions: memory-core Extension: memory-core agents Agent runtime and tooling size: XS labels Oct 16, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug 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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR avoids unused compaction signatures and removes duplicated plain-text fields from memory preparation worker results.

Example: Prepare a 64 KiB text source for memory indexing.

  • Before: Reported serialized preparation output is 131,350 bytes.
  • After: Reported serialized preparation output is 65,785 bytes, preserving the source text.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is narrow and source-consistent with successful exact-head CI; candidate runtime allocation evidence remains limited to serialization measurements.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor-proof gate; supplied Gateway diagnostics establish baseline allocations, while candidate evidence measures serialization and matched runtime controls remain pending.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Large sessions cause avoidable transient allocation during compaction and memory indexing.
Reason: The maintainer-authored direction has a concrete allocation target and a small implementation that preserves existing product behavior.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it makes useful, narrow allocation reductions that current main does not provide, with no concrete correctness or security finding.

Priority: P2
Reviewed head: 9d28e1275b0cd85fd7490f1e4295fcc37e26fda8

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Matched candidate Gateway compaction/indexing allocation results remain pending; the new serialization regression's fail-on-base result is not explicitly recorded.
Agent review details

How this fits together

Compaction prepares transcript messages for summarization; Memory Core prepares text chunks in a worker, then passes them to embedding and publication owners.

flowchart TD
  A[Session transcript] --> B[Compaction retry pruning]
  B --> C[Summarization]
  A --> D[Memory preparation worker]
  D --> E[Embedding consumers]
  E --> F[Index publication]
Loading

Technical review

Best possible solution:

Retain these optimizations in the existing compaction and preparation owners while preserving transcript, embedding, and publication contracts.

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

Current-main source demonstrably constructs discarded retry signatures and returns duplicate plain-text representations; the PR also reports Gateway allocation attribution, but no target code was executed during this review.

Is this the best way to solve the issue?

The changes address the allocation producers directly, reuse existing consumer fallbacks, and preserve retry boundaries without introducing another owner or pending state.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Compaction duplicate-user bookkeeping keeps the original intent (3533521: The supplied provenance identifies duplicate-turn pruning; readable later history establishes sender-aware keys and assistant-boundary resets, which the fast path preserves.)
  • Heading embedding representation keeps the original intent (cf53496: Heading attachment kept text, hash, and embedding input synchronized; consumers already support obtaining equivalent plain-text input from chunk.text.)
  • Worker preparation output keeps the original intent (e14b3dd: Preparation moved off the Gateway thread while publication retained ownership; removing redundant output preserves that division.)

Testing

Proof path: unit tests only.

Security

None.

Evidence

What I checked:

  • Verified introduced change: The pinned introduction contains only the compaction fast path, redundant plain-text payload removal, and serialization regression coverage; comparison with fetched main confirms both optimizations remain absent there. (9d28e1275b0c)
  • Compaction equivalence: The fast path requires an empty retry map and either an immediately following assistant or transcript end; neither case has a later consumer of the skipped signature, while other messages retain existing normalization and retry comparison. (src/agents/embedded-agent-runner/compaction-duplicate-user-messages.ts:59, 9d28e1275b0c)
  • Plain-text consumer contract: Embedding batches already fall back to chunk.text when embeddingInput is absent; provider splitting uses chunk.text, and multimodal preparation bypasses the changed preparation owner. (extensions/memory-core/src/memory/manager-embedding-cache-ops.ts:120, 9d28e1275b0c)
  • Original behavior preserved: The heading behavior established by fix(memory): keep standalone headings with following content #168867 remains intact: merged text, hashes, annotations, and provider limits are retained; only its redundant worker representation is removed. (extensions/memory-core/src/memory/manager-index-preparation.ts:94, cf534960545d)
  • Runtime evidence scope: The complete PR body reports real Gateway compaction and indexing allocation attribution, plus baseline/candidate serialization measurements; it explicitly leaves matched runtime controls pending and disclaims lifecycle and latency success. (9d28e1275b0c)
  • Exact-head CI: The reviewed head has successful aggregate CI, dependency-review, and security-sensitive-review statuses; the only cancelled check found was auto-response, not a demonstrated patch failure. (9d28e1275b0c)

Likely related people:

  • Peter Steinberger: Raw commit cf53496 adds extensions/memory-core/src/memory/manager-index-preparation.ts:94 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: cf534960545d; files: extensions/memory-core/src/memory/manager-index-preparation.ts)
  • SunnyShu: Raw commit 89104d7 adds src/agents/embedded-agent-runner/compaction-duplicate-user-messages.ts:56 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 89104d74ba07; files: src/agents/embedded-agent-runner/compaction-duplicate-user-messages.ts)

PR surface

Source +11, Tests +21. Total +32 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 13 2 +11
Tests 1 22 1 +21
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 35 3 +32

Labels

Label changes:

  • add P2: The changes reduce avoidable memory allocation for large sessions without establishing an urgent outage or changing normal user behavior.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: The changes reduce avoidable memory allocation for large sessions without establishing an urgent outage or changing normal user behavior.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Complete the already planned matched Gateway runs to confirm allocation reductions while preserving compaction and indexed results.

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.

Reviewed October 16, 2026, 1:05 PM ET / 17:05 UTC.

@steipete
steipete merged commit 858af47 into main Oct 16, 2026
146 of 147 checks passed
@steipete
steipete deleted the dbasync/mainheap branch October 16, 2026 17:28
vincentkoc added a commit that referenced this pull request Oct 16, 2026
…158510

* commit 'cff3c307ba6d0ce273abcdaf5cade848d9746d30':
  feat(decisions): preserve native catalog capabilities and accounting (#157492)
  fix(ui): avoid reactive read warnings in picker scrolling (#174436)
  refactor(test): remove unused Nextcloud fixture signing (#174470)
  refactor(browser): share managed tab eviction fixtures (#174474)
  fix(update): preserve Windows inspection path identities (#174471)
  perf: reduce large-session compaction and indexing allocations (#174433)
  perf(codex): reduce allocations while reading app-server output (#174468)
  fix(gateway): skip startup publication checks without a target (#174453)
  refactor: deslop agent harnesses, channel plugins and packages (wave-6 bundle A) (#173531)
  perf(state): reduce shared SQLite worker heap retention (#174420)
  refactor: remove routine channel callsite diagnostics (#174402)
vincentkoc added a commit that referenced this pull request Oct 16, 2026
…esafe-decision-native

* commit 'cff3c307ba6d0ce273abcdaf5cade848d9746d30':
  feat(decisions): preserve native catalog capabilities and accounting (#157492)
  fix(ui): avoid reactive read warnings in picker scrolling (#174436)
  refactor(test): remove unused Nextcloud fixture signing (#174470)
  refactor(browser): share managed tab eviction fixtures (#174474)
  fix(update): preserve Windows inspection path identities (#174471)
  perf: reduce large-session compaction and indexing allocations (#174433)
  perf(codex): reduce allocations while reading app-server output (#174468)
  fix(gateway): skip startup publication checks without a target (#174453)
  refactor: deslop agent harnesses, channel plugins and packages (wave-6 bundle A) (#173531)
  perf(state): reduce shared SQLite worker heap retention (#174420)
  refactor: remove routine channel callsite diagnostics (#174402)

# Conflicts:
#	src/agents/decision-inference.integration.test.ts
vincentkoc added a commit that referenced this pull request Oct 16, 2026
…/decision-tool-v2-proof-20261016

* commit 'cff3c307ba6d0ce273abcdaf5cade848d9746d30':
  feat(decisions): preserve native catalog capabilities and accounting (#157492)
  fix(ui): avoid reactive read warnings in picker scrolling (#174436)
  refactor(test): remove unused Nextcloud fixture signing (#174470)
  refactor(browser): share managed tab eviction fixtures (#174474)
  fix(update): preserve Windows inspection path identities (#174471)
  perf: reduce large-session compaction and indexing allocations (#174433)
  perf(codex): reduce allocations while reading app-server output (#174468)
  fix(gateway): skip startup publication checks without a target (#174453)
  refactor: deslop agent harnesses, channel plugins and packages (wave-6 bundle A) (#173531)
  perf(state): reduce shared SQLite worker heap retention (#174420)
  refactor: remove routine channel callsite diagnostics (#174402)

# Conflicts:
#	docs/plugins/sdk-overview/capabilities.md
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…law#174433)

Avoid transferring duplicate plain-text embedding input from the memory preparation worker after provider splitting. Skip compaction retry signatures when the empty retry map will be reset before any comparison.

Preserve transcript contents, duplicate retry handling, embedding inputs, and publication behavior. Add a serialization-budget regression for plain and provider-split text; existing compaction and native worker/publication tests pass.

No SQL, schema, public SDK, or lifecycle change.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling extensions: memory-core Extension: memory-core P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XS status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant