Skip to content

Stream prompt attachments from server to daemon without buffering - #6332

Merged
ymichael merged 1 commit into
mainfrom
bb/stream-attachment-transfers-thr_tjj6vvmme2
Oct 26, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/stream-attachment-transfers-thr_tjj6vvmme2

Conversation

@ymichael

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

The internal attachment route read each attachment fully on the server (readAttachment) and copied it into a new Uint8Array for the response. The daemon then collected every chunk into an array and copied them into a second full buffer before writing the file. With the 35 MiB attachment cap, one attachment held several full copies in memory at once. In a measurement, a 34 MiB attachment peaked at about 65 MiB of live memory, at least.

What changed

  • Server (apps/server/src/internal/session.ts): /internal/session/project-attachment-content now returns the existing streaming createAttachmentContentResponse, which reads in 64 KiB chunks, sends content-length, and refuses files that change mid-read. Authorization (session, thread, project, assigned host) is unchanged.
  • Daemon (apps/host-daemon/src/verified-file-transfer.ts, new):
    • writeVerifiedFile streams a source into a newly created file. It enforces the byte cap and expected size and writes each chunk fully. On any failure it cancels the source and removes the partial file.
    • hashFile and publishFileWithoutReplacing (hard link, no-clobber copy fallback) support publishing.
  • Daemon (command-handlers/prompt-attachments.ts, server-client.ts):
    • fetchProjectAttachment returns the response body stream. content-length is still checked before reading.
    • Staging writes to a hidden .bb-attachment-<uuid>.partial in the thread's Attachments directory, then publishes it under the usual name or a -N suffix. An identical existing file is detected by hash. The temp file is always removed.
  • No wire change, so no HOST_DAEMON_PROTOCOL_VERSION bump. An older daemon reads the streamed response like the old one, and this daemon reads an old server's full response as a stream.
  • This is the attachment half of Transfer skill trees by manifest, fetching only missing files #6330, which is now stacked on this PR and covers only the skill-tree transfer.

How you verified

  • Tests:
    • New: an interrupted attachment stream fails with attachment_unavailable and leaves no partial file, and an attachment whose declared length differs is rejected before its body is read (the body is cancelled).
    • Existing staging tests (renaming, identical-file reuse, cleanup on runtime failure, size mismatch) pass with streamed content.
  • Commands: turbo run typecheck --filter=@bb/host-daemon --filter=@bb/server; vitest for server-client, thread-dispatch, command-router, command-dispatch and internal-project-attachment-content.
  • Memory, measured with the real server on loopback HTTP plus the real daemon client and staging code: a 34 MiB attachment peaked at ≥ 64.7 MiB of live heap before and 1.7 MiB after, sampled with forced GC.
  • Manual repro: under ulimit -f, the old write loop reported 4,096 bytes written with 512 on disk. The full-write loop fails with EFBIG and leaves no file.
  • Live run with a real Codex thread on a pnpm start:worktree instance: a 30 MiB attachment was staged with a matching sha256.

🤖 Generated with Claude Code

AGENT GENERATED

The server read each attachment fully and copied it into the response; the
daemon collected every chunk and then copied them into a second buffer
before writing. A 34 MiB attachment peaked at about 65 MiB of live memory
across both sides.

The internal attachment route now uses the existing streaming file
response. The daemon streams the body into a hidden temp file in the
thread's Attachments directory, enforcing the size cap and expected size
and writing each chunk fully. The finished file is published with a
no-clobber hard link (copy fallback), and the temp file is always removed.
Authorization, limits, cleanup and reference rewriting are unchanged. The
wire format is unchanged, so no protocol bump is needed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 28f4694 into main Oct 26, 2026
56 of 57 checks passed
@ymichael
ymichael deleted the bb/stream-attachment-transfers-thr_tjj6vvmme2 branch October 26, 2026 19:33
ymichael added a commit that referenced this pull request Oct 26, 2026
## Human comments

## What was wrong

Server-owned skills (global, plugin and built-in) went to the host
daemon as one JSON document with every file base64-encoded. The server
re-read the tree, and the daemon parsed, decoded, hashed and rewrote it,
holding the whole tree in memory at each step. The daemon also kept a
per-tree cache of file contents with no byte budget. Any edit, even one
line of SKILL.md, re-sent the entire tree including large assets. The
server computed tree hashes by synchronously reading every file on each
thread start and turn submit.

Follows #6332 (merged), which added attachment streaming and the shared
`verified-file-transfer.ts` helper. This PR covers only the skill-tree
transfer and extends that helper.

## What changed

- **Contract (`HOST_DAEMON_PROTOCOL_VERSION` 252 → 253):**
- The tree hash is now v2: sha256 over each file's path, mode, size and
content sha256, defined once in `@bb/host-daemon-contract/skill-tree`
for both server and daemon.
- `GET /internal/skills/tree/:hash` returns a manifest (path, mode,
size, sha256 per file).
- New `POST /internal/skills/tree/:hash/content` streams the requested
files back to back. The base64 tree response is removed.
- **Server:**
- `SkillTreeRegistry.readTree` hashes files asynchronously with streamed
reads. If a file changes while it is being hashed, it retries up to 3
times and takes size and mode from the stat the hash matched.
- It keeps metadata-only manifests by hash. A root's previous hash is
dropped when its content changes.
- The content route refuses (404) any file whose stat changed since it
was hashed.
- There is deliberately no per-file hash cache. It saved about 20 ms per
resolution for 36 MiB of skills, and about 1–2 ms at typical sizes, and
its invalidation was the most error-prone part.
- **Daemon:**
- Pulls validate the manifest (hash, path safety, depth, count, 10 MiB
budget). Files the local store already has with the same sha256 are
copied and re-verified, and only the rest are downloaded, in one
streamed request.
- Each file is verified for size and sha256 and written fully. On
failure nothing is published and partial files are removed.
- Stored trees keep a `manifest.json`. The collected-tree cache holds
metadata only, bounded by tree and file counts.
- Staging copies from disk with verification. The source is opened
lazily, so a missing file can't surface as an unhandled stream error.
Staging retries up to 3 times if a host source changes mid-stage.
- **Unchanged on purpose:** the daemon's 10 MiB per-skill limit (#6267
is where that is decided). No CLI, SDK, plugin API or config changes.

## How you verified

- **Tests:**
- Bad downloads: manifest hash mismatch, unsafe paths, wrong content,
truncated and over-long streams — each leaves nothing in the store.
- Edits and reuse: only changed files are fetched after an edit, and a
corrupted stored copy is re-downloaded.
- Concurrency and rebuild: concurrent stages pull a tree once, and the
stage rebuilds after store eviction.
- Copy safety: a missing source with a failing destination raises no
unhandled error. This test fails without the fix.
- Server routes: manifest, content and path validation, refusal of
changed files, and dropping superseded hashes.
  - Contract: v2 hash ordering and field binding.
- **Manual repro:** a 200 MiB file appended mid-hash. The old code
recorded the pre-append size; the fix records the final size.
- **Commands:** `turbo run typecheck` and `turbo run test` for
`@bb/host-daemon-contract`, `@bb/host-daemon` and `@bb/server`.
- **Benchmark:** real server on loopback HTTP plus the real daemon
client and staging code. "Before" was measured on the base commit.

  | Scenario | Before | After |
  |---|---|---|
  | 9 MiB skill, first pull, wire bytes | 12.0 MiB | 9.0 MiB |
| Same skill after a one-line SKILL.md edit, wire bytes | 12.0 MiB | ~0
|
| Skill pull, peak live heap (GC while sampling) | ≥ 24.8 MiB | 2.3 MiB
|
| Catalog resolve, 4 × 9 MiB skills | 15 ms, blocking the event loop |
23 ms, async |

- **Live run** on a `pnpm start:worktree` instance with a real Codex
thread:
  - A 9 MiB skill asset was staged with a matching sha256.
- After a SKILL.md edit and a follow-up turn, the daemon logged 1 file
downloaded (182 bytes) and 1 reused.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

> AGENT GENERATED

---------

Co-authored-by: review <review@local>
Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Oct 26, 2026
…read (#6335)

## Human comments

## What was wrong

`host.write_file` without `expectedSha256` overwrote its target in
place, so a crash or full disk partway through left a truncated file.
`host.read_file_relative` loaded whole files with no size limit and sent
them as one base64 WebSocket message. Both bugs came from duplicated
paths. There were two whole-file reads: `read_file_relative` was built
for the status-folder server, removed in June, and its only remaining
caller was the provider-skill read. There were also three hand-written
copies of the temp-file, hash-check, rename save, so a fix in one never
reached the others.

## What changed

- **One atomic save:** new dependency-free package `@bb/file-transfer`.
`verified-file-transfer.ts` (from #6332/#6330) moved into it unchanged,
apart from the `durable` and `mode` arguments below. A new `replaceFile`
does the whole save:
  1. check the expected hash;
2. write and fsync a fixed-length `.bb-write-<uuid>` temp file next to
the target;
  3. put it in place:
     - **no hash:** rename over the target;
     - **`expectedSha256: null`:** no-clobber link;
     - **a hash:** re-check, then rename.
- **Who uses it:** `writeHostFile` keeps only root confinement, parent
creation and error mapping. The server-owned skill save in
`skill-listing.ts` calls `replaceFile` directly instead of its own copy.
- **Modes:** an existing file keeps its mode exactly. A requested mode
on a new file goes through `open()`, so the umask applies, as on main.
- **Read-only folders:** an unconditional write falls back to
overwriting in place, as on main. A hash-checked save fails with
`EACCES`, as on main.
- **fsync:** `writeVerifiedFile` takes `durable` (user saves fsync;
attachments and skill trees don't) and an explicit create-or-exact
`mode`.
- **One whole-file read:** removed `host.read_file_relative`. The skill
read now uses `host.read_file`, which has the 25 MB (10 MB image) cap.
- **Symlinked skill folders:** `host.read_file` gains a required
`followRootSymlink` boolean, matching `host.list_files`, so linked skill
folders still resolve (#5556). Skill reads pass `true`; every other
caller passes `false`. The schema rejects `true` with a git `ref` or
without a `rootPath`.
- **Server-side path checks:** the server rejects absolute, `..` and
dotfile skill paths before calling the host, using the same check
server-owned skills already used.
  - **Errors:** an oversized skill file now returns 413 instead of 502.
- **Wire change:** `HOST_DAEMON_PROTOCOL_VERSION` goes from 255 to 256,
for the removed command and the new required field. `host.write_file`'s
fields and results are unchanged.
- **Docs:** updated the symlinked-skill paragraph in
`docs/debugging-and-qa.md`.
- **Behaviour note:** saves replace the file, so hard links, xattrs and
ACLs on an overwritten file aren't carried over. Hash-checked saves
already worked this way.

## How you verified

- **New tests:**
  - `@bb/file-transfer`:
    - an interrupted write leaves the original intact;
- read-only folder: an unconditional write lands in place, a
hash-checked save is refused;
    - a requested mode respects the umask;
    - a 240-character filename saves.
  - daemon: an oversized read under a followed root is rejected.
  - server:
    - oversized skill file → 413;
- absolute, `..` and dotfile skill paths are rejected without calling
the host;
- server-owned skill save writes on a fresh revision and returns 409 on
a stale one.
  - Each failed before its fix.
- **Commands:**
- `pnpm exec turbo run typecheck lint --filter='...[origin/main]'`:
133/133 tasks pass.
- `pnpm exec turbo run test` for `@bb/file-transfer` (7),
`@bb/host-daemon-contract` (76), `@bb/host-daemon` (833, 12 skipped) and
`@bb/server` (3655 of 3656). The one server failure is a timeout in
`builtin-plugins.test.ts`, which nothing on this branch touches. A
different test in that file timed out on each full run, both under heavy
machine load, and that file's 28 tests pass when run alone.
- **Manual:** a `pnpm start:worktree` instance with a fixture project,
checked by a script of 24 CLI/API checks, all passing:
  - symlinked skill reads, the 27 MB → 413 case, rejected paths;
- daemon- and server-saved skills: fresh save lands, stale save returns
409, no temp files left behind;
  - `bb file write`: unconditional, stale hash, read-only folder;
  - the umask and long-filename cases.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant