Repository navigation
Session-log persistence re-reads and re-decodes the whole zstd log on every access → heap OOM on long-lived sessions #14320
Replies: 3 comments
Follow-up: prototype, benchmarks, and what we see while running itTwo things: (1) the tail-reading prototype is small enough to review inline, (2) we have it running on the second host now, and the measurement after that gives a useful data point for the window/index direction. What the prototype doesKeep the live CorrectnessCompared against the current full decode on a real 18.5 MB v4 log (12 828 frames, 23 107 events, 52.9 MB plaintext):
Benchmarks (same fixture, same machine, both paths in one process)
Running it on the 843-session hostWe patched
The patch (against
|
Update: 3 hours in production with the tail-read prototypeQuick follow-up with what we see on the host now (≈820 session directories, several agents working concurrently, two planned restarts to apply config changes — no OOM, no Before → after, same host, same workload:
So the tail-read direction does what the profile predicted: the churn collapses, and the Host UI stops starving. The workspace tree and WebSocket connection are stable again. Two caveats worth recording, because they masquerade as harness instability. Part of what we originally attributed to DSH was actually our deployment:
Still open on our side: is the windowed/byte-indexed read the direction you would accept? We can attach the prototype patch, the benchmark harness and the real fixtures (18.5 MB log, append/truncate/rename/torn-tail cases) for review, and we are happy to re-run anything on the production corpus. Thanks for the quick turnaround on the earlier follow-up. |
|
我们对照当前 |
Uh oh!
There was an error while loading. Please reload this page.
Target
@deepseek-ai/dsh-session-persistence-jsonl0.2.2-rc.1bug,memory,persistenceSummary
On a long-running
dsh webserver with many concurrent sessions, the process dies withFATAL ERROR: Ineffective mark-compacts near heap limit — JavaScript heap out of memory. A 60-second V8 sampling profile attributes 89% of live heap (853.8 MB of 954.4 MB) to a single call path:Every
read(offset, length)on a session materialises the entire stored log:fs.readFileof the whole file (readStableSnapshot), full zstd decompression (readZstdPrefix), andJSON.parseof every event line (consumeEventLine). The requestedoffset/lengthwindow is applied only after the full decode (source.events.slice(offset, offset + length)).The decoded result is memoised, but the memo is bounded by entry count, not bytes (
COLD_LOG_MEMO_MAX_ENTRIES = 2) and invalidated whenever the file revision changes — i.e. after every append. For an actively written session the cache therefore never hits, and the cost of one appended batch is the decompression and re-parsing of the whole history.Result: O(history) work and O(history) transient allocation per event — quadratic behaviour per session, and guaranteed heap exhaustion once histories grow.
Environment
Restart=alwaysdsh web --host 127.0.0.1 --port 3080behind nginx (proxy_buffering off, SSE/WebSocket)Symptoms
Main process exited, code=killed, status=6/ABRTMark-Compact 4086.5 (4103.7) -> 4068.2 (4083.1) MB(default ~4 GB old space, the process was started without--max-old-space-size)/proc/<pid>/ioover ~5 minutes:rchar 9.7 GB,wchar 8.5 GB— the server reads its own logs back faster than it writes themIndependent confirmation on a second host (2026-11-25)
Same component 0.2.2-rc.1, 8 vCPU / 23 GB RAM, 843 session logs (1.2 GB compressed):
POST /api/session/listwith a valid session cookie returned 842 items in 43.7 s and 60.3 s on two consecutive calls — the web client times out and renders an empty/partial workspace tree with a reconnect banner.rustcprocesses from agent builds; process RSS 6.9 GB, heap churn dominated by the path above.session/liststill takes tens of seconds on a full corpus, which keeps the client from ever showing the session list reliably.Evidence (heap sampling)
HeapProfiler.startSampling(interval 64 KiB) over 60 s on the live server:Top stacks are all the same path (
consumeEventLine <- SessionLogScanner.write <- readZstdPrefix <- decodeStoredLog), 684.6 MB and 109.8 MB among them.decodeSeqRanges/dsh-session-format-v1-to-v2shows the v1→v2 migration decoder also participating.Root cause
read(offset, length)(:66) resolves the current log and callsreadCurrent(:103) →readStoredLog(:2834): a whole-filefs.readFile, full zstd frame decompression (readZstdPrefix:2989) andJSON.parseof every line (consumeEventLine:1086). The slice happens after the decode. There is a chunked reader for the header only (readFirstLine), but not for events.coldLogMemokeeps at most 2 decoded logs (:2289) and is dropped when the file revision changes. Two large sessions can occupy hundreds of MB, and an active session never benefits.appendLines(:3307) is a proper append + fsync, but the next read sees a new revision and re-decodes everything, so the cost per appended batch is O(history) — the workload is inherently quadratic in session length.What we did
/proc/iocounters, per-session open descriptors during a read-heavy request, systemd crash history.readStoredLogseam rather than a synthetic model.inheritedEventCountandeventStateare identical across append-only growth, truncation, inode replacement (rename) and torn-tail scenarios; the prototype falls back to a full decode whenever the file is not a pure append.Measured prototype (same fixture, same machine, both paths in one process):
Also observed the same path starving the Host UI (session/list timing above).
How the prototype works
The live
SessionLogScanneris kept per session together with the file offset it has consumed. When the log grew (same inode, larger size), only the appended byte range is read, only its zstd frames are decoded, and the same scanner continues (its decoder state is intact; continuing afterfinish()is safe). Results are frozen copies, the live collector array is never frozen. A size-triggered LRU bounds the retained decoded events, and a full row re-validation runs periodically as a safety net. Any deviation from a pure append (shrink, new inode, torn frame, decode error) falls back to today's full decode.The prototype is not offered as a drop-in patch — it exists to show the size of the win and to validate the windowed-read direction below. We can attach it and the benchmark harness on request.
Proposed fix
Treat the log as an append-only record stream instead of re-parsing it as a document. The central abstraction is a window over the log stream, not a cache of decoded logs:
(startSeq, endSeq)plus the decoded records inside it, charged against a byte budget (per session and globally);Concretely:
frameOffset → (firstSeq, lastSeq, plaintextStartOffset, plaintextLength), in the existing storage domain or the sqlite session index. The index is what makes a frame act as a page.fs.read(fd, { position, length, buffer })) plus independently decodable frames let a window be materialised from a handful of blocks.[offset, offset + length), in blocks, and charge the decoded slice to the window budget: O(window), not O(history).observedLength/lastSeqin memory and in the index instead of re-reading the log to learn them; repair a torn tail against the index.Why not just a bigger LRU
A cache optimises hits for random access and must still grow to the size of the working set. A window makes the working set bounded by construction: the consumer asks for a range, gets it, and the rest is explicitly out of scope — the property this implementation lacks on a server with hundreds of sessions.
Relation to OS virtual memory
The analogy is close but simpler in our favour: real virtual memory needs dirty-page write-back, a page-fault handler and swap; here every page is clean and immutable (append-only log), so the window only needs
load(page)anddrop(page).Acceptance criteria
SessionHandle.read(offset, length)allocates O(length), independent of total log size (measure: heap delta while reading a 200 MB log withlength = 1000must stay in the noise).Ineffective mark-compactsabort.session/listover 800 sessions returns in well under a second (currently tens of seconds on the second host above).Workaround applied locally (not a fix)
--max-old-space-size=8192+MemoryHigh=16G/MemoryMax=20G+RestartSec=30on the unit only stretches the interval between aborts; the churn remains. The only workload-side mitigation that actually helps is shorter sessions (a new log per task) — which confirms the cost is a function of log length.Minimal repro sketch
Attachments available on request
.heapprofile) and the sampling harnessstatus=6/ABRTsequence),/proc/<pid>/iosamples, nginx 5xx timelinedsh-session-persistence-jsonl@0.2.2-rc.1Filed from a production incident on a self-hosted DSH server (744 sessions, 138 active, 7 OOM crashes in under 2 hours; second host: 843 sessions,
session/list43–71 s, repeated OOM/restarts).All reactions