perf(memory): swap-not-clone the chunk body in extract scoring
Summary
- Extract-chunk scoring no longer clones the whole
Chunkto carry the full body into the scorer; it swaps the body in and restores the preview after. - Cuts per-extract-job allocation (no metadata + preview clone) and, more importantly, keeps
PreparedExtractholding only the <=500-char preview instead of the full body. - Behavior-preserving:
score_chunksees the identical full body; scoring, admission, and persistence are unchanged.
Problem
prepare_extract reads the full chunk body off disk (the SQLite content column only holds a <=500-char preview after the MD-on-disk migration). To feed the full body into score_chunk — which only borrows &Chunk — it built a second chunk:
let chunk_with_body = {
let mut c = chunk.clone(); // clones metadata + the preview too
c.content = body;
c
};
let result = score::score_chunk(&chunk_with_body, &scoring_cfg).await?;
Two costs:
- Every extract job clones the whole
Chunk(metadata + preview) just to replace one field. - The returned
PreparedExtractcarriedchunk_with_body, i.e. the full body.handle_extract_batchprepares all jobs into aVec<PreparedExtract>before finalizing any, so a batch of N items retained N full bodies in memory — even thoughfinalize_extractnever readschunk.content(onlychunk.idandchunk.metadata).
Solution
Swap instead of clone:
let body = content_read::read_chunk_body(config, &chunk.id)?;
let preview = std::mem::replace(&mut chunk.content, body);
let result = score::score_chunk(&chunk, &scoring_cfg).await?;
// Restore the preview, dropping the full body now that scoring is done.
chunk.content = preview;
score_chunk sees the full body exactly as before. After scoring, the full body is dropped and chunk.content is the preview again, so PreparedExtract holds only the preview. Per-batch footprint drops from N full bodies to N previews; no API change, no scoring change.
Submission Checklist
- [x] Tests added or updated (happy path + at least one failure / edge case) — added
prepare_extract_scores_full_body_but_returns_preview: seeds a chunk whose on-disk body exceeds the preview cap, runsprepare_extractunder an offline static chat provider, and asserts the returned chunk holds the restored preview and NOT the full body. - [x] Diff coverage ≥ 80% — the changed lines are the swap/restore in
prepare_extract, directly exercised by the new test (cargo test --lib memory_queue::handlers::tests::prepare_extract_scores_full_body_but_returns_previewpasses). - [x] N/A: Coverage matrix — behaviour-preserving perf change, no feature rows added/removed/renamed.
- [x] N/A: feature IDs — no matrix feature affected.
- [x] No new external network dependencies introduced (scoring pinned to an offline static provider in the test; runtime path unchanged).
- [x] N/A: manual smoke checklist — internal memory extract pipeline, no release-cut surface.
- [x] N/A: no linked issue — proactive performance improvement.
Impact
- Runtime: Rust core memory extract pipeline. Removes a full
Chunkclone per extract job and stops retaining N full bodies across a prepared batch. - Memory: per-batch footprint drops from N full bodies to N previews.
- No migration, security, or compatibility implications.
Related
- Closes:
- Follow-up PR(s)/TODOs:
AI Authored PR Metadata
Linear Issue
- Key: N/A
- URL: N/A
Commit & Branch
- Branch: perf/extract-no-chunk-clone
Validation Run
- [x] N/A:
pnpm --filter openhuman-app format:check— no app/ changes - [x] N/A:
pnpm typecheck— no TypeScript changes - [x] Focused tests:
cargo test --lib memory_queue::handlers::tests::prepare_extract_scores_full_body_but_returns_preview(1 passed) - [x] Rust fmt/check:
cargo fmt -p openhuman - [x] N/A: Tauri fmt/check — no shell changes
Validation Blocked
- command: N/A
- error: N/A
- impact: N/A
Behavior Changes
- Intended behavior change: none (perf-only; scoring input + outcome preserved)
- User-visible effect: lower memory use during memory extract batches
Parity Contract
- Legacy behavior preserved:
score_chunkreceives the identical full body; admission, persistence, and follow-up job enqueue are unchanged. - Guard/fallback/dispatch parity checks:
finalize_extractreads onlychunk.id/chunk.metadata, neverchunk.content, so restoring the preview is safe.
Duplicate / Superseded PR Handling
- Duplicate PR(s): N/A
- Canonical PR: N/A
- Resolution: N/A
Summary by CodeRabbit
Release Notes
-
Refactor
- Improved memory efficiency during chunk extraction processing by reducing unnecessary data duplication.
-
Tests
- Added regression test to verify correct chunk body handling during extraction.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 06725344-f422-40e3-ba5d-a10feee6efbf
📥 Commits
Reviewing files that changed from the base of the PR and between 08cbd9813d5e44c59d5d40024121a9e1d5aa5673 and b506bd50ad17eb40ed4f29a209e2551ee1ef3495.
📒 Files selected for processing (2)
src/openhuman/memory_queue/handlers/mod.rssrc/openhuman/memory_queue/handlers/mod_tests.rs
📝 Walkthrough
Walkthrough
The prepare_extract handler was refactored to reduce memory usage during batch extraction preparation. Instead of cloning the entire chunk with its full body, the implementation now swaps the loaded body directly into the owned chunk via std::mem::replace, performs scoring on the temporarily modified chunk, and restores the original preview immediately afterward.
Changes
prepare_extract memory optimization
| Layer / File(s) | Summary |
|---|---|
Memory-efficient chunk body handling src/openhuman/memory_queue/handlers/mod.rs |
Function signature changed to accept mutable chunk; full body is loaded and swapped into chunk.content for scoring, then the original preview is restored in-place instead of cloning the entire chunk. |
Regression test for body/preview handling src/openhuman/memory_queue/handlers/mod_tests.rs |
New test constructs a chunk with a body longer than the preview cap, stages full body to disk, and verifies prepare_extract returns content matching the stored preview, not the full body. |
Estimated code review effort
🎯 2 (Simple) | ⏱️ ~15 minutes
Poem
A rabbit digs deep in the chunk with great care, Swapping bodies in, scoring with flair, Then back goes the preview—no clones in between, Memory saved with each swap—oh, so clean! 🐰✨
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
| Check name | Status | Explanation |
|---|---|---|
| Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. |
| Title check | ✅ Passed | The title 'perf(memory): swap-not-clone the chunk body in extract scoring' directly and accurately describes the main change: replacing cloning with a swap operation to improve memory performance when handling chunk bodies in extract scoring. |
| Docstring Coverage | ✅ Passed | Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. |
| Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
| Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.