Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions docs/audits/daemon-stream-retention/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Daemon stream retention reproduction

Run from the worktree root after installing dependencies:

```sh
ORCA_BACKGROUND_LAUNCH=1 node docs/audits/daemon-stream-retention/reproduce.mjs
```

The script bundles the current `DaemonStreamDataBatcher` with esbuild, then uses real loopback TCP sockets. It pauses the reader, feeds at most 8 MiB, honors the producer-pause callback, resumes the reader, and closes every socket in `finally`. It starts no PTY, agent, or application window. Output includes the bundle hash, queued payload sizes, RSS, and drain outcome.

Visible 64 KiB and 1 KiB producers should pause within the backlog budget and resume after both queues drain. A hidden 1 KiB producer should keep running while the existing keep-tail policy bounds its held output. RSS includes allocator/GC timing; queue measurements are the direct evidence.

`after.json` records the fixed run: the visible bulk producer paused after 2,686,976 characters with 131,300 socket bytes and 2,031,616 held characters; the visible small-write producer paused with 3,401,200 socket bytes. The hidden producer processed all 8 MiB with 131,300 socket bytes and 667,648 held characters. Every case resumed and drained both queues to zero.

## Preserved measurements before the fix

`before-1mib-chunks.json` and `before-64kib-chunks.json` were captured before adding producer backpressure, with a real paused reader and 96 MiB of input. The latter includes the original compiled bundle hash and a hidden-session comparison.

| Input | Socket buffered bytes | Held characters |
| ------ | --------------------: | --------------: |
| 32 MiB | 131,321 | 32,636,928 |
| 64 MiB | 32,809,583 | 33,554,432 |
| 96 MiB | 66,406,511 | 33,554,432 |

The last 32 MiB retained another 33,596,928 queued payload bytes. The held queue plateaued at 32 MiB while the socket queue grew at 1.00127 bytes per produced ASCII byte. Resuming the reader drained both queues in 74 ms. Sampled RSS reached 1.38 GB with 64 KiB chunks; this includes string coalescing/slicing and GC effects.

The original measurement's build command was:

```sh
ORCA_BACKGROUND_LAUNCH=1 node_modules/.bin/esbuild src/main/daemon/daemon-stream-data-batcher.ts --bundle --platform=node --format=esm --outfile=notes/daemon-stream-retention/daemon-stream-data-batcher.mjs
ORCA_BACKGROUND_LAUNCH=1 node notes/daemon-stream-retention/compare.mjs
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
```

This proves a current stalled-consumer retaining path. It does not attribute issue #19831's whole-system memory total to this path; that report lacks per-process measurements.
46 changes: 46 additions & 0 deletions docs/audits/daemon-stream-retention/after.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
"node": "v26.6.0",
Comment thread
nwparker marked this conversation as resolved.
Resolved
"platform": "darwin",
"bundleSha256": "7c63ca547aa62570878664f9e0504a8747f4daec2daf7c3cffcfce65ebede6bd",
"cases": [
{
"chunkSize": 65536,
"hidden": false,
"stalled": {
"producedChars": 2686976,
"producerPaused": true,
"socketBufferedBytes": 131300,
"batcherQueuedChars": 2031616,
"rssBytes": 62291968
},
"receivedBytes": 2690244,
"afterDrain": { "producerPaused": false, "socketBufferedBytes": 0, "batcherQueuedChars": 0 }
},
{
"chunkSize": 1024,
"hidden": false,
"stalled": {
"producedChars": 3674112,
"producerPaused": true,
"socketBufferedBytes": 3401200,
"batcherQueuedChars": 0,
"rssBytes": 92307456
},
"receivedBytes": 3946800,
"afterDrain": { "producerPaused": false, "socketBufferedBytes": 0, "batcherQueuedChars": 0 }
},
{
"chunkSize": 1024,
"hidden": true,
"stalled": {
"producedChars": 8388608,
"producerPaused": false,
"socketBufferedBytes": 131300,
"batcherQueuedChars": 667648,
"rssBytes": 105005056
},
"receivedBytes": 1607892,
"afterDrain": { "producerPaused": false, "socketBufferedBytes": 0, "batcherQueuedChars": 0 }
}
]
}
37 changes: 37 additions & 0 deletions docs/audits/daemon-stream-retention/before-1mib-chunks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"source": "src/main/daemon/daemon-stream-data-batcher.ts",
"node": "v26.6.0",
"platform": "darwin",
"stalledReader": true,
"samples": [
{
"fedMiB": 0,
"socketBufferedBytes": 0,
"batcherQueuedChars": 0,
"retainedAsciiPayloadBytes": 0,
"rssBytes": 51249152
},
{
"fedMiB": 32,
"socketBufferedBytes": 131333,
"batcherQueuedChars": 32636928,
"retainedAsciiPayloadBytes": 32768261,
"rssBytes": 57917440
},
{
"fedMiB": 64,
"socketBufferedBytes": 32811587,
"batcherQueuedChars": 33554432,
"retainedAsciiPayloadBytes": 66366019,
"rssBytes": 239484928
},
{
"fedMiB": 96,
"socketBufferedBytes": 66410563,
"batcherQueuedChars": 33554432,
"retainedAsciiPayloadBytes": 99964995,
"rssBytes": 311885824
}
],
"retainedBytesPerProducedByteAfterValve": 1.0013275146484375
}
86 changes: 86 additions & 0 deletions docs/audits/daemon-stream-retention/before-64kib-chunks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
{
"source": "src/main/daemon/daemon-stream-data-batcher.ts",
"bundleSha256": "7555dbf7f6020022aca2a0d75f5d9eae2e2c3cf1586e0c1e66fbc357f3a3143e",
"node": "v26.6.0",
"platform": "darwin",
"cases": [
{
"droppable": false,
"samples": [
{
"fedMiB": 0,
"socketBufferedBytes": 0,
"batcherQueuedChars": 0,
"rssBytes": 53968896
},
{
"fedMiB": 32,
"socketBufferedBytes": 131321,
"batcherQueuedChars": 32636928,
"rssBytes": 59834368
},
{
"fedMiB": 64,
"socketBufferedBytes": 32809583,
"batcherQueuedChars": 33554432,
"rssBytes": 1241956352
},
{
"fedMiB": 96,
"socketBufferedBytes": 66406511,
"batcherQueuedChars": 33554432,
"rssBytes": 1381416960
}
],
"finalRetainedQueuedPayloadBytes": 99960943,
"queuedBytesPerProducedByteAfter64MiB": 1.0012664794921875,
"afterDrain": {
"fedMiB": 96,
"socketBufferedBytes": 0,
"batcherQueuedChars": 0,
"rssBytes": 327680000
},
"drainMs": 74.25875000000042,
"receivedBytes": 100791448
},
{
"droppable": true,
"samples": [
{
"fedMiB": 0,
"socketBufferedBytes": 0,
"batcherQueuedChars": 0,
"rssBytes": 327974912
},
{
"fedMiB": 32,
"socketBufferedBytes": 137492,
"batcherQueuedChars": 786432,
"rssBytes": 390053888
},
{
"fedMiB": 64,
"socketBufferedBytes": 144389,
"batcherQueuedChars": 720896,
"rssBytes": 454852608
},
{
"fedMiB": 96,
"socketBufferedBytes": 151286,
"batcherQueuedChars": 655360,
"rssBytes": 519733248
}
],
"finalRetainedQueuedPayloadBytes": 806646,
"queuedBytesPerProducedByteAfter64MiB": -0.0017475783824920654,
"afterDrain": {
"fedMiB": 96,
"socketBufferedBytes": 0,
"batcherQueuedChars": 0,
"rssBytes": 520437760
},
"drainMs": 5.139125000000149,
"receivedBytes": 1595433
}
]
}
112 changes: 112 additions & 0 deletions docs/audits/daemon-stream-retention/reproduce.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { once } from 'node:events'
import { createServer, Socket } from 'node:net'
import { setImmediate as nextTurn, setTimeout as delay } from 'node:timers/promises'
import { createHash } from 'node:crypto'
import { fileURLToPath } from 'node:url'
import { resolve } from 'node:path'
import { build } from 'esbuild'

if (process.env.ORCA_BACKGROUND_LAUNCH !== '1') {
throw new Error('Run with ORCA_BACKGROUND_LAUNCH=1')
}
const root = fileURLToPath(new URL('../../../', import.meta.url))
const built = await build({
entryPoints: [resolve(root, 'src/main/daemon/daemon-stream-data-batcher.ts')],
bundle: true,
platform: 'node',
format: 'esm',
write: false
})
const bundle = built.outputFiles[0].text
const { DaemonStreamDataBatcher } = await import(
`data:text/javascript;base64,${Buffer.from(bundle).toString('base64')}`
)
const MiB = 1024 * 1024

async function run(chunkSize, hidden) {
const server = createServer()
const writer = new Socket()
let reader
let paused = false
let produced = 0
let receivedBytes = 0
const batcher = new DaemonStreamDataBatcher(() => ({ streamSocket: writer }), {
onProducerBackpressureChanged: (_sessionId, value) => {
paused = value
},
isSessionDroppable: () => hidden
})
writer.on('drain', () => batcher.flush('client'))
try {
const accepted = once(server, 'connection')
server.listen(0, '127.0.0.1')
await once(server, 'listening')
const address = server.address()
if (!address || typeof address === 'string') {
throw new Error('Expected TCP address')
}
writer.connect(address.port, '127.0.0.1')
await once(writer, 'connect')
;[reader] = await accepted
reader.on('data', (data) => {
receivedBytes += data.length
})
reader.pause()
const chunk = 'x'.repeat(chunkSize)
while (!paused && produced < 8 * MiB) {
batcher.enqueue('client', 'session', chunk, { flushImmediately: true, flushMaxChars: 1024 })
batcher.flush('client')
produced += chunkSize
if (produced % MiB === 0) {
await nextTurn()
}
}
const stalled = {
producedChars: produced,
producerPaused: paused,
socketBufferedBytes: writer.writableLength,
batcherQueuedChars: batcher.queuedCharsForClient('client'),
rssBytes: process.memoryUsage().rss
}
reader.resume()
const start = performance.now()
while (paused || writer.writableLength || batcher.queuedCharsForClient('client')) {
if (performance.now() - start > 5000) {
throw new Error('Failed to drain')
}
await delay(5)
}
const ended = once(reader, 'end')
writer.end()
await ended
return {
chunkSize,
hidden,
stalled,
receivedBytes,
afterDrain: {
producerPaused: paused,
socketBufferedBytes: writer.writableLength,
batcherQueuedChars: batcher.queuedCharsForClient('client')
}
}
} finally {
batcher.clear()
writer.destroy()
reader?.destroy()
await new Promise((done) => server.close(done))
}
}

console.log(
JSON.stringify(
{
node: process.version,
platform: process.platform,
bundleSha256: createHash('sha256').update(bundle).digest('hex'),
cases: [await run(64 * 1024, false), await run(1024, false), await run(1024, true)]
Comment thread
nwparker marked this conversation as resolved.
Resolved
},
null,
2
)
)
2 changes: 2 additions & 0 deletions src/main/daemon/daemon-client-connections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,8 @@ export class DaemonClientConnections {
socket.on('error', cleanup)
if (previous && previous !== socket) {
previous.destroy()
this.options.streamDataBatcher.replaceStream(client.clientId)
this.options.streamDataBatcher.flush(client.clientId)
}
}
}
Comment thread
nwparker marked this conversation as resolved.
Resolved
9 changes: 9 additions & 0 deletions src/main/daemon/daemon-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@ export class DaemonServer {
this.streamDataBatcher = new DaemonStreamDataBatcher(
(clientId) => this.connections.get(clientId),
{
onProducerBackpressureChanged: (sessionId, paused) =>
paused
? this.host.pauseProducer(sessionId, 'stream')
: this.host.resumeProducer(sessionId, 'stream'),
isSessionAttachedToClient: (clientId, sessionId) => {
const owner = this.attachments.clientIdForSession(sessionId)
return owner === undefined || owner === clientId
},
isSessionDroppable: (sessionId) =>
BACKGROUND_STREAM_DROP_ENABLED && this.transientFactRelay.isBackgrounded(sessionId),
salvageDroppedData: (dropped) => {
Expand Down Expand Up @@ -128,6 +136,7 @@ export class DaemonServer {
onControlReplaced: (clientId) => {
this.preparations.cancelForClient(clientId)
this.historySeedTransfers.clearOwner(clientId)
this.streamDataBatcher.clear(clientId)
},
onClientDisconnected: (clientId) => {
this.preparations.cancelForClient(clientId)
Expand Down
Loading
Loading