From 049fcdf89f3b17c342fa77bb1ab320b5d66ca136 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 3 Oct 2026 10:33:46 +0000 Subject: [PATCH 1/3] fix(platform): delete cleanup bytes only when nothing holds them #4110's caller sweep found three more lanes that deleted bytes a task or a document could still list, and the task release took a product's image: - A video link's cleanup (cancel, retry, watchdog) and its 7-day unbound GC deleted the job's ref outright. The ref is its paster's own transcript row's ref, handed to the chip as storageId, so the task door and the document door take it; the GC also dropped a row a document had taken over. Both now drop the row first (never a document's) and reclaim the bytes through deleteUnheldOrgBlobRefs, a files-domain helper over blobRefHeld, so the bytes go only when nothing holds them. A completed transcript row the cleanup keeps by design now keeps its bytes too, until the GC reaps both. - A staged skill or automation bundle is deleted by its own lane on every path, yet ownsUploadedBlob's intent arm accepted an intent of any purpose, so a task, a document or a mail could take the zip first. The arm now proves only a file upload: an intent is consumed by the lane its purpose names, and nothing else can name a staged bundle. - Dropping a task's attachment trashed every unbound row of the ref, a product's image row included, and the release job then deleted the bytes and the row the product still showed (its image answered 404). The task release now leaves product-image rows to the product domain. The new backend:integration lanes checkVideoLinkHeldBlobs, checkStagedBundlesUnnameable and checkTaskReleaseKeepsProductImage fail on main and pass here; unit tests pin the helper, the SQL and the order of row and bytes. The manual register's blob row names every blob lane. Closes #4110 --- .../backend/domains/files/blob-holders.ts | 16 +- .../files/held-blob-cleanups.integration.ts | 604 ++++++++++++++++++ .../platform/backend/domains/files/service.ts | 24 + .../files/service.unheld-reclaim.test.ts | 97 +++ .../domains/files/upload-intents.test.ts | 14 + .../backend/domains/files/upload-intents.ts | 6 + .../backend/domains/tasks/retire.test.ts | 19 + .../platform/backend/domains/tasks/retire.ts | 4 + .../video_links/service.finalizer.test.ts | 90 ++- .../backend/domains/video_links/service.ts | 35 +- .../platform/backend/integration-check.ts | 41 ++ .../tests/manual/reference/automation.md | 2 +- 12 files changed, 934 insertions(+), 18 deletions(-) create mode 100644 services/platform/backend/domains/files/held-blob-cleanups.integration.ts create mode 100644 services/platform/backend/domains/files/service.unheld-reclaim.test.ts diff --git a/services/platform/backend/domains/files/blob-holders.ts b/services/platform/backend/domains/files/blob-holders.ts index 2aaa607670..b3af641b7f 100644 --- a/services/platform/backend/domains/files/blob-holders.ts +++ b/services/platform/backend/domains/files/blob-holders.ts @@ -15,13 +15,15 @@ import { taskHoldsBlobRef } from '../tasks/blob-holders.ts'; * * ONE predicate for every lane that deletes bytes outside the release seam: * `deleteFile` once its own row is gone, the abandoned-upload sweep and the - * rejected-upload reclaim (`upload-intents.ts`), and a product's released - * managed image (`products/service.ts`). Each lane used to carry its own - * copy, and a copy that missed a holder deleted that holder's bytes: the - * reclaim asked about file rows alone and took a task's attachment - * (2026-10-03, #4104); the product image release asked about file rows and - * current documents and took one too (#4110). A new holder joins here, once, - * for all of them. The + * rejected-upload reclaim (`upload-intents.ts`), a product's released + * managed image (`products/service.ts`), and a video link's cleanup and + * unbound GC (`video_links/service.ts`, through `deleteUnheldOrgBlobRefs`). + * Each lane used to carry its own copy, or none, and a lane that missed a + * holder deleted that holder's bytes: the reclaim asked about file rows + * alone and took a task's attachment (2026-10-03, #4104); the product image + * release asked about file rows and current documents, and the video-link + * lanes asked nothing (#4110). A new holder joins here, once, for all of + * them. The * release seam (`knowledge/liveness.ts`) asks a sibling question in the * middle of a purge — live rows only, minus the document or file row being * purged — and keeps its own statement for that reason. diff --git a/services/platform/backend/domains/files/held-blob-cleanups.integration.ts b/services/platform/backend/domains/files/held-blob-cleanups.integration.ts new file mode 100644 index 0000000000..c149a29328 --- /dev/null +++ b/services/platform/backend/domains/files/held-blob-cleanups.integration.ts @@ -0,0 +1,604 @@ +/** + * Real Postgres and the object-store pin: the cleanup lanes #4110's sweep + * left open delete bytes only when nothing holds them (`blobRefHeld`), or + * hold a ref nothing else can name. Each lane used to delete a ref a task or + * a document could still list: + * + * - a video link's cleanup (cancel, retry, watchdog) and its 7-day unbound + * GC deleted the job's ref, which is its paster's own file row's ref — so + * the task door and the document door take it — and the GC dropped a + * file row a document had taken over; + * - the skill and automation bundle lanes delete their staged zip, whose + * upload intent the task, document and mail doors accepted whatever its + * purpose; + * - dropping a task's attachment trashed every unbound row of the ref, + * a product's image row included, and the release then took the bytes + * and the row the product still shows. + * + * Every write a user makes goes through the session doors; every verdict on + * the bytes is a HEAD against the store. + */ +import { randomUUID } from 'node:crypto'; + +import type { Sql } from 'postgres'; +import { z } from 'zod'; + +import { encodeS3Ref } from '../../core/lib/storage/blob_ref.ts'; +import { + itestObjectStore, + type RecordCheck, + recordSkip, +} from '../../integration-lane-helpers.ts'; +import { + buildObjectKey, + resolveObjectStore, + s3DeleteObject, + s3HeadObject, + s3PutObject, +} from '../../lib/object-store.ts'; +import { runReleaseRefsJob } from '../knowledge/release.ts'; +import { ensureDefaultObjectStore } from '../object_storage/bootstrap.ts'; +import { productImageId } from '../products/image-url.ts'; +import { runVideoLinkWatchdog } from '../video_links/service.ts'; + +interface Actor { + cookie: string; + userId: string; +} + +type SignUpMember = (label: string, role: string) => Promise; + +/** A 1×1 PNG: the product image door sniffs the bytes, never the header. */ +const PNG = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=', + 'base64', +); + +const keyOf = (ref: string) => (ref.startsWith('s3:') ? ref.slice(3) : ref); + +/** + * One lane's org-scoped probe: its own admin uploader (so it neither spends + * the shared user's upload budget nor depends on earlier lanes), a project + * for its tasks, the doors it calls, and the bookkeeping its cleanup undoes. + */ +async function openProbe( + sql: Sql, + base: string, + orgId: string, + signUpMember: SignUpMember, + label: string, +) { + const objectStore = itestObjectStore(); + if (!objectStore) return null; + const suffix = randomUUID().slice(0, 8); + const slugRows = await sql<{ slug: string }[]>` + SELECT "slug" FROM "organization" WHERE "id" = ${orgId} LIMIT 1 + `; + const orgSlug = slugRows[0]?.slug ?? ''; + // A filtered run may not have run checkFiles, which seeds the default + // store; keep a configured one intact so earlier lanes' blobs stay put. + try { + await resolveObjectStore(orgSlug); + } catch { + await ensureDefaultObjectStore(sql, { + OBJECT_STORE_ENDPOINT: objectStore.endpoint, + OBJECT_STORE_BUCKET: `itest-held-blob-${suffix}`, + OBJECT_STORE_ACCESS_KEY: objectStore.accessKeyId, + OBJECT_STORE_SECRET_KEY: objectStore.secretAccessKey, + }); + } + const store = await resolveObjectStore(orgSlug); + const owner = await signUpMember(`${label}-${suffix}`, 'admin'); + const projectId = randomUUID(); + const now = Date.now(); + await sql` + INSERT INTO app.projects (id, org_id, name, created_by, created_at_ms, + updated_at_ms) + VALUES (${projectId}, ${orgId}, ${`Held blob probe ${label}`}, + ${owner.userId}, ${now}, ${now}) + `; + const refs: string[] = []; + const productIds: string[] = []; + const documentIds: string[] = []; + + const call = (method: string, route: string, body?: unknown) => + fetch( + `${base}/api/app/${route}${route.includes('?') ? '&' : '?'}orgId=${orgId}`, + { + method, + headers: { + ...(body === undefined ? {} : { 'content-type': 'application/json' }), + cookie: owner.cookie, + origin: base, + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }, + ); + const jsonOf = async (response: Response): Promise => + response.json().catch(() => null); + const present = async (ref: string): Promise => + (await s3HeadObject(store, keyOf(ref))) !== null; + /** Bytes put straight into the org's store, as a server lane writes them. */ + const putBlob = async (text: string): Promise => { + const key = buildObjectKey(store, orgSlug); + await s3PutObject(store, key, new TextEncoder().encode(text), 'text/plain'); + const ref = encodeS3Ref(key); + refs.push(ref); + return ref; + }; + /** The byte lane (`POST files/upload`): an intent of `purpose`, no row. */ + const upload = async (purpose: string, text: string): Promise => { + const response = await fetch( + `${base}/api/app/files/upload?orgId=${orgId}&purpose=${purpose}`, + { + method: 'POST', + headers: { + 'content-type': 'application/octet-stream', + cookie: owner.cookie, + origin: base, + }, + body: text, + }, + ); + const parsed = z + .object({ storageId: z.string() }) + .safeParse(await jsonOf(response)); + if (!parsed.success) { + throw new Error(`upload ${purpose}: ${response.status}`); + } + refs.push(parsed.data.storageId); + return parsed.data.storageId; + }; + /** The task door with `ref` as the new task's attachment. */ + const attach = async (ref: string, name: string) => { + const response = await call('POST', 'tasks', { + projectId, + title: `Held blob probe: ${name}`, + attachments: [ + { + fileId: ref, + fileName: `${name}.txt`, + fileType: 'text/plain', + fileSize: 1, + }, + ], + }); + const parsed = z + .object({ taskId: z.string() }) + .safeParse(await jsonOf(response)); + return { + status: response.status, + taskId: parsed.success ? parsed.data.taskId : null, + }; + }; + /** The document door that takes the caller's upload over as a document. */ + const bindDocument = async (ref: string, name: string) => { + const response = await call('POST', 'documents/from-blob-upload', { + storageRef: ref, + fileName: `${name}.txt`, + contentType: 'text/plain', + }); + const parsed = z + .object({ documentId: z.string() }) + .safeParse(await jsonOf(response)); + if (parsed.success) documentIds.push(parsed.data.documentId); + return response.status; + }; + const listed = async (taskId: string | null, ref: string) => { + if (taskId === null) return false; + const rows = await sql<{ listed: boolean }[]>` + SELECT coalesce(attachments, '[]'::jsonb) + @> jsonb_build_array(jsonb_build_object('fileId', ${ref}::text)) + AS listed + FROM app.tasks WHERE id = ${taskId} + `; + return rows[0]?.listed ?? false; + }; + /** A file row's lifecycle, or `gone`. */ + const rowState = async (fileId: string): Promise => { + const rows = await sql<{ lifecycle: string | null }[]>` + SELECT lifecycle_status AS lifecycle FROM app.file_metadata + WHERE id = ${fileId} + `; + const row = rows[0]; + return row === undefined ? 'gone' : (row.lifecycle ?? 'active'); + }; + const close = async () => { + // Leave no probe bytes or rows behind; the project cascades its tasks. + for (const ref of refs) { + await s3DeleteObject(store, keyOf(ref)).catch((error: unknown) => + console.warn('[itest] held-blob probe cleanup failed:', error), + ); + } + await sql`DELETE FROM app.video_link_jobs WHERE org_id = ${orgId} + AND storage_ref = ANY(${refs})`; + await sql`DELETE FROM app.products WHERE id = ANY(${productIds})`; + await sql`DELETE FROM app.documents WHERE org_id = ${orgId} + AND (id = ANY(${documentIds}) OR file_ref = ANY(${refs}))`; + await sql`DELETE FROM app.file_metadata WHERE org_id = ${orgId} + AND storage_ref = ANY(${refs})`; + await sql`DELETE FROM app.upload_intents WHERE org_id = ${orgId} + AND s3_ref = ANY(${refs})`; + await sql`DELETE FROM app.projects WHERE id = ${projectId}`; + }; + return { + suffix, + owner, + refs, + productIds, + call, + jsonOf, + present, + putBlob, + upload, + attach, + bindDocument, + listed, + rowState, + close, + }; +} + +/** Recorded, never thrown: a thrown lane truncates every later lane. */ +function recordThrow(record: RecordCheck, lane: string, error: unknown) { + record( + `${lane} lane runs to completion`, + false, + `threw ${error instanceof Error ? error.message : String(error)}`, + ); +} + +/** + * A video link's ref is its paster's own transcript row's ref, handed to the + * chip as `storageId`: the task door (file-row arm) and the document door + * both take it. The cleanup (cancel, retry, watchdog) and the unbound GC + * must leave the bytes to whatever still holds them, and the GC must leave + * a row a document took over — while an unheld job still goes, row and all. + */ +export async function checkVideoLinkHeldBlobs( + sql: Sql, + base: string, + ctx: { orgId: string }, + signUpMember: SignUpMember, + record: RecordCheck, +): Promise { + const p = await openProbe(sql, base, ctx.orgId, signUpMember, 'video-held'); + if (p === null) { + recordSkip( + record, + 'video-link held blobs', + 'no ITEST_S3_ENDPOINT — S3 lanes not exercised in this run', + ); + return; + } + const { orgId } = ctx; + const GC_AGE_MS = 8 * 24 * 60 * 60 * 1000; + /** A video-link job over its transcript row, as the finalizers leave it. */ + const videoJob = async (args: { + label: string; + status: string; + fileStatus: string; + aged?: boolean; + }) => { + const text = `video transcript probe ${args.label}`; + const ref = await p.putBlob(text); + const at = Date.now() - (args.aged === true ? GC_AGE_MS : 0); + const files = await sql<{ id: string }[]>` + INSERT INTO app.file_metadata ( + org_id, storage_ref, source, file_name, content_type, size, + uploaded_by, transcript, transcription_status, created_at_ms + ) VALUES ( + ${orgId}, ${ref}, 'video_link', ${`${args.label}.txt`}, + 'text/plain; charset=utf-8', ${text.length}, ${p.owner.userId}, + ${text}, ${args.fileStatus}, ${at} + ) RETURNING id + `; + const fileId = files[0]?.id ?? ''; + const jobs = await sql<{ id: string }[]>` + INSERT INTO app.video_link_jobs ( + org_id, uploaded_by, source_url, source_url_hash, source_platform, + pasted_token, status, status_changed_at_ms, storage_ref, + file_metadata_id, lifecycle_status, created_at_ms + ) VALUES ( + ${orgId}, ${p.owner.userId}, + ${`https://example.test/held-${p.suffix}-${args.label}`}, + ${`held-${p.suffix}-${args.label}`}, 'youtube', + ${`held-${args.label}`}, ${args.status}, ${at}, ${ref}, ${fileId}, + 'active', ${at} + ) RETURNING id + `; + return { jobId: jobs[0]?.id ?? '', fileId, ref }; + }; + const cancel = async (jobId: string) => + (await p.call('POST', `video-links/${jobId}/cancel`)).status; + const jobGone = async (jobId: string) => + ( + await sql<{ n: number }[]>` + SELECT count(*)::int AS n FROM app.video_link_jobs WHERE id = ${jobId} + ` + )[0]?.n === 0; + + try { + // The cleanup: a cancelled chip whose ref a task lists, or whose row a + // document took over, keeps its bytes; an unheld one is reclaimed. + const taskHeld = await videoJob({ + label: 'cancel-task', + status: 'failed', + fileStatus: 'failed', + }); + const taskAttach = await p.attach(taskHeld.ref, 'cancel-task'); + const taskCancel = await cancel(taskHeld.jobId); + const taskKept = await p.present(taskHeld.ref); + const taskListed = await p.listed(taskAttach.taskId, taskHeld.ref); + const taskRow = await p.rowState(taskHeld.fileId); + const docHeld = await videoJob({ + label: 'cancel-document', + status: 'failed', + fileStatus: 'failed', + }); + const docBind = await p.bindDocument(docHeld.ref, 'cancel-document'); + const docCancel = await cancel(docHeld.jobId); + const docKept = await p.present(docHeld.ref); + const docRow = await p.rowState(docHeld.fileId); + const done = await videoJob({ + label: 'cancel-completed', + status: 'completed', + fileStatus: 'completed', + }); + const doneCancel = await cancel(done.jobId); + const doneKept = await p.present(done.ref); + const doneRow = await p.rowState(done.fileId); + const unheld = await videoJob({ + label: 'cancel-unheld', + status: 'failed', + fileStatus: 'failed', + }); + const unheldCancel = await cancel(unheld.jobId); + const unheldGone = !(await p.present(unheld.ref)); + const unheldRow = await p.rowState(unheld.fileId); + record( + 'a cancelled video link keeps the bytes a task or a document holds, and reclaims an unheld one (#4110)', + taskAttach.status === 200 && + taskCancel === 200 && + taskKept && + taskListed && + docBind === 200 && + docCancel === 200 && + docKept && + docRow === 'active' && + doneCancel === 200 && + doneKept && + doneRow === 'active' && + unheldCancel === 200 && + unheldGone && + unheldRow === 'gone', + `task: attach=${taskAttach.status} cancel=${taskCancel} kept=${taskKept} listed=${taskListed} row=${taskRow} (want 200/200/true/true, row gone); document: bind=${docBind} cancel=${docCancel} kept=${docKept} row=${docRow} (want 200/200/true/active); completed transcript: cancel=${doneCancel} kept=${doneKept} row=${doneRow} (want 200/true/active — the row the cleanup keeps holds its bytes); unheld: cancel=${unheldCancel} gone=${unheldGone} row=${unheldRow} (want 200/true/gone)`, + ); + + // The 7-day unbound GC: the same holders keep the bytes, a document's + // row stays the document's, and an unheld job goes with its row and + // bytes. + const gcTask = await videoJob({ + label: 'gc-task', + status: 'completed', + fileStatus: 'completed', + aged: true, + }); + const gcAttach = await p.attach(gcTask.ref, 'gc-task'); + const gcDoc = await videoJob({ + label: 'gc-document', + status: 'completed', + fileStatus: 'completed', + aged: true, + }); + const gcBind = await p.bindDocument(gcDoc.ref, 'gc-document'); + const gcUnheld = await videoJob({ + label: 'gc-unheld', + status: 'skipped', + fileStatus: 'completed', + aged: true, + }); + await runVideoLinkWatchdog(sql); + const gcTaskKept = await p.present(gcTask.ref); + const gcTaskListed = await p.listed(gcAttach.taskId, gcTask.ref); + const gcDocKept = await p.present(gcDoc.ref); + const gcDocRow = await p.rowState(gcDoc.fileId); + const gcUnheldGone = !(await p.present(gcUnheld.ref)); + const gcUnheldRow = await p.rowState(gcUnheld.fileId); + const jobsGone = [ + await jobGone(gcTask.jobId), + await jobGone(gcDoc.jobId), + await jobGone(gcUnheld.jobId), + ]; + record( + 'the unbound video-link GC keeps the bytes a task or a document holds and a document’s row, and reclaims an unheld job (#4110)', + gcAttach.status === 200 && + gcTaskKept && + gcTaskListed && + gcBind === 200 && + gcDocKept && + gcDocRow === 'active' && + gcUnheldGone && + gcUnheldRow === 'gone' && + jobsGone.every(Boolean), + `task: attach=${gcAttach.status} kept=${gcTaskKept} listed=${gcTaskListed} (want 200/true/true); document: bind=${gcBind} kept=${gcDocKept} row=${gcDocRow} (want 200/true/active); unheld: gone=${gcUnheldGone} row=${gcUnheldRow} (want true/gone); jobs reaped=${jobsGone.join('/')} (want true each)`, + ); + } catch (error) { + recordThrow(record, 'video-link held blobs', error); + } finally { + await p.close(); + } +} + +/** + * A staged skill or automation bundle is consumed by its own lane, which + * deletes the zip on every path. Its upload intent must therefore prove + * nothing to the doors that bind the caller's uploads (task, document, + * mail): an intent is consumed by the lane its purpose names. A file upload + * still binds there, and the bundle lanes still reclaim their zip. + */ +export async function checkStagedBundlesUnnameable( + sql: Sql, + base: string, + ctx: { orgId: string }, + signUpMember: SignUpMember, + record: RecordCheck, +): Promise { + const p = await openProbe(sql, base, ctx.orgId, signUpMember, 'bundle-held'); + if (p === null) { + recordSkip( + record, + 'staged bundles', + 'no ITEST_S3_ENDPOINT — S3 lanes not exercised in this run', + ); + return; + } + const lanes = { + skill_bundle: 'skills/upload', + automation_bundle: 'automations/upload', + } as const; + const consume = async (purpose: keyof typeof lanes, storageId: string) => + (await p.call('POST', lanes[purpose], { storageId })).status; + + try { + const verdicts: string[] = []; + let refusedAndReclaimed = true; + for (const purpose of ['skill_bundle', 'automation_bundle'] as const) { + // Not a zip: the lane reads it, refuses it and deletes it — the same + // `finally` a good bundle meets. + const viaTask = await p.upload(purpose, `not a zip: ${purpose} task`); + const attached = await p.attach(viaTask, `${purpose}-task`); + const taskConsumed = await consume(purpose, viaTask); + const taskKept = await p.present(viaTask); + const taskListed = await p.listed(attached.taskId, viaTask); + const viaDocument = await p.upload(purpose, `not a zip: ${purpose} doc`); + const bound = await p.bindDocument(viaDocument, `${purpose}-document`); + const docConsumed = await consume(purpose, viaDocument); + const docKept = await p.present(viaDocument); + const alone = await p.upload(purpose, `not a zip: ${purpose} alone`); + const aloneConsumed = await consume(purpose, alone); + const aloneGone = !(await p.present(alone)); + refusedAndReclaimed &&= + attached.status === 403 && + !taskListed && + bound !== 200 && + !taskKept && + !docKept && + aloneGone; + verdicts.push( + `${purpose}: attach=${attached.status} (want 403) then upload=${taskConsumed} kept=${taskKept} listed=${taskListed}; document bind=${bound} (want refused) then upload=${docConsumed} kept=${docKept}; alone: upload=${aloneConsumed} reclaimed=${aloneGone} (want true)`, + ); + } + // A file upload still binds through the same proof. + const file = await p.upload('file', 'a file upload still binds'); + const fileAttach = await p.attach(file, 'file-upload'); + const fileBind = await p.bindDocument(file, 'file-upload'); + record( + 'a staged bundle’s upload can be attached or bound by nothing but its own lane, which reclaims it (#4110)', + refusedAndReclaimed && fileAttach.status === 200 && fileBind === 200, + `${verdicts.join('; ')}; file upload: attach=${fileAttach.status} bind=${fileBind} (want 200/200)`, + ); + } catch (error) { + recordThrow(record, 'staged bundles', error); + } finally { + await p.close(); + } +} + +/** + * Dropping a task's attachment releases the ref: the task's own unbound + * rows are trashed, and the release job takes the bytes (and reaps the + * trashed rows) once nothing live names them. A product's image row is the + * product's, not the task's: when a task let go of an image's ref, the + * release took the bytes and the row the product still shows. + */ +export async function checkTaskReleaseKeepsProductImage( + sql: Sql, + base: string, + ctx: { orgId: string }, + signUpMember: SignUpMember, + record: RecordCheck, +): Promise { + const p = await openProbe(sql, base, ctx.orgId, signUpMember, 'retire-held'); + if (p === null) { + recordSkip( + record, + 'task release and product images', + 'no ITEST_S3_ENDPOINT — S3 lanes not exercised in this run', + ); + return; + } + const { orgId } = ctx; + /** Drop every attachment of `taskId`, then run its release job now. */ + const dropAndRelease = async (taskId: string | null, ref: string) => { + const dropped = + taskId === null + ? 0 + : (await p.call('POST', `tasks/${taskId}`, { attachments: [] })).status; + await runReleaseRefsJob(sql, { organizationId: orgId, refs: [ref] }); + return dropped; + }; + + try { + const response = await fetch( + `${base}/api/app/products/images?orgId=${orgId}`, + { + method: 'POST', + headers: { + 'content-type': 'image/png', + cookie: p.owner.cookie, + origin: base, + }, + body: PNG, + }, + ); + const uploaded = z + .object({ imageUrl: z.string() }) + .safeParse(await p.jsonOf(response)); + if (!uploaded.success) throw new Error(`image: ${response.status}`); + const fileId = productImageId(uploaded.data.imageUrl, orgId) ?? ''; + const created = z.object({ productId: z.string() }).safeParse( + await p.jsonOf( + await p.call('POST', 'products', { + name: `Retire probe ${p.suffix}`, + imageUrl: uploaded.data.imageUrl, + }), + ), + ); + if (!created.success) throw new Error('product create failed'); + p.productIds.push(created.data.productId); + const read = z + .object({ file: z.object({ storageRef: z.string() }) }) + .safeParse(await p.jsonOf(await p.call('GET', `files/${fileId}`))); + if (!read.success) throw new Error('files door refused the image'); + const imageRef = read.data.file.storageRef; + p.refs.push(imageRef); + const imageTask = await p.attach(imageRef, 'product-image'); + const imageDrop = await dropAndRelease(imageTask.taskId, imageRef); + const imageRow = await p.rowState(fileId); + const imageKept = await p.present(imageRef); + const served = (await p.call('GET', `products/images/${fileId}`)).status; + + // The control: the task's own upload still goes once the task drops it. + const own = await p.upload('file', 'a task’s own attachment'); + const ownTask = await p.attach(own, 'own-attachment'); + const ownDrop = await dropAndRelease(ownTask.taskId, own); + const ownGone = !(await p.present(own)); + record( + 'dropping a task’s attachment leaves a product’s image to the product, and still releases the task’s own upload (#4110)', + imageTask.status === 200 && + imageDrop === 200 && + imageRow === 'active' && + imageKept && + served === 200 && + ownTask.status === 200 && + ownDrop === 200 && + ownGone, + `product image: attach=${imageTask.status} drop=${imageDrop} row=${imageRow} kept=${imageKept} served=${served} (want 200/200/active/true/200); own upload: attach=${ownTask.status} drop=${ownDrop} released=${ownGone} (want 200/200/true)`, + ); + } catch (error) { + recordThrow(record, 'task release and product images', error); + } finally { + await p.close(); + } +} diff --git a/services/platform/backend/domains/files/service.ts b/services/platform/backend/domains/files/service.ts index a1b5ccc610..52b05c1c4e 100644 --- a/services/platform/backend/domains/files/service.ts +++ b/services/platform/backend/domains/files/service.ts @@ -734,6 +734,30 @@ export async function deleteOrgBlobRefs( } } +/** + * Reclaim the bytes of `refs` that nothing holds any more — no file row, no + * document (current or retained version) and no task names them + * ({@link blobRefHeld}) — and keep the rest: the reclaim for a lane whose + * ref another row may have come to name, such as a video link's transcript, + * which its paster can attach to a task or take over as a document. Drop + * the lane's own rows first, as `deleteFile` does, or they keep the bytes. + * Best-effort like {@link deleteOrgBlobRefs}; answers the refs it deleted. + */ +export async function deleteUnheldOrgBlobRefs( + db: Sql | TransactionSql, + organizationId: string, + refs: readonly string[], +): Promise { + if (refs.length === 0) return []; + const unheld = await db<{ ref: string }[]>` + SELECT r.ref FROM unnest(${[...refs]}::text[]) AS r(ref) + WHERE NOT ${blobRefHeld(db, organizationId, db`r.ref`)} + `; + const doomed = unheld.map((row) => row.ref); + await deleteOrgBlobRefs(db, organizationId, doomed); + return doomed; +} + /** * Store RAW BYTES into the org's store and answer the blob ref — the mail- * attachments write lane (the 0.4 `storeOrgBlob` contract): the bytes are diff --git a/services/platform/backend/domains/files/service.unheld-reclaim.test.ts b/services/platform/backend/domains/files/service.unheld-reclaim.test.ts new file mode 100644 index 0000000000..43d17b056d --- /dev/null +++ b/services/platform/backend/domains/files/service.unheld-reclaim.test.ts @@ -0,0 +1,97 @@ +// @vitest-environment node + +import type { Sql } from 'postgres'; +import { afterEach, expect, it, vi } from 'vitest'; + +import { deleteOrgObject } from '../../lib/object-store.ts'; +import { deleteUnheldOrgBlobRefs } from './service.ts'; + +/** + * The reclaim for a lane whose ref another row may have come to name (a + * video link's transcript, which its paster can attach to a task or take + * over as a document): one statement asks the ONE holder rule + * (`blobRefHeld`) for every ref, and only the bytes nothing holds go (#4110). + */ + +const { blobRefHeld } = vi.hoisted(() => ({ blobRefHeld: vi.fn() })); + +// The real rule, watched: the reclaim asks it rather than a copy. +vi.mock('./blob-holders.ts', async (importOriginal) => { + const actual = await importOriginal(); + blobRefHeld.mockImplementation(actual.blobRefHeld); + return { blobRefHeld }; +}); +vi.mock(import('../../lib/object-store.ts'), async (importOriginal) => ({ + ...(await importOriginal()), + deleteOrgObject: vi.fn(() => Promise.resolve()), +})); +vi.mock('../../lib/org-config.ts', () => ({ + resolveOrgSlug: vi.fn(() => Promise.resolve('acme')), +})); + +interface Statement { + text: string; + values: unknown[]; +} + +/** A recording tag that answers the holder query with `unheld`. */ +function fakeSql(unheld: readonly string[]): { + sql: Sql; + statements: Statement[]; +} { + const statements: Statement[] = []; + const tag = (strings: TemplateStringsArray, ...values: unknown[]) => { + const text = strings.join('?').replace(/\s+/g, ' ').trim(); + statements.push({ text, values }); + return Promise.resolve( + text.startsWith('SELECT r.ref FROM unnest') + ? unheld.map((ref) => ({ ref })) + : [], + ); + }; + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- test double for the postgres.js tag + return { sql: tag as unknown as Sql, statements }; +} + +afterEach(() => { + vi.clearAllMocks(); +}); + +it('deletes only the bytes nothing holds, asking the shared rule once for every ref', async () => { + const fake = fakeSql(['s3:blobs/acme/loose']); + + const deleted = await deleteUnheldOrgBlobRefs(fake.sql, 'org_1', [ + 's3:blobs/acme/loose', + 's3:blobs/acme/held', + ]); + + expect(deleted).toEqual(['s3:blobs/acme/loose']); + expect(blobRefHeld).toHaveBeenCalledTimes(1); + expect(blobRefHeld).toHaveBeenCalledWith( + fake.sql, + 'org_1', + expect.anything(), + ); + const question = fake.statements.find((s) => + s.text.startsWith('SELECT r.ref FROM unnest'), + ); + expect(question?.text).toContain('WHERE NOT ?'); + expect(question?.values[0]).toEqual([ + 's3:blobs/acme/loose', + 's3:blobs/acme/held', + ]); + expect(deleteOrgObject).toHaveBeenCalledTimes(1); + expect(deleteOrgObject).toHaveBeenCalledWith('acme', 'blobs/acme/loose'); +}); + +it('keeps every byte something holds, and asks nothing for no refs', async () => { + const held = fakeSql([]); + expect( + await deleteUnheldOrgBlobRefs(held.sql, 'org_1', ['s3:blobs/acme/held']), + ).toEqual([]); + expect(deleteOrgObject).not.toHaveBeenCalled(); + + const none = fakeSql([]); + expect(await deleteUnheldOrgBlobRefs(none.sql, 'org_1', [])).toEqual([]); + expect(none.statements).toEqual([]); +}); diff --git a/services/platform/backend/domains/files/upload-intents.test.ts b/services/platform/backend/domains/files/upload-intents.test.ts index 1f6284a9f4..17ca1469c7 100644 --- a/services/platform/backend/domains/files/upload-intents.test.ts +++ b/services/platform/backend/domains/files/upload-intents.test.ts @@ -167,6 +167,20 @@ describe('ownsUploadedBlob', () => { expect(proof?.text).toContain('uploaded_by = ?'); }); + it('proves nothing through a staged bundle’s intent, which its own lane consumes and deletes (#4110)', async () => { + const fake = fakeLedger({ stamped: [{ id: 'i-1' }] }); + + await ownsUploadedBlob(fake.sql, { + ...scope, + storageRef: 's3:blobs/acme/aaa', + }); + + const stamp = fake.statements.find((s) => + s.text.startsWith('UPDATE app.upload_intents'), + ); + expect(stamp?.text).toContain("AND purpose = 'file'"); + }); + it('refuses a ref that is neither minted for the caller nor theirs by row', async () => { const fake = fakeLedger({ stamped: [], uploaderRow: false }); diff --git a/services/platform/backend/domains/files/upload-intents.ts b/services/platform/backend/domains/files/upload-intents.ts index 967c2e3771..a6440abc16 100644 --- a/services/platform/backend/domains/files/upload-intents.ts +++ b/services/platform/backend/domains/files/upload-intents.ts @@ -178,6 +178,11 @@ export async function claimRejectedUpload( * blob — and neither the abandoned-upload sweep nor the rejected-upload * reclaim may take the bytes of a ref that was vouched for. A stamp inside a * bind transaction rolls back with a refusal. + * + * Only a `file` intent proves anything here. A skill or automation bundle's + * intent is consumed by the lane its purpose names, which deletes the + * staged zip on every path: a task, document or mail that took the zip + * would list bytes about to go (#4110). */ export async function ownsUploadedBlob( sql: Sql | TransactionSql, @@ -189,6 +194,7 @@ export async function ownsUploadedBlob( WHERE s3_ref = ${args.storageRef} AND org_id = ${args.organizationId} AND user_id = ${args.userId} + AND purpose = 'file' AND expires_at_ms > ${now} RETURNING id `; diff --git a/services/platform/backend/domains/tasks/retire.test.ts b/services/platform/backend/domains/tasks/retire.test.ts index b121b5f62b..f7300fc530 100644 --- a/services/platform/backend/domains/tasks/retire.test.ts +++ b/services/platform/backend/domains/tasks/retire.test.ts @@ -152,6 +152,25 @@ describe('retireTasksInTx', () => { }); describe('releaseUnlistedTaskBlobRefs', () => { + it('trashes the tasks’ own unbound rows of a dropped ref, never a product’s image row (#4110)', async () => { + const { tx, statements } = fakeTx(); + + await expect( + releaseUnlistedTaskBlobRefs(tx, 'org_1', ['s3:only-mine']), + ).resolves.toEqual(['s3:only-mine']); + + const trash = statements.find((s) => + s.text.startsWith('UPDATE app.file_metadata SET'), + ); + expect(trash?.text).toContain( + 'document_id IS NULL AND thread_id IS NULL AND conversation_id IS NULL', + ); + expect(trash?.text).toContain( + "AND source IS DISTINCT FROM 'product-image'", + ); + expect(trash?.values).toContainEqual(['s3:only-mine']); + }); + it('queues a large release in bounded jobs, as every lane releasing more than one ref does', async () => { // A project's whole task tree can release thousands of refs at once. const refs = Array.from( diff --git a/services/platform/backend/domains/tasks/retire.ts b/services/platform/backend/domains/tasks/retire.ts index 8ffd494d6a..dd67d1ed4a 100644 --- a/services/platform/backend/domains/tasks/retire.ts +++ b/services/platform/backend/domains/tasks/retire.ts @@ -185,6 +185,9 @@ export async function releaseUnlistedTaskBlobRefs( `; const releasedRefs = orphaned.map((row) => row.ref); if (releasedRefs.length > 0) { + // A product's image row is the product's, not the task's: the product + // domain ends it (`releaseManagedImage`). Trashed here, the release + // took the bytes and the row of an image a product still shows (#4110). await tx` UPDATE app.file_metadata SET lifecycle_status = 'trashed', status_changed_at_ms = ${Date.now()} @@ -192,6 +195,7 @@ export async function releaseUnlistedTaskBlobRefs( AND storage_ref = ANY(${releasedRefs}) AND document_id IS NULL AND thread_id IS NULL AND conversation_id IS NULL + AND source IS DISTINCT FROM 'product-image' AND (lifecycle_status IS NULL OR lifecycle_status = 'active') `; await queueRefRelease(tx, organizationId, releasedRefs); diff --git a/services/platform/backend/domains/video_links/service.finalizer.test.ts b/services/platform/backend/domains/video_links/service.finalizer.test.ts index b1e6a21a83..051d389508 100644 --- a/services/platform/backend/domains/video_links/service.finalizer.test.ts +++ b/services/platform/backend/domains/video_links/service.finalizer.test.ts @@ -17,16 +17,21 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { addJobInTx } from '../../jobs/enqueue.ts'; import { createAuditLog } from '../audit_logs/service.ts'; -import { deleteOrgBlobRefs } from '../files/service.ts'; +import { + deleteOrgBlobRefs, + deleteUnheldOrgBlobRefs, +} from '../files/service.ts'; import { markRagQueued } from '../knowledge/service.ts'; import { cancelVideoLink, finalizeClonedTranscript, insertSyntheticFileMetadata, + runVideoLinkWatchdog, } from './service.ts'; vi.mock('../files/service.ts', () => ({ deleteOrgBlobRefs: vi.fn(() => Promise.resolve()), + deleteUnheldOrgBlobRefs: vi.fn(() => Promise.resolve([])), putOrgBlobBytes: vi.fn(), })); vi.mock('../knowledge/service.ts', () => ({ @@ -85,6 +90,8 @@ function jobRow(overrides: Record): Record { function fakeJobs(script: { jobs: Record[]; updates: { id: string }[][]; + /** The watchdog's aged, unbound, terminal jobs. */ + gc?: { id: string }[]; }): { sql: Sql; statements: Statement[] } { const statements: Statement[] = []; const tag = (strings: TemplateStringsArray, ...values: unknown[]) => { @@ -112,6 +119,10 @@ function fakeJobs(script: { rows = script.updates.shift() ?? []; } else if (text.startsWith('SELECT id FROM app.video_link_jobs WHERE id')) { rows = [{ id: 'job-1' }]; + } else if ( + text.startsWith('SELECT id FROM app.video_link_jobs WHERE status IN') + ) { + rows = script.gc ?? []; } return Promise.resolve(rows); }; @@ -283,6 +294,7 @@ describe('cancelVideoLink', () => { expect(patches[0]?.values).toContain('skipped'); expect(patches[0]?.values).toContain('indexing'); expect(deleteOrgBlobRefs).not.toHaveBeenCalled(); + expect(deleteUnheldOrgBlobRefs).not.toHaveBeenCalled(); expect( fake.statements.some((s) => s.text.startsWith('DELETE FROM app.file_metadata'), @@ -313,3 +325,79 @@ describe('cancelVideoLink', () => { expect(createAuditLog).toHaveBeenCalledTimes(1); }); }); + +/** + * The cleanup and the unbound GC used to delete the job's ref outright: it + * is its paster's own transcript row's ref, so a task could list it and a + * document could have taken the row over. The row goes first (never a + * document's), and the bytes only when nothing holds them (#4110). + */ +describe('a video link’s reclaim', () => { + const cancelArgs = { + organizationId: 'org-1', + userId: 'user-1', + jobId: 'job-1', + }; + const held = { storageRef: 's3:acme/t', fileMetadataId: 'fm-1' }; + + function recordReclaim(statements: Statement[]): void { + vi.mocked(deleteUnheldOrgBlobRefs).mockImplementation(async () => { + statements.push({ text: 'RECLAIM', values: [] }); + return []; + }); + } + + it('drops the transcript row before the bytes on a cancel, and reclaims only bytes nothing holds', async () => { + const fake = fakeJobs({ + jobs: [ + jobRow({ status: 'failed', ...held }), + // The cleanup's own read after the cancel landed. + jobRow({ status: 'skipped', ...held }), + ], + updates: [[{ id: 'job-1' }]], + }); + recordReclaim(fake.statements); + + await cancelVideoLink(fake.sql, cancelArgs); + + const texts = fake.statements.map((s) => s.text); + const rowDelete = texts.findIndex((t) => + t.startsWith('DELETE FROM app.file_metadata'), + ); + expect(texts[rowDelete]).toContain( + "transcription_status IS DISTINCT FROM 'completed'", + ); + expect(texts[rowDelete]).toContain('document_id IS NULL'); + expect(texts.indexOf('RECLAIM')).toBeGreaterThan(rowDelete); + expect(deleteUnheldOrgBlobRefs).toHaveBeenCalledWith(fake.sql, 'org-1', [ + 's3:acme/t', + ]); + expect(deleteOrgBlobRefs).not.toHaveBeenCalled(); + }); + + it('reaps an aged unbound job: its row unless a document took it over, then only bytes nothing holds', async () => { + const fake = fakeJobs({ + jobs: [jobRow({ status: 'completed', ...held })], + updates: [], + gc: [{ id: 'job-1' }], + }); + recordReclaim(fake.statements); + + await runVideoLinkWatchdog(fake.sql); + + const texts = fake.statements.map((s) => s.text); + const rowDelete = texts.findIndex((t) => + t.startsWith('DELETE FROM app.file_metadata'), + ); + expect(texts[rowDelete]).toContain('document_id IS NULL'); + const reclaim = texts.indexOf('RECLAIM'); + expect(reclaim).toBeGreaterThan(rowDelete); + expect( + texts.findIndex((t) => t.startsWith('DELETE FROM app.video_link_jobs')), + ).toBeGreaterThan(reclaim); + expect(deleteUnheldOrgBlobRefs).toHaveBeenCalledWith(fake.sql, 'org-1', [ + 's3:acme/t', + ]); + expect(deleteOrgBlobRefs).not.toHaveBeenCalled(); + }); +}); diff --git a/services/platform/backend/domains/video_links/service.ts b/services/platform/backend/domains/video_links/service.ts index dd1dc21788..8b198f7c5b 100644 --- a/services/platform/backend/domains/video_links/service.ts +++ b/services/platform/backend/domains/video_links/service.ts @@ -20,7 +20,11 @@ import { reportBrowserSessionResult, } from '../browser_sessions/service.ts'; import { chatShimHandlers } from '../chat/shim.ts'; -import { deleteOrgBlobRefs, putOrgBlobBytes } from '../files/service.ts'; +import { + deleteOrgBlobRefs, + deleteUnheldOrgBlobRefs, + putOrgBlobBytes, +} from '../files/service.ts'; import { loadBudgetSubject } from '../governance/budget-gate.ts'; import { markRagQueued } from '../knowledge/service.ts'; import { checkTtsBudget } from '../tts/service.ts'; @@ -234,16 +238,23 @@ async function cleanupCancelledVideoLink( const job = await getJob(sql, jobId); if (!job) return; if (job.messageBoundAt !== null) return; - if (job.storageRef !== null) { - await deleteOrgBlobRefs(sql, job.organizationId, [job.storageRef]); - } if (job.fileMetadataId !== null) { + // A row a document took over (`documents/from-blob-upload`) is the + // document's file now, whatever its transcription did. await sql` DELETE FROM app.file_metadata WHERE id = ${job.fileMetadataId} AND transcription_status IS DISTINCT FROM 'completed' + AND document_id IS NULL `; } + // The row first, then the bytes, and only when nothing holds them: the + // ref is its paster's own row's ref, handed to the chip as `storageId`, so + // a task may list it and a document may have taken it over — and a + // completed transcript row, which the cleanup keeps, holds it too (#4110). + if (job.storageRef !== null) { + await deleteUnheldOrgBlobRefs(sql, job.organizationId, [job.storageRef]); + } } /** @@ -501,7 +512,8 @@ const HANDOFF_ORPHAN_WINDOW_MS = 35 * 60_000; * handoff rows whose transcription already settled (the safety net under * the settle cascade — and the heal for rows parked by older deployments), * fail handoff rows whose file row is gone, and reap terminal-but-unbound - * rows older than 7 days (blob + non-completed file row + job). + * rows older than 7 days (the file row unless a document took it over, the + * blob unless something still holds it, and the job). */ export async function runVideoLinkWatchdog(sql: Sql): Promise { const now = Date.now(); @@ -599,11 +611,16 @@ export async function runVideoLinkWatchdog(sql: Sql): Promise { for (const row of gcRows) { const job = await getJob(sql, row.id); if (!job || job.messageBoundAt !== null) continue; - if (job.storageRef !== null) { - await deleteOrgBlobRefs(sql, job.organizationId, [job.storageRef]); - } + // The cleanup's order and rule: the row goes unless a document took it + // over, then the bytes, unless something still holds them (#4110). if (job.fileMetadataId !== null) { - await sql`DELETE FROM app.file_metadata WHERE id = ${job.fileMetadataId}`; + await sql` + DELETE FROM app.file_metadata + WHERE id = ${job.fileMetadataId} AND document_id IS NULL + `; + } + if (job.storageRef !== null) { + await deleteUnheldOrgBlobRefs(sql, job.organizationId, [job.storageRef]); } await sql`DELETE FROM app.video_link_jobs WHERE id = ${row.id}`; await hintVideoJobs(sql, [job]); diff --git a/services/platform/backend/integration-check.ts b/services/platform/backend/integration-check.ts index 1852010a40..088a087c17 100644 --- a/services/platform/backend/integration-check.ts +++ b/services/platform/backend/integration-check.ts @@ -76,6 +76,11 @@ import { setMailTransportForTesting } from './domains/connectors/service.ts'; import { checkConversationApi } from './domains/conversations/api-sync.integration.ts'; import { checkErasureReviewHandoverRaces } from './domains/erasure/review-handover.integration.ts'; import { checkRagWatchdogBatch } from './domains/file_metadata/watchdogs.integration.ts'; +import { + checkStagedBundlesUnnameable, + checkTaskReleaseKeepsProductImage, + checkVideoLinkHeldBlobs, +} from './domains/files/held-blob-cleanups.integration.ts'; import { checkRejectedUploadReclaim } from './domains/files/reject-blob.integration.ts'; import { checkHubFolderWriteRole } from './domains/folders/write-role.integration.ts'; import { checkEmailedAttachments } from './domains/knowledge/attachment-mail.integration.ts'; @@ -59006,6 +59011,42 @@ async function main(): Promise { record, ), ], + [ + 'checkVideoLinkHeldBlobs', + () => + checkVideoLinkHeldBlobs( + sql, + baseUrl, + authCtx, + (label, role) => + signUpOrgMember(sql, baseUrl, authCtx.orgId, label, role), + record, + ), + ], + [ + 'checkStagedBundlesUnnameable', + () => + checkStagedBundlesUnnameable( + sql, + baseUrl, + authCtx, + (label, role) => + signUpOrgMember(sql, baseUrl, authCtx.orgId, label, role), + record, + ), + ], + [ + 'checkTaskReleaseKeepsProductImage', + () => + checkTaskReleaseKeepsProductImage( + sql, + baseUrl, + authCtx, + (label, role) => + signUpOrgMember(sql, baseUrl, authCtx.orgId, label, role), + record, + ), + ], [ 'checkNotificationProjectBackfill', () => checkNotificationProjectBackfill(sql, authCtx), diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index c99b5eb254..8f92104e2a 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -718,4 +718,4 @@ Scroll-responsive navigation is covered by `packages/ui/src/hooks/use-scroll-com | [tasks](../suites/tasks.md) | A captured reviewer can stage one listed file of at most 20 MiB with its exact review identity. The 50-entry manifest cursor binds reviewer and source evidence. Current issuer, grant, task/source membership and policy are rechecked; document bindings retain their ACL, invalid or ambiguous metadata stays unavailable. Signed v2 caps and exact-byte checks reject overflow, clean short EOF and body errors before the existing daemon writes, preserving prior bytes and leaving no new partial file. Ordinary v1 remains unchanged. Native PG/MinIO plus actual runnerd prove exact bytes, repeats and concurrent handoff refusal; historical authorized bytes may remain, and staging is not a claim of model inspection. | ✅ unit + real Postgres + native HTTP + actual daemon | `backend/core/lib/storage/sandbox_stage_token.test.ts`, `backend/domains/files/sandbox-blob-routes.test.ts`, `backend/domains/tasks/agent-review-files.test.ts`, `backend/core/node_only/sandbox/workspace_tools_bridge.test.ts`, `backend/domains/tasks/agent-review-files.integration.ts` (through `checkAgentTaskReviews`) | | [tasks](../suites/tasks.md) | Human approval after explicit agent-to-person CAS handoff reads policy strictly: invalid configuration refuses signoff without effects, valid restored configuration permits recovery, and an absent optional policy remains supported. Native verdicts also refuse unreadable policy. Human request-changes/withdrawal behavior is unchanged; the app’s comment and status writes remain separate. | ✅ unit + real Postgres + HTTP | `backend/domains/tasks/reviews.member.test.ts`, `backend/domains/tasks/agent-review.test.ts`, `backend/domains/tasks/agent-review.integration.ts`, `backend/domains/tasks/agent-review-routing.integration.ts` | -| [tasks](../suites/tasks.md) | An attachment whose bytes left the object store: the sandbox-blob door passes the store's 404 through (no longer the 502 that also means "store down"), the run start fails by the file's shown name and settles `input_missing` — never auto-retried, a steer restart included — and the task says **The agent couldn't finish this task** with `tasks.agentRun.failure.input` (the bell and e-mail body `inbox.agentRunFailedInputBody`); a gone earlier deliverable leaves the brief instead of failing the run; and the bytes any task still lists survive the file row's deletion, the abandoned-upload sweep, the client's reclaim of a rejected upload and the knowledge release — one predicate, `tasks/blob-holders.ts`. `POST /api/app/files/reject-blob` answers `deleted: false` for any ref a file row, a document (current file or retained version) or a task holds, or a non-consuming bind (task door, document multi-bind, outbound mail) vouched for, a bind racing it included, and closes the intent it reclaims so the ref can no longer be attached — one holder rule, `files/blob-holders.ts`, shared with the file delete and the sweep | ✅ backend + component + real Postgres/MinIO | `backend/domains/files/sandbox-blob-routes.test.ts`, `backend/core/tasks/agent_run_host.task_inputs.test.ts`, `backend/core/tasks/task_input_missing_error.test.ts`, `backend/core/tasks/start_failure.test.ts`, `backend/core/tasks/task_auto_retry.test.ts`, `lib/shared/task-run-failure.test.ts`, `backend/domains/collab/service.test.ts`, `app/features/tasks/components/task-agent-run-failure-notice.test.tsx`, `backend/domains/tasks/blob-holders.test.ts`, `backend/domains/knowledge/liveness.test.ts`, `backend/domains/files/upload-intents.test.ts`, `backend/domains/files/blob-holders.test.ts`, `backend/domains/files/service.reject-blob.test.ts`; `checkSandboxBlobDoor`, `checkTaskHeldBlobOutlivesFileRow` and `checkRejectedUploadReclaim` in `backend:integration` | +| [tasks](../suites/tasks.md) | An attachment whose bytes left the object store: the sandbox-blob door passes the store's 404 through (no longer the 502 that also means "store down"), the run start fails by the file's shown name and settles `input_missing` — never auto-retried, a steer restart included — and the task says **The agent couldn't finish this task** with `tasks.agentRun.failure.input` (the bell and e-mail body `inbox.agentRunFailedInputBody`); a gone earlier deliverable leaves the brief instead of failing the run; and the bytes any task still lists survive the file row's deletion, the abandoned-upload sweep, the client's reclaim of a rejected upload and the knowledge release — one predicate, `tasks/blob-holders.ts`. `POST /api/app/files/reject-blob` answers `deleted: false` for any ref a file row, a document (current file or retained version) or a task holds, or a non-consuming bind (task door, document multi-bind, outbound mail) vouched for, a bind racing it included, and closes the intent it reclaims so the ref can no longer be attached — one holder rule, `files/blob-holders.ts`, shared with the file delete and the sweep. The same rule decides a product's released image (a replace or a product delete keeps the bytes a task, a document or another file row holds) and a video link's cleanup (cancel, retry, watchdog) and 7-day unbound GC, which also never delete a file row a document took over; a staged skill or automation bundle's upload binds nothing but its own lane (the task, document and mail doors refuse it); and a task that drops a product image's ref leaves the product's row and bytes alone | ✅ backend + component + real Postgres/MinIO | `backend/domains/files/sandbox-blob-routes.test.ts`, `backend/core/tasks/agent_run_host.task_inputs.test.ts`, `backend/core/tasks/task_input_missing_error.test.ts`, `backend/core/tasks/start_failure.test.ts`, `backend/core/tasks/task_auto_retry.test.ts`, `lib/shared/task-run-failure.test.ts`, `backend/domains/collab/service.test.ts`, `app/features/tasks/components/task-agent-run-failure-notice.test.tsx`, `backend/domains/tasks/blob-holders.test.ts`, `backend/domains/knowledge/liveness.test.ts`, `backend/domains/files/upload-intents.test.ts`, `backend/domains/files/blob-holders.test.ts`, `backend/domains/files/service.reject-blob.test.ts`, `backend/domains/files/service.unheld-reclaim.test.ts`, `backend/domains/products/service.test.ts`, `backend/domains/video_links/service.finalizer.test.ts`, `backend/domains/tasks/retire.test.ts`; `checkSandboxBlobDoor`, `checkTaskHeldBlobOutlivesFileRow`, `checkRejectedUploadReclaim`, `checkProductImageReleaseHolders`, `checkVideoLinkHeldBlobs`, `checkStagedBundlesUnnameable` and `checkTaskReleaseKeepsProductImage` in `backend:integration` | From e2f0b0556d185a4c79d3a4d45fe38ca78913950c Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 3 Oct 2026 11:09:18 +0000 Subject: [PATCH 2/3] chore: re-run checks after the checkBellHintWire hang (#4112) Backend integration on 049fcdf89 (run 37116965181, job 111185558771) truncated at lane 49 of 222, checkBellHintWire, which did not settle within 10 min; the step then timed out after 30 minutes and no later lane ran. No code change. From feb13bf049d7dd41ca52e6e15cf9ecbbc04a97c6 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Sat, 3 Oct 2026 12:01:39 +0000 Subject: [PATCH 3/3] fix(platform): spare a video link's rows in the task release Agent #2's review of #4129 found the task release still deleting a video link's transcript: a link pasted before a thread exists has an unbound row, the task door takes its ref, and dropping the attachment trashed the row, so the release deleted its bytes and reaped it while the chip still read completed (the send then skipped it). The release now leaves a row a video-link job names to that job's cleanup and GC, as it leaves a product's image to the product. The cleanup and the GC found the job's row only by its recorded id, while the Whisper lane commits the audio row before patching that id: a cancel or a crash in between left the row, and under the holder rule its bytes, behind for good. Both now also drop the job's own rows by its ref (same uploader, never a document's). deleteUnheldOrgBlobRefs keeps every byte when its holder check fails, so a cancel no longer answers 500 after its flip, and says what it answers; two comments the cleanup outdated are corrected. The lanes assert the cancelled row, cover an unrecorded row, a video transcript the task drops and a registered upload control, and the register row names the four doors the bundle proof refuses at. --- .../files/held-blob-cleanups.integration.ts | 134 ++++++++++++++++-- .../platform/backend/domains/files/service.ts | 18 ++- .../files/service.unheld-reclaim.test.ts | 20 +++ .../backend/domains/tasks/retire.test.ts | 6 +- .../platform/backend/domains/tasks/retire.ts | 14 +- .../video_links/service.finalizer.test.ts | 20 +++ .../backend/domains/video_links/service.ts | 59 +++++--- .../platform/backend/integration-check.ts | 6 +- .../tests/manual/reference/automation.md | 2 +- 9 files changed, 233 insertions(+), 46 deletions(-) diff --git a/services/platform/backend/domains/files/held-blob-cleanups.integration.ts b/services/platform/backend/domains/files/held-blob-cleanups.integration.ts index c149a29328..04b2177d38 100644 --- a/services/platform/backend/domains/files/held-blob-cleanups.integration.ts +++ b/services/platform/backend/domains/files/held-blob-cleanups.integration.ts @@ -279,6 +279,8 @@ export async function checkVideoLinkHeldBlobs( status: string; fileStatus: string; aged?: boolean; + /** False: the engine committed the row but never recorded its id. */ + recorded?: boolean; }) => { const text = `video transcript probe ${args.label}`; const ref = await p.putBlob(text); @@ -303,8 +305,8 @@ export async function checkVideoLinkHeldBlobs( ${orgId}, ${p.owner.userId}, ${`https://example.test/held-${p.suffix}-${args.label}`}, ${`held-${p.suffix}-${args.label}`}, 'youtube', - ${`held-${args.label}`}, ${args.status}, ${at}, ${ref}, ${fileId}, - 'active', ${at} + ${`held-${args.label}`}, ${args.status}, ${at}, ${ref}, + ${args.recorded === false ? null : fileId}, 'active', ${at} ) RETURNING id `; return { jobId: jobs[0]?.id ?? '', fileId, ref }; @@ -362,6 +364,7 @@ export async function checkVideoLinkHeldBlobs( taskCancel === 200 && taskKept && taskListed && + taskRow === 'gone' && docBind === 200 && docCancel === 200 && docKept && @@ -423,6 +426,40 @@ export async function checkVideoLinkHeldBlobs( jobsGone.every(Boolean), `task: attach=${gcAttach.status} kept=${gcTaskKept} listed=${gcTaskListed} (want 200/true/true); document: bind=${gcBind} kept=${gcDocKept} row=${gcDocRow} (want 200/true/active); unheld: gone=${gcUnheldGone} row=${gcUnheldRow} (want true/gone); jobs reaped=${jobsGone.join('/')} (want true each)`, ); + + // A row the engine committed under the job's ref but never recorded on + // the job (the Whisper lane saves the audio row, then patches its id; a + // cancel or a crash in between): the cleanup and the GC find it by ref, + // so neither the row nor, once it is gone, its bytes outlive the job. + const lost = await videoJob({ + label: 'cancel-unrecorded', + status: 'failed', + fileStatus: 'failed', + recorded: false, + }); + const lostCancel = await cancel(lost.jobId); + const lostRow = await p.rowState(lost.fileId); + const lostGone = !(await p.present(lost.ref)); + const lostAged = await videoJob({ + label: 'gc-unrecorded', + status: 'failed', + fileStatus: 'failed', + aged: true, + recorded: false, + }); + await runVideoLinkWatchdog(sql); + const lostAgedRow = await p.rowState(lostAged.fileId); + const lostAgedGone = !(await p.present(lostAged.ref)); + record( + 'a video link’s cleanup and GC drop the row its engine never recorded, and its bytes (#4110)', + lostCancel === 200 && + lostRow === 'gone' && + lostGone && + lostAgedRow === 'gone' && + lostAgedGone && + (await jobGone(lostAged.jobId)), + `cancel: status=${lostCancel} row=${lostRow} bytes gone=${lostGone} (want 200/gone/true); GC: row=${lostAgedRow} bytes gone=${lostAgedGone} (want gone/true)`, + ); } catch (error) { recordThrow(record, 'video-link held blobs', error); } finally { @@ -508,11 +545,12 @@ export async function checkStagedBundlesUnnameable( /** * Dropping a task's attachment releases the ref: the task's own unbound * rows are trashed, and the release job takes the bytes (and reaps the - * trashed rows) once nothing live names them. A product's image row is the - * product's, not the task's: when a task let go of an image's ref, the - * release took the bytes and the row the product still shows. + * trashed rows) once nothing live names them. A product's image row and a + * video link's transcript row are their lanes', not the task's: when a task + * let go of such a ref, the release took the bytes and the row the product + * still showed, or the chip was about to send. */ -export async function checkTaskReleaseKeepsProductImage( +export async function checkTaskReleaseKeepsLaneRows( sql: Sql, base: string, ctx: { orgId: string }, @@ -579,22 +617,98 @@ export async function checkTaskReleaseKeepsProductImage( const imageKept = await p.present(imageRef); const served = (await p.call('GET', `products/images/${fileId}`)).status; - // The control: the task's own upload still goes once the task drops it. + // A video link's transcript, pasted before a thread existed (no + // thread_id): its job names the row, and a send binds it from there. + const transcript = 'video transcript held by its chip'; + const chipRef = await p.putBlob(transcript); + const now = Date.now(); + const chipRows = await sql<{ id: string }[]>` + INSERT INTO app.file_metadata ( + org_id, storage_ref, source, file_name, content_type, size, + uploaded_by, transcript, transcription_status, created_at_ms + ) VALUES ( + ${orgId}, ${chipRef}, 'video_link', 'chip.txt', + 'text/plain; charset=utf-8', ${transcript.length}, ${p.owner.userId}, + ${transcript}, 'completed', ${now} + ) RETURNING id + `; + const chipFileId = chipRows[0]?.id ?? ''; + await sql` + INSERT INTO app.video_link_jobs ( + org_id, uploaded_by, source_url, source_url_hash, source_platform, + pasted_token, status, status_changed_at_ms, storage_ref, + file_metadata_id, lifecycle_status, created_at_ms + ) VALUES ( + ${orgId}, ${p.owner.userId}, ${`https://example.test/chip-${p.suffix}`}, + ${`chip-${p.suffix}`}, 'youtube', 'chip', 'completed', ${now}, + ${chipRef}, ${chipFileId}, 'active', ${now} + ) + `; + const chipTask = await p.attach(chipRef, 'video-chip'); + const chipDrop = await dropAndRelease(chipTask.taskId, chipRef); + const chipRow = await p.rowState(chipFileId); + const chipKept = await p.present(chipRef); + + // The controls: the task's own uploads still go once the task drops + // them — one only its intent records, one registered as a file row. const own = await p.upload('file', 'a task’s own attachment'); const ownTask = await p.attach(own, 'own-attachment'); const ownDrop = await dropAndRelease(ownTask.taskId, own); const ownGone = !(await p.present(own)); + const presigned = z + .object({ url: z.string().url(), s3Ref: z.string() }) + .safeParse( + await p.jsonOf( + await p.call('POST', 'files/blob-upload', { + contentType: 'text/plain', + }), + ), + ); + if (!presigned.success) throw new Error('presign failed'); + const registeredRef = presigned.data.s3Ref; + p.refs.push(registeredRef); + await fetch(presigned.data.url, { + method: 'PUT', + headers: { 'content-type': 'text/plain' }, + body: 'a task’s own registered attachment', + }); + const registered = await p.call('POST', 'files/register', { + storageRef: registeredRef, + fileName: 'own-registered.txt', + contentType: 'text/plain', + }); + const registeredRows = await sql<{ id: string }[]>` + SELECT id FROM app.file_metadata + WHERE org_id = ${orgId} AND storage_ref = ${registeredRef} + `; + const registeredTask = await p.attach(registeredRef, 'own-registered'); + const registeredDrop = await dropAndRelease( + registeredTask.taskId, + registeredRef, + ); + const registeredRow = await p.rowState(registeredRows[0]?.id ?? ''); + const registeredGone = !(await p.present(registeredRef)); record( - 'dropping a task’s attachment leaves a product’s image to the product, and still releases the task’s own upload (#4110)', + 'dropping a task’s attachment leaves a product’s image and a video link’s transcript to their lanes, and still releases the task’s own uploads (#4110)', imageTask.status === 200 && imageDrop === 200 && imageRow === 'active' && imageKept && served === 200 && + chipTask.status === 200 && + chipDrop === 200 && + chipRow === 'active' && + chipKept && ownTask.status === 200 && ownDrop === 200 && - ownGone, - `product image: attach=${imageTask.status} drop=${imageDrop} row=${imageRow} kept=${imageKept} served=${served} (want 200/200/active/true/200); own upload: attach=${ownTask.status} drop=${ownDrop} released=${ownGone} (want 200/200/true)`, + ownGone && + registered.status === 200 && + registeredRows.length === 1 && + registeredTask.status === 200 && + registeredDrop === 200 && + registeredRow === 'gone' && + registeredGone, + `product image: attach=${imageTask.status} drop=${imageDrop} row=${imageRow} kept=${imageKept} served=${served} (want 200/200/active/true/200); video transcript: attach=${chipTask.status} drop=${chipDrop} row=${chipRow} kept=${chipKept} (want 200/200/active/true); own upload: attach=${ownTask.status} drop=${ownDrop} released=${ownGone} (want 200/200/true); own registered file: register=${registered.status} rows=${registeredRows.length} attach=${registeredTask.status} drop=${registeredDrop} row=${registeredRow} released=${registeredGone} (want 200/1/200/200/gone/true)`, ); } catch (error) { recordThrow(record, 'task release and product images', error); diff --git a/services/platform/backend/domains/files/service.ts b/services/platform/backend/domains/files/service.ts index 52b05c1c4e..db5dc2d5d4 100644 --- a/services/platform/backend/domains/files/service.ts +++ b/services/platform/backend/domains/files/service.ts @@ -741,7 +741,9 @@ export async function deleteOrgBlobRefs( * ref another row may have come to name, such as a video link's transcript, * which its paster can attach to a task or take over as a document. Drop * the lane's own rows first, as `deleteFile` does, or they keep the bytes. - * Best-effort like {@link deleteOrgBlobRefs}; answers the refs it deleted. + * Best-effort like {@link deleteOrgBlobRefs}: a holder check that fails + * keeps every byte (orphaned bytes are reclaimable later, a held ref's are + * not), and a failed delete logs. Answers the refs it judged unheld. */ export async function deleteUnheldOrgBlobRefs( db: Sql | TransactionSql, @@ -749,10 +751,16 @@ export async function deleteUnheldOrgBlobRefs( refs: readonly string[], ): Promise { if (refs.length === 0) return []; - const unheld = await db<{ ref: string }[]>` - SELECT r.ref FROM unnest(${[...refs]}::text[]) AS r(ref) - WHERE NOT ${blobRefHeld(db, organizationId, db`r.ref`)} - `; + let unheld: { ref: string }[]; + try { + unheld = await db<{ ref: string }[]>` + SELECT r.ref FROM unnest(${[...refs]}::text[]) AS r(ref) + WHERE NOT ${blobRefHeld(db, organizationId, db`r.ref`)} + `; + } catch (error) { + console.warn('[files] blob reclaim skipped (holder check failed):', error); + return []; + } const doomed = unheld.map((row) => row.ref); await deleteOrgBlobRefs(db, organizationId, doomed); return doomed; diff --git a/services/platform/backend/domains/files/service.unheld-reclaim.test.ts b/services/platform/backend/domains/files/service.unheld-reclaim.test.ts index 43d17b056d..a1d91f99a5 100644 --- a/services/platform/backend/domains/files/service.unheld-reclaim.test.ts +++ b/services/platform/backend/domains/files/service.unheld-reclaim.test.ts @@ -95,3 +95,23 @@ it('keeps every byte something holds, and asks nothing for no refs', async () => expect(await deleteUnheldOrgBlobRefs(none.sql, 'org_1', [])).toEqual([]); expect(none.statements).toEqual([]); }); + +it('keeps every byte when the holder check fails, and logs it', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + // Only the holder question fails; the fragments it is built from never + // reach the database on their own. + const failing = ((strings: TemplateStringsArray) => + strings.join('?').trim().startsWith('SELECT r.ref') + ? Promise.reject(new Error('connection lost')) + : Promise.resolve([])) as unknown as Sql; + + expect( + await deleteUnheldOrgBlobRefs(failing, 'org_1', ['s3:blobs/acme/a']), + ).toEqual([]); + expect(deleteOrgObject).not.toHaveBeenCalled(); + expect(warn).toHaveBeenCalledWith( + '[files] blob reclaim skipped (holder check failed):', + expect.any(Error), + ); + warn.mockRestore(); +}); diff --git a/services/platform/backend/domains/tasks/retire.test.ts b/services/platform/backend/domains/tasks/retire.test.ts index f7300fc530..0f6b98ac06 100644 --- a/services/platform/backend/domains/tasks/retire.test.ts +++ b/services/platform/backend/domains/tasks/retire.test.ts @@ -152,7 +152,7 @@ describe('retireTasksInTx', () => { }); describe('releaseUnlistedTaskBlobRefs', () => { - it('trashes the tasks’ own unbound rows of a dropped ref, never a product’s image row (#4110)', async () => { + it('trashes the tasks’ own unbound rows of a dropped ref, never a product’s image or a video link’s row (#4110)', async () => { const { tx, statements } = fakeTx(); await expect( @@ -168,6 +168,10 @@ describe('releaseUnlistedTaskBlobRefs', () => { expect(trash?.text).toContain( "AND source IS DISTINCT FROM 'product-image'", ); + // Nor a row a video-link job names: its job's cleanup and GC end it. + expect(trash?.text).toContain( + 'AND NOT EXISTS ( SELECT 1 FROM app.video_link_jobs job WHERE job.org_id = file_metadata.org_id AND job.file_metadata_id = file_metadata.id )', + ); expect(trash?.values).toContainEqual(['s3:only-mine']); }); diff --git a/services/platform/backend/domains/tasks/retire.ts b/services/platform/backend/domains/tasks/retire.ts index dd67d1ed4a..c2cff7b7c7 100644 --- a/services/platform/backend/domains/tasks/retire.ts +++ b/services/platform/backend/domains/tasks/retire.ts @@ -185,9 +185,12 @@ export async function releaseUnlistedTaskBlobRefs( `; const releasedRefs = orphaned.map((row) => row.ref); if (releasedRefs.length > 0) { - // A product's image row is the product's, not the task's: the product - // domain ends it (`releaseManagedImage`). Trashed here, the release - // took the bytes and the row of an image a product still shows (#4110). + // A row another lane binds outside these columns is that lane's, not + // the task's: a product's image (the product domain ends it, + // `releaseManagedImage`) and a video link's file row (its job's cleanup + // and GC end it). Trashed here, the release took the bytes and the row + // of an image a product still showed, or a transcript a chip was about + // to send (#4110). await tx` UPDATE app.file_metadata SET lifecycle_status = 'trashed', status_changed_at_ms = ${Date.now()} @@ -196,6 +199,11 @@ export async function releaseUnlistedTaskBlobRefs( AND document_id IS NULL AND thread_id IS NULL AND conversation_id IS NULL AND source IS DISTINCT FROM 'product-image' + AND NOT EXISTS ( + SELECT 1 FROM app.video_link_jobs job + WHERE job.org_id = file_metadata.org_id + AND job.file_metadata_id = file_metadata.id + ) AND (lifecycle_status IS NULL OR lifecycle_status = 'active') `; await queueRefRelease(tx, organizationId, releasedRefs); diff --git a/services/platform/backend/domains/video_links/service.finalizer.test.ts b/services/platform/backend/domains/video_links/service.finalizer.test.ts index 051d389508..c7380d61f1 100644 --- a/services/platform/backend/domains/video_links/service.finalizer.test.ts +++ b/services/platform/backend/domains/video_links/service.finalizer.test.ts @@ -368,6 +368,18 @@ describe('a video link’s reclaim', () => { "transcription_status IS DISTINCT FROM 'completed'", ); expect(texts[rowDelete]).toContain('document_id IS NULL'); + // The recorded row, or one the engine committed under the job's ref + // before recording it; a completed transcript stays (the guard is on). + expect(texts[rowDelete]).toContain( + 'id = ? OR (storage_ref = ? AND uploaded_by = ?)', + ); + expect(fake.statements[rowDelete]?.values).toEqual([ + 'org-1', + 'fm-1', + 's3:acme/t', + 'user-1', + false, + ]); expect(texts.indexOf('RECLAIM')).toBeGreaterThan(rowDelete); expect(deleteUnheldOrgBlobRefs).toHaveBeenCalledWith(fake.sql, 'org-1', [ 's3:acme/t', @@ -390,6 +402,14 @@ describe('a video link’s reclaim', () => { t.startsWith('DELETE FROM app.file_metadata'), ); expect(texts[rowDelete]).toContain('document_id IS NULL'); + // The GC takes a completed transcript too (the guard is off). + expect(fake.statements[rowDelete]?.values).toEqual([ + 'org-1', + 'fm-1', + 's3:acme/t', + 'user-1', + true, + ]); const reclaim = texts.indexOf('RECLAIM'); expect(reclaim).toBeGreaterThan(rowDelete); expect( diff --git a/services/platform/backend/domains/video_links/service.ts b/services/platform/backend/domains/video_links/service.ts index 8b198f7c5b..c05299dff9 100644 --- a/services/platform/backend/domains/video_links/service.ts +++ b/services/platform/backend/domains/video_links/service.ts @@ -227,9 +227,10 @@ async function updateJob( /** * Cancellation/retry cleanup (the 0.4 twin): message-bound rows are - * UNTOUCHABLE (their transcript is a sent bubble's content of record); - * otherwise the blob deletes best-effort and a non-completed - * file_metadata row drops. + * UNTOUCHABLE (their transcript is a sent bubble's content of record). + * Otherwise the job's own row drops, unless it is a completed transcript + * (the donor copy a cancel keeps) or a document took it over; then the + * bytes go only when nothing holds them (#4110). */ async function cleanupCancelledVideoLink( sql: Sql, @@ -238,25 +239,42 @@ async function cleanupCancelledVideoLink( const job = await getJob(sql, jobId); if (!job) return; if (job.messageBoundAt !== null) return; - if (job.fileMetadataId !== null) { - // A row a document took over (`documents/from-blob-upload`) is the - // document's file now, whatever its transcription did. - await sql` - DELETE FROM app.file_metadata - WHERE id = ${job.fileMetadataId} - AND transcription_status IS DISTINCT FROM 'completed' - AND document_id IS NULL - `; - } + await deleteJobFileRows(sql, job, { keepCompleted: true }); // The row first, then the bytes, and only when nothing holds them: the // ref is its paster's own row's ref, handed to the chip as `storageId`, so // a task may list it and a document may have taken it over — and a - // completed transcript row, which the cleanup keeps, holds it too (#4110). + // completed transcript row, which the cleanup keeps, holds it too. if (job.storageRef !== null) { await deleteUnheldOrgBlobRefs(sql, job.organizationId, [job.storageRef]); } } +/** + * Drop a job's own file rows: the one it recorded, and any its engine + * committed under the job's ref before recording it (the Whisper lane + * saves the audio row, then patches `file_metadata_id`; a cancel or a + * crash in between left that row, and so its bytes, behind for good). A + * row a document took over (`documents/from-blob-upload`) is the + * document's file now, whatever its transcription did. + */ +async function deleteJobFileRows( + sql: Sql, + job: VideoLinkJobRow, + options: { keepCompleted: boolean }, +): Promise { + if (job.fileMetadataId === null && job.storageRef === null) return; + await sql` + DELETE FROM app.file_metadata + WHERE org_id = ${job.organizationId} + AND (id = ${job.fileMetadataId} + OR (storage_ref = ${job.storageRef} + AND uploaded_by = ${job.uploadedBy})) + AND document_id IS NULL + AND (${!options.keepCompleted} + OR transcription_status IS DISTINCT FROM 'completed') + `; +} + /** * Thrown inside a finalizer transaction when the job is no longer where the * finalizer left it (`indexing`): a cancel, a watchdog flip or a retry moved @@ -611,14 +629,9 @@ export async function runVideoLinkWatchdog(sql: Sql): Promise { for (const row of gcRows) { const job = await getJob(sql, row.id); if (!job || job.messageBoundAt !== null) continue; - // The cleanup's order and rule: the row goes unless a document took it + // The cleanup's order and rule: the rows go unless a document took them // over, then the bytes, unless something still holds them (#4110). - if (job.fileMetadataId !== null) { - await sql` - DELETE FROM app.file_metadata - WHERE id = ${job.fileMetadataId} AND document_id IS NULL - `; - } + await deleteJobFileRows(sql, job, { keepCompleted: false }); if (job.storageRef !== null) { await deleteUnheldOrgBlobRefs(sql, job.organizationId, [job.storageRef]); } @@ -1310,8 +1323,8 @@ export async function cancelVideoLink( // The cancel is a CAS on the state the user saw. The finalizers settle a // job `indexing → completed` in one transaction; a cancel that landed on - // that completed row afterwards would take its blob with it (the cleanup - // keeps a completed file row) and leave a Ready chip over deleted bytes. + // that completed row afterwards would undo a job that settled on its own: + // the transcript the user was waiting for would vanish behind a skip. // A job that merely ADVANCED (still in flight) is cancelled in its new // state; a job that SETTLED on its own is left as it settled. let cancelled = job; diff --git a/services/platform/backend/integration-check.ts b/services/platform/backend/integration-check.ts index 088a087c17..b869d0357c 100644 --- a/services/platform/backend/integration-check.ts +++ b/services/platform/backend/integration-check.ts @@ -78,7 +78,7 @@ import { checkErasureReviewHandoverRaces } from './domains/erasure/review-handov import { checkRagWatchdogBatch } from './domains/file_metadata/watchdogs.integration.ts'; import { checkStagedBundlesUnnameable, - checkTaskReleaseKeepsProductImage, + checkTaskReleaseKeepsLaneRows, checkVideoLinkHeldBlobs, } from './domains/files/held-blob-cleanups.integration.ts'; import { checkRejectedUploadReclaim } from './domains/files/reject-blob.integration.ts'; @@ -59036,9 +59036,9 @@ async function main(): Promise { ), ], [ - 'checkTaskReleaseKeepsProductImage', + 'checkTaskReleaseKeepsLaneRows', () => - checkTaskReleaseKeepsProductImage( + checkTaskReleaseKeepsLaneRows( sql, baseUrl, authCtx, diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 8f92104e2a..c12f3010f9 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -718,4 +718,4 @@ Scroll-responsive navigation is covered by `packages/ui/src/hooks/use-scroll-com | [tasks](../suites/tasks.md) | A captured reviewer can stage one listed file of at most 20 MiB with its exact review identity. The 50-entry manifest cursor binds reviewer and source evidence. Current issuer, grant, task/source membership and policy are rechecked; document bindings retain their ACL, invalid or ambiguous metadata stays unavailable. Signed v2 caps and exact-byte checks reject overflow, clean short EOF and body errors before the existing daemon writes, preserving prior bytes and leaving no new partial file. Ordinary v1 remains unchanged. Native PG/MinIO plus actual runnerd prove exact bytes, repeats and concurrent handoff refusal; historical authorized bytes may remain, and staging is not a claim of model inspection. | ✅ unit + real Postgres + native HTTP + actual daemon | `backend/core/lib/storage/sandbox_stage_token.test.ts`, `backend/domains/files/sandbox-blob-routes.test.ts`, `backend/domains/tasks/agent-review-files.test.ts`, `backend/core/node_only/sandbox/workspace_tools_bridge.test.ts`, `backend/domains/tasks/agent-review-files.integration.ts` (through `checkAgentTaskReviews`) | | [tasks](../suites/tasks.md) | Human approval after explicit agent-to-person CAS handoff reads policy strictly: invalid configuration refuses signoff without effects, valid restored configuration permits recovery, and an absent optional policy remains supported. Native verdicts also refuse unreadable policy. Human request-changes/withdrawal behavior is unchanged; the app’s comment and status writes remain separate. | ✅ unit + real Postgres + HTTP | `backend/domains/tasks/reviews.member.test.ts`, `backend/domains/tasks/agent-review.test.ts`, `backend/domains/tasks/agent-review.integration.ts`, `backend/domains/tasks/agent-review-routing.integration.ts` | -| [tasks](../suites/tasks.md) | An attachment whose bytes left the object store: the sandbox-blob door passes the store's 404 through (no longer the 502 that also means "store down"), the run start fails by the file's shown name and settles `input_missing` — never auto-retried, a steer restart included — and the task says **The agent couldn't finish this task** with `tasks.agentRun.failure.input` (the bell and e-mail body `inbox.agentRunFailedInputBody`); a gone earlier deliverable leaves the brief instead of failing the run; and the bytes any task still lists survive the file row's deletion, the abandoned-upload sweep, the client's reclaim of a rejected upload and the knowledge release — one predicate, `tasks/blob-holders.ts`. `POST /api/app/files/reject-blob` answers `deleted: false` for any ref a file row, a document (current file or retained version) or a task holds, or a non-consuming bind (task door, document multi-bind, outbound mail) vouched for, a bind racing it included, and closes the intent it reclaims so the ref can no longer be attached — one holder rule, `files/blob-holders.ts`, shared with the file delete and the sweep. The same rule decides a product's released image (a replace or a product delete keeps the bytes a task, a document or another file row holds) and a video link's cleanup (cancel, retry, watchdog) and 7-day unbound GC, which also never delete a file row a document took over; a staged skill or automation bundle's upload binds nothing but its own lane (the task, document and mail doors refuse it); and a task that drops a product image's ref leaves the product's row and bytes alone | ✅ backend + component + real Postgres/MinIO | `backend/domains/files/sandbox-blob-routes.test.ts`, `backend/core/tasks/agent_run_host.task_inputs.test.ts`, `backend/core/tasks/task_input_missing_error.test.ts`, `backend/core/tasks/start_failure.test.ts`, `backend/core/tasks/task_auto_retry.test.ts`, `lib/shared/task-run-failure.test.ts`, `backend/domains/collab/service.test.ts`, `app/features/tasks/components/task-agent-run-failure-notice.test.tsx`, `backend/domains/tasks/blob-holders.test.ts`, `backend/domains/knowledge/liveness.test.ts`, `backend/domains/files/upload-intents.test.ts`, `backend/domains/files/blob-holders.test.ts`, `backend/domains/files/service.reject-blob.test.ts`, `backend/domains/files/service.unheld-reclaim.test.ts`, `backend/domains/products/service.test.ts`, `backend/domains/video_links/service.finalizer.test.ts`, `backend/domains/tasks/retire.test.ts`; `checkSandboxBlobDoor`, `checkTaskHeldBlobOutlivesFileRow`, `checkRejectedUploadReclaim`, `checkProductImageReleaseHolders`, `checkVideoLinkHeldBlobs`, `checkStagedBundlesUnnameable` and `checkTaskReleaseKeepsProductImage` in `backend:integration` | +| [tasks](../suites/tasks.md) | An attachment whose bytes left the object store: the sandbox-blob door passes the store's 404 through (no longer the 502 that also means "store down"), the run start fails by the file's shown name and settles `input_missing` — never auto-retried, a steer restart included — and the task says **The agent couldn't finish this task** with `tasks.agentRun.failure.input` (the bell and e-mail body `inbox.agentRunFailedInputBody`); a gone earlier deliverable leaves the brief instead of failing the run; and the bytes any task still lists survive the file row's deletion, the abandoned-upload sweep, the client's reclaim of a rejected upload and the knowledge release — one predicate, `tasks/blob-holders.ts`. `POST /api/app/files/reject-blob` answers `deleted: false` for any ref a file row, a document (current file or retained version) or a task holds, or a non-consuming bind (task door, document multi-bind, outbound mail) vouched for, a bind racing it included, and closes the intent it reclaims so the ref can no longer be attached — one holder rule, `files/blob-holders.ts`, shared with the file delete and the sweep. The same rule decides a product's released image (a replace or a product delete keeps the bytes a task, a document or another file row holds) and a video link's cleanup (cancel, retry, watchdog) and 7-day unbound GC, which also never delete a file row a document took over; a staged skill or automation bundle's upload binds nothing but its own lane (one proof, `ownsUploadedBlob`, refuses it at the task, document, mail and REST sync doors; the lane drives the task and document doors); a cleanup also drops the row its engine committed but never recorded on the job; and a task that drops a product image's or a video link's ref leaves that lane's row and bytes alone | ✅ backend + component + real Postgres/MinIO | `backend/domains/files/sandbox-blob-routes.test.ts`, `backend/core/tasks/agent_run_host.task_inputs.test.ts`, `backend/core/tasks/task_input_missing_error.test.ts`, `backend/core/tasks/start_failure.test.ts`, `backend/core/tasks/task_auto_retry.test.ts`, `lib/shared/task-run-failure.test.ts`, `backend/domains/collab/service.test.ts`, `app/features/tasks/components/task-agent-run-failure-notice.test.tsx`, `backend/domains/tasks/blob-holders.test.ts`, `backend/domains/knowledge/liveness.test.ts`, `backend/domains/files/upload-intents.test.ts`, `backend/domains/files/blob-holders.test.ts`, `backend/domains/files/service.reject-blob.test.ts`, `backend/domains/files/service.unheld-reclaim.test.ts`, `backend/domains/products/service.test.ts`, `backend/domains/video_links/service.finalizer.test.ts`, `backend/domains/tasks/retire.test.ts`; `checkSandboxBlobDoor`, `checkTaskHeldBlobOutlivesFileRow`, `checkRejectedUploadReclaim`, `checkProductImageReleaseHolders`, `checkVideoLinkHeldBlobs`, `checkStagedBundlesUnnameable` and `checkTaskReleaseKeepsLaneRows` in `backend:integration` |