Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Admit Beeper attachment publication and orphan cleanup

[._.]/ Adam Eivyb4f25d28ed8a
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 04ededbd88..5bc7e19d17 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -113,6 +113,7 @@ Admission inventory (`withBackupAssetPublication`):
| CoS agent archive/index publication (`cosAgentLifecycle.js`, `cosAgentArchive.js`, `cosAgentIndex.js`) | Covered (#9982 partial): completion, zombie/stale archival, deletion and legacy layout migration lease directory changes through state and index publication; state-locked workflows acquire admission first |
| Game compiled manifests (`games/compile.js`) | Covered (#9982 partial): versioned manifest and game compiled/history pointers hold one lease before the per-game queue |
| Toolkit run creation, CLI/API terminal recording and deletion (`aiToolkit/runner.js`, `internal/runFinalizer.js`) | Covered through the host-injected `withAssetPublication` boundary. Standalone toolkit defaults to direct execution. Terminal hooks run after release; output failures retain truthful persisted byte counts. This does not itself coordinate a separate runner process |
+| Beeper attachment mirror (`beeperAttachments.js`) | Covered (#9982 partial): network transfer stays outside admission; content-addressed installation/dedupe and its `local_path` row commit share admission and a path queue with eviction/orphan cleanup. This also protects snapshots that opt into the normally excluded attachment bytes |
| Runtime recording completion tails (`runtimeFilePublication.js`, server runner/TUI finalizers, CoS runner completion, loop iterations, TUI spooler) | Covered (#9982 partial): output and completion metadata are admitted together with rollback on write failure; CoS completion retains admission through runner ownership removal. Each parsed/raw spool flush is a short lease, including durable truncation/failure flags. Model execution stays outside. Uses the shared process admission protocol when installed; startup/other runtime lanes remain separately outstanding below |
| Agent usage run creation and completion (`agentRunTracking.js`) | Covered: prompt/output creation precedes metadata inside one lease; completion holds output replacement through terminal metadata, with usage and event callbacks after release |
| Active runtime transcript/metadata pairs (`runner.js`, `tuiPromptRunner.js`, `agentTuiSpawning/outputSpooler.js`, `sessionController.js`) | Outstanding (#9982): output replacement and completion metadata, parsed output/state batches and raw-spool truncation flags span writes and may execute in the separate runner process. The server-local lease cannot establish a cross-process recording cut; requires a coordinated barrier before claiming global consistency |
diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.js
index 0e9aba114e..92f346bd98 100644
--- a/server/lib/backupAssetOwners.js
+++ b/server/lib/backupAssetOwners.js
@@ -464,6 +464,13 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
'services/agentTuiSpawning/sessionController.js',
],
},
+ {
+ // Downloads remain staged outside admission. Hash-path installation/dedupe
+ // and the local_path row commit share a lease/queue with eviction and orphan
+ // cleanup. The byte mirror is an overridable backup exclusion.
+ id: 'beeper-attachment-mirror', status: 'admitted',
+ modules: ['services/beeperAttachments.js'],
+ },
// Anything the sweep did not reach. A new asset owner lands here until it is
// classified; the claim cannot become `global` while this entry exists.
{ id: 'unclassified-durable-owners', status: 'outstanding', modules: [] },
diff --git a/server/services/beeperAttachments.js b/server/services/beeperAttachments.js
index 630cbc1224..7b13edf0fa 100644
--- a/server/services/beeperAttachments.js
+++ b/server/services/beeperAttachments.js
@@ -34,6 +34,8 @@ import { dirname, join } from 'path';
import { Readable } from 'stream';
import { pipeline } from 'stream/promises';
import { query } from '../lib/db.js';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
+import { createRecordWriteQueue } from '../lib/fileWriteQueue.js';
import { ServerError } from '../lib/errorHandler.js';
import { PATHS, pathExists } from '../lib/fileUtils.js';
import {
@@ -70,6 +72,8 @@ const MAX_EVICTIONS_PER_SWEEP = 50;
export const attachmentsRoot = () => PATHS.beeperAttachments;
const tmpRoot = () => join(attachmentsRoot(), TMP_DIR_NAME);
+const queueAttachment = createRecordWriteQueue();
+const publishAttachment = (path, work) => withBackupAssetPublication(() => queueAttachment(path, work));
const notFound = () => new ServerError('Attachment not found', { status: 404, code: 'NOT_FOUND' });
@@ -224,7 +228,7 @@ const tooLarge = (bytes) => new ServerError(
* declines to report `Content-Length` would otherwise get an unbounded write
* past a ceiling the pre-flight could not see.
*/
-async function streamAssetToStore(mxcId, { maxBytes, extension }) {
+async function streamAssetToStore(mxcId, { maxBytes, extension, commit }) {
// Abort on SILENCE, not on elapsed time — see STREAM_IDLE_TIMEOUT_MS. The
// controller is handed to the client so the abort tears down the live socket,
// not just this side's reader. `abort()` cannot throw, which matters because
@@ -294,29 +298,29 @@ async function streamAssetToStore(mxcId, { maxBytes, extension }) {
const sha256 = hash.digest('hex');
const relativePath = attachmentRelativePath(sha256, extension);
const destPath = join(attachmentsRoot(), relativePath);
- await mkdir(dirname(destPath), { recursive: true });
-
- // `link` is atomic and fails with EEXIST rather than clobbering — which for
- // a content-addressed store means the bytes are already mirrored under
- // another row and this download was redundant, not a conflict.
- const linkError = await link(tmpPath, destPath).catch((err) => err);
- if (!linkError) {
- await unlink(tmpPath).catch(() => {});
- return { sha256, relativePath, bytes: received };
- }
- if (linkError.code === 'EEXIST') {
- await rm(tmpPath, { force: true }).catch(() => {});
- return { sha256, relativePath, bytes: received, deduped: true };
- }
- // EXDEV or a filesystem without hard links: rename is the portable fallback.
- const renameError = await rename(tmpPath, destPath).catch((err) => err);
- if (renameError) {
- await rm(tmpPath, { force: true }).catch(() => {});
- throw new ServerError(`Could not store attachment: ${renameError.message}`, {
- status: 500, code: 'ATTACHMENT_STORE_FAILED',
+ try {
+ // The transfer is complete. Serialize installation/dedupe and row commit
+ // with orphan cleanup for this hash; admit BEFORE waiting on that queue.
+ return await publishAttachment(relativePath, async () => {
+ await mkdir(dirname(destPath), { recursive: true });
+ const stored = { sha256, relativePath, bytes: received };
+ // link never replaces already referenced bytes. Portable fallback keeps
+ // this same path queue held through the metadata claim.
+ const linkError = await link(tmpPath, destPath).catch(error => error);
+ if (linkError?.code === 'EEXIST') stored.deduped = true;
+ else if (linkError) {
+ await rename(tmpPath, destPath).catch(error => {
+ throw new ServerError(`Could not store attachment: ${error.message}`, {
+ status: 500, code: 'ATTACHMENT_STORE_FAILED',
+ });
+ });
+ }
+ // A failed row write leaves an immutable unclaimed file for the existing
+ // orphan sweep. Never delete a deduplicated file another row may own.
+ await commit(stored);
+ return stored;
});
- }
- return { sha256, relativePath, bytes: received };
+ } finally { await rm(tmpPath, { force: true }).catch(() => {}); }
}
async function markUnavailable(row, message) {
@@ -394,24 +398,17 @@ export async function ensureAttachmentBytes(messageId, idx, { force = false } =
}
const extension = attachmentExtension({ mimeType: row.mime_type, fileName: row.file_name });
- const stored = await streamAssetToStore(row.mxc_id, { maxBytes, extension }).catch(async (err) => {
- if (err?.code === 'ASSET_UNAVAILABLE') await markUnavailable(row, err.message);
- throw err;
- });
-
- // `sha256` is not persisted (audit cluster 06 decision 3): it was written
- // here but never read back — the content-addressed path is built from the
- // hash `streamAssetToStore` just computed, not from this column. The VALUE
- // stays in `stored.sha256` / `stored.relativePath` for that path; only the
- // column write goes.
- await query(
+ const stored = await streamAssetToStore(row.mxc_id, { maxBytes, extension, commit: stored => query(
`UPDATE beeper_attachments
SET local_path = $3, byte_length = $4,
fetched_at = NOW(), last_viewed_at = NOW(),
unavailable_at = NULL, fetch_error = NULL, updated_at = NOW()
WHERE message_id = $1 AND idx = $2`,
[row.message_id, row.idx, stored.relativePath, stored.bytes],
- );
+ ) }).catch(async err => {
+ if (err?.code === 'ASSET_UNAVAILABLE') await markUnavailable(row, err.message);
+ throw err;
+ });
console.log(`🫧 Beeper attachment mirrored: ${stored.bytes} bytes for message ${row.message_id}#${row.idx}${stored.deduped ? ' (deduped)' : ''}`);
return {
filePath: join(attachmentsRoot(), stored.relativePath),
@@ -519,12 +516,14 @@ export async function backfillAttachments({ limit = 500 } = {}) {
*/
async function releaseRowBytes(row) {
const relativePath = row.local_path;
- await query(
- `UPDATE beeper_attachments SET local_path = NULL, fetched_at = NULL, updated_at = NOW()
- WHERE message_id = $1 AND idx = $2`,
- [row.message_id, row.idx],
- );
- return unlinkIfUnreferenced(relativePath);
+ return publishAttachment(relativePath, async () => {
+ await query(
+ `UPDATE beeper_attachments SET local_path = NULL, fetched_at = NULL, updated_at = NOW()
+ WHERE message_id = $1 AND idx = $2`,
+ [row.message_id, row.idx],
+ );
+ return unlinkIfUnreferencedNow(relativePath);
+ });
}
/**
@@ -544,6 +543,10 @@ async function releaseRowBytes(row) {
* @returns {Promise<{ removed: boolean, bytes: number, failed: boolean }>}
*/
async function unlinkIfUnreferenced(relativePath) {
+ return publishAttachment(relativePath, () => unlinkIfUnreferencedNow(relativePath));
+}
+
+async function unlinkIfUnreferencedNow(relativePath) {
const untouched = { removed: false, bytes: 0, failed: false };
if (!relativePath || !isSafeAttachmentRelativePath(relativePath)) return untouched;
const others = await query(
diff --git a/server/services/beeperAttachments.test.js b/server/services/beeperAttachments.test.js
index 50ecd4650e..6263e8d0a5 100644
--- a/server/services/beeperAttachments.test.js
+++ b/server/services/beeperAttachments.test.js
@@ -13,13 +13,22 @@
* instance, and nothing here sends anything through a messaging API.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { mkdirSync, readdirSync, rmSync, utimesSync, writeFileSync, existsSync } from 'fs';
+import { mkdirSync, readdirSync, rmSync, utimesSync, writeFileSync, readFileSync, existsSync } from 'fs';
import { dirname, join } from 'path';
import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
const tempRoot = createTempDataRoot('portos-beeper-attachments-');
vi.mock('../lib/db.js', () => ({ query: vi.fn() }));
+const publicationSeam = vi.hoisted(() => ({ bypass: false, reached: null }));
+vi.mock('../lib/backupSnapshotBoundary.js', async original => {
+ const actual = await original();
+ return { ...actual, withBackupAssetPublication: work => {
+ publicationSeam.reached?.();
+ return publicationSeam.bypass ? work() : actual.withBackupAssetPublication(work);
+ } };
+});
+
vi.mock('./settings.js', () => ({ getSettings: vi.fn() }));
// The client is mocked WHOLE rather than partially: importing the real module
// pulls in the vault-backed credential store, which reads `PATHS` at import
@@ -120,6 +129,7 @@ const storedFiles = () => {
beforeEach(() => {
vi.clearAllMocks();
+ publicationSeam.bypass = false; publicationSeam.reached = null;
vi.mocked(getSettings).mockResolvedValue({ beeper: { attachmentBudgetGb: 5 } });
rmSync(tempRoot, { recursive: true, force: true });
mkdirSync(tempRoot, { recursive: true });
@@ -750,3 +760,90 @@ describe('shapeAttachment', () => {
expect(shaped).toMatchObject({ stored: true, unavailable: true, overCap: true });
});
});
+
+
+describe('attachment snapshot publication', () => {
+ const deferred = () => Promise.withResolvers();
+ function mirror(beforeCommit = async () => {}) {
+ let row = attachmentRow();
+ vi.mocked(query).mockImplementation(async (sql, params) => {
+ const flat = String(sql).replace(/\s+/g, ' ');
+ if (flat.includes('FROM beeper_attachments WHERE message_id')) return { rows: [row] };
+ if (flat.includes('SET local_path = $3')) {
+ await beforeCommit(params[2]);
+ row = { ...row, local_path: params[2], byte_length: params[3] };
+ }
+ if (flat.includes('SELECT DISTINCT local_path')) return { rows: row.local_path ? [{ local_path: row.local_path }] : [] };
+ if (flat.includes('SELECT 1 FROM beeper_attachments')) return { rows: row.local_path ? [{}] : [] };
+ return { rows: [] };
+ });
+ vi.mocked(headAsset).mockResolvedValue({ bytes: 4 });
+ vi.mocked(fetchAssetStream).mockImplementation(async () => streamResponse([new Uint8Array([1, 2, 3, 4])]));
+ return { row: () => row, forget: () => { row = { ...row, local_path: null }; } };
+ }
+
+ it.each([false, true])('keeps a new path outside an active file-copy cut (bypass=%s)', async bypass => {
+ const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');
+ const table = mirror();
+ const arrived = deferred();
+ publicationSeam.reached = arrived.resolve;
+ publicationSeam.bypass = bypass;
+ const release = await acquireBackupSnapshotCut();
+ const copiedFiles = storedFiles();
+ const work = ensureAttachmentBytes('msg-example-1', 0);
+ try {
+ await arrived.promise;
+ if (bypass) await work;
+ expect(table.row().local_path != null).toBe(bypass);
+ // Negative control: a post-copy database dump names bytes not copied.
+ expect(table.row().local_path != null && !copiedFiles.includes(table.row().local_path)).toBe(bypass);
+ } finally { release(); await work; }
+ expect(readFileSync(join(attachmentsRoot(), table.row().local_path))).toEqual(Buffer.from([1, 2, 3, 4]));
+ });
+
+ it('drains an installed file through its row commit, including row-write failure', async () => {
+ const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');
+ const reached = deferred(); const finish = deferred();
+ const table = mirror(async () => { reached.resolve(); await finish.promise; throw new Error('row unavailable'); });
+ const work = ensureAttachmentBytes('msg-example-1', 0);
+ const rejected = expect(work).rejects.toThrow('row unavailable');
+ await reached.promise;
+ expect(storedFiles()).toHaveLength(1);
+ let cutReady = false;
+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });
+ try {
+ await new Promise(resolve => setImmediate(resolve));
+ expect(cutReady).toBe(false);
+ } finally { finish.resolve(); }
+ await rejected;
+ const release = await cut;
+ try {
+ expect(table.row().local_path).toBeNull();
+ // Unclaimed immutable bytes are safe; cleanup must not remove deduped data.
+ expect(storedFiles()).toHaveLength(1);
+ } finally { release(); }
+ });
+
+ it('serializes orphan deletion behind a deduplicated file claim', async () => {
+ let block = false;
+ const reached = deferred(); const finish = deferred();
+ const table = mirror(async () => { if (block) { reached.resolve(); await finish.promise; } });
+ const first = await ensureAttachmentBytes('msg-example-1', 0);
+ table.forget(); block = true;
+ const old = new Date(Date.now() - 2 * 60 * 60 * 1000);
+ utimesSync(first.filePath, old, old);
+ const claim = ensureAttachmentBytes('msg-example-1', 0);
+ await reached.promise;
+ const deleting = deferred();
+ publicationSeam.reached = deleting.resolve;
+ const sweep = sweepAttachmentOrphans();
+ try {
+ await deleting.promise;
+ expect(existsSync(first.filePath)).toBe(true);
+ } finally { finish.resolve(); }
+ await claim;
+ expect(await sweep).toMatchObject({ orphansRemoved: 0 });
+ expect(table.row().local_path).not.toBeNull();
+ expect(existsSync(first.filePath)).toBe(true);
+ });
+});