Skip to content

feat(core): store blobs with the same bytes once - #67662

Merged
rekram1-node merged 3 commits into
devfrom
blob-hash
Dec 2, 2026
Merged

rekram1-node merged 3 commits into
devfrom
blob-hash

Conversation

@rekram1-node

@rekram1-node rekram1-node commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Blobs with the same bytes now share one file on disk. Each blob keeps its own ID, name and session, but its bytes live at <data>/blobs/<sha256>, so storing the same image twice costs disk once.

The reason is tool-output media, which moves to blobs after pastes. In my local database, Kit's media:<hash> table saves 759 MB this way, 745 MB of it across sessions: a swarm of about 256 subagents each read the same six reference images. Deduplicating only within a session would have caught 7 MB.

How it works:

 write:
   stream to blobs/<id>.part
+  hash the bytes while streaming (SHA-256)
-  rename to blobs/<id>, insert the row
+  in one transaction: insert the row, rename to blobs/<hash>
 remove:
-  delete the row, delete blobs/<id>
+  in one transaction: delete the row, delete blobs/<hash> only if no other row has that hash

SQLite write transactions start with BEGIN IMMEDIATE, so a write and a remove of the same bytes can't interleave, even across processes on one database. Renaming over an existing file with the same bytes changes nothing.

The hash is internal for now: it's a column with a plain index, not part of Blob.Info or the API, so no client changes. No unique rule, since two rows with the same bytes are expected.

The upgrade is two migrations. 20261202041631_blob_hash hashes each existing blob's file, rebuilds blob_v2 with the hash column, and hard-links each file to its hash (a copy where links aren't supported). A row whose file is missing or unreadable is dropped with a warning, since it could never be read anyway. Linking instead of moving means a failed commit leaves every old file where it was, so the rerun finds them. 20261202051500_blob_hash_cleanup then removes the old ID-named files in its own transaction, and is safe to rerun.

Hashing cost: about 0.34 ms per MB locally, 0.8 ms per MB streamed into a Durable Object under local workerd, so about 0.3 s on a 349 MB video and nothing noticeable on a paste.

Follow-up to #67016.

Checks: bun run check, bun run typecheck:tsc and bun run migration --check in packages/core; core blob store, video, migration, snapshot and execution tests (96 pass); server video tests. The new tests cover two blobs with the same bytes sharing a file until the last is removed, and the full upgrade from old loose files through both migrations, including a missing file, two files with the same bytes, and a commit that fails after linking.


Added by the opencode bot (AI-generated).

Related: #58436

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks sound to me. Blobs with the same bytes share one file, and an upgrade from a base-written database works. I wrote two identical blobs and one different blob with the base checkout, then opened the database with this branch. All three read back correctly from two <sha256> files, and the shared file was deleted only when the last blob using it was removed. The blob-store, video and migration tests pass, as do typecheck:tsc and migration --check.

Public API: unchanged. hash is an internal column and is not part of Blob.Info or the HTTP API.

One point is worth fixing before this ships: the migration renames files inside its transaction, so a crash or a failed rename during the upgrade can lose blobs on the next start (inline).

Related: #58436

yield* tx.run(
`CREATE INDEX \`blob_v2_session_idx\` ON \`blob_v2\` (\`session_id\`,\`time_created\`) WHERE "blob_v2"."session_id" is not null;`,
)
// Files move last, so only a failed commit can leave one renamed. Rows with the same bytes end on one file.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This step isn't safe to retry. The renames happen before the commit. If the process dies partway through this loop, or one rename fails, the transaction rolls back but the files already moved stay at <hash>. On the next start the migration runs again: hashFile(<id>) hits ENOENT, the row is dropped as "missing", and the <hash> file is left orphaned. That loses data that was fine before the upgrade, and it can happen on a large blob directory.

One fix is to create the <hash> file with a hard link (link(<id>, <hash>), ignoring EEXIST) instead of rename, and remove the old <id> files only after the commit (or leave them for a later cleanup). Then a rerun still finds every <id> file. Another option: when <id> is missing on a rerun, don't drop the row, but there's no hash to recover at that point, so the link approach seems simpler.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: the migration hard-links each file to its hash instead of renaming it, so a failed commit leaves every old file in place and the rerun finds them. A second migration removes the old ID-named files after the first one commits, and it's safe to rerun too. The test now runs a commit that fails after linking, then the rerun and the cleanup.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this fixes the case I raised. In 77eaa3c92, a failed commit after linking leaves every <id> file in place. On the rerun each file hashes again and link returns EEXIST, which is skipped. 20261202051500_blob_hash_cleanup deletes only <id> names for rows that are already committed and ignores ENOENT, so running it again is safe. I ran test/blob-store.test.ts against pr/head in a separate worktree (since removed), and all 4 tests passed, including the failed commit, rerun and cleanup sequence.

One gap is left, and it's in the copy fallback in linkOnce. That fallback only runs on file systems without hard links, so it's rare, but it can lose data:

  • If the process dies partway through copyFile, it leaves a partial <hash> file. On the rerun, link hits EEXIST on that partial file and keeps it. The cleanup then deletes the good <id> file, so the blob ends up truncated.
  • The EEXIST check on copyFile never fires: without COPYFILE_EXCL, copyFile overwrites the target instead of failing.

To fix it, copy to a temporary file and rename it into place, so <hash> only ever appears complete:

async function linkOnce(from: string, to: string) {
  await link(from, to).catch(async (error: NodeJS.ErrnoException) => {
    if (error.code === "EEXIST") return
    const part = `${to}.${path.basename(from)}.part`
    await copyFile(from, part)
    await rename(part, to)
  })
}

(This needs rename imported from node:fs/promises again.) If you'd rather skip it because hard links are nearly always available here, the rest is fine as it is.

I didn't change anything in repo/. The bun.lock change there isn't mine, and I left it in place.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: the copy fallback now copies to a temporary file and renames it into place, so the hash file only ever appears whole.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this fixes it. In 2e2c405f1, linkOnce copies to <hash>.<id>.part and then renames it to <hash>, so a crash during the copy can't leave a partial <hash> file. If a rerun's link hits EEXIST, the file it skips is always complete, so the cleanup can safely delete the <id> files.

One small thing: a crash during the copy can leave a .part file behind. It only wastes disk, and the next rerun overwrites it because the name is fixed for each id, so it's fine as is.

I ran test/blob-store.test.ts against pr/head in a separate worktree, which I've since removed, and all 4 tests pass. None of them exercise the copy fallback, so I checked that by reading the code. I didn't change anything in repo/; the bun.lock change there isn't mine and I left it in place.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The retry problem is fixed. The upgrade now links each old file to its hash name and leaves the original in place, and the new cleanup migration removes the ID-named files only after the hashing migration has committed, so a failed commit leaves every old file for the rerun. I wrote three blobs with the base checkout (two with the same bytes) and opened the database with this head. All three read back correctly from the two hash-named files, and the old files were gone. The blob-store tests, typecheck:tsc and migration --check pass.

Public API: unchanged.

No further concerns.

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