Repository navigation
feat(core): store blobs with the same bytes once - #67662
Conversation
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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,linkhits EEXIST on that partial file and keeps it. The cleanup then deletes the good<id>file, so the blob ends up truncated. - The
EEXISTcheck oncopyFilenever fires: withoutCOPYFILE_EXCL,copyFileoverwrites 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.
There was a problem hiding this comment.
Fixed: the copy fallback now copies to a temporary file and renames it into place, so the hash file only ever appears whole.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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:
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.Infoor 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_hashhashes each existing blob's file, rebuildsblob_v2with thehashcolumn, 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_cleanupthen 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:tscandbun run migration --checkin 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