Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(avatars): stop a deleted copy from wiping the R2 objects a live avatar still points at

nirholasc7fb0c6f6dcf
diff --git a/api/_lib/avatars.js b/api/_lib/avatars.js
index d9156a5a7..ff52013fa 100644
--- a/api/_lib/avatars.js
+++ b/api/_lib/avatars.js
@@ -214,6 +214,27 @@ export async function updateAvatar({ id, userId, patch }) {
return row ? decorate(row) : null;
}
+// A copy, remix or forge variant points at the source avatar's R2 objects
+// instead of duplicating the bytes, so two rows routinely share one
+// storage_key or thumbnail_key. Deleting an object for a soft-deleted row
+// therefore blanks every LIVE avatar still pointing at it: that is how live
+// avatars ended up serving 404 models and broken thumbnails across the
+// gallery, /pulse and every agent card. Only a key no live row still
+// references may be removed from the bucket.
+async function unreferencedKeys(keys) {
+ const wanted = [...new Set(keys.filter(Boolean))];
+ if (!wanted.length) return [];
+ const rows = await sql`
+ select storage_key as k from avatars
+ where deleted_at is null and storage_key = any(${wanted}::text[])
+ union
+ select thumbnail_key as k from avatars
+ where deleted_at is null and thumbnail_key = any(${wanted}::text[])
+ `;
+ const stillUsed = new Set(rows.map((r) => r.k));
+ return wanted.filter((k) => !stillUsed.has(k));
+}
+
export async function deleteAvatar({ id, userId }) {
const rows = await sql`
update avatars set deleted_at = now()
@@ -224,15 +245,22 @@ export async function deleteAvatar({ id, userId }) {
if (!row) return false;
// Fire-and-forget object delete — DB row is source of truth.
queueMicrotask(async () => {
+ let keys;
try {
- await deleteObject(row.storage_key);
+ keys = await unreferencedKeys([row.storage_key, row.thumbnail_key]);
} catch (e) {
- console.warn('r2 delete failed', e?.message);
+ // Never guess when the reference check itself fails: keeping an object
+ // costs storage, deleting a shared one costs a live avatar its model.
+ console.warn('avatar key reference check failed, keeping objects', e?.message);
+ return;
}
- if (row.thumbnail_key)
+ for (const key of keys) {
try {
- await deleteObject(row.thumbnail_key);
- } catch {}
+ await deleteObject(key);
+ } catch (e) {
+ console.warn('r2 delete failed', e?.message);
+ }
+ }
});
return true;
}
diff --git a/scripts/repair-orphaned-avatar-assets.mjs b/scripts/repair-orphaned-avatar-assets.mjs
new file mode 100644
index 000000000..cd25b5b06
--- /dev/null
+++ b/scripts/repair-orphaned-avatar-assets.mjs
@@ -0,0 +1,160 @@
+#!/usr/bin/env node
+/**
+ * Find live avatars whose R2 objects are gone, and re-queue the recoverable ones.
+ *
+ * Why these exist: a copy, remix or forge variant points at the source avatar's
+ * storage_key / thumbnail_key instead of duplicating the bytes, and deleteAvatar
+ * used to delete those objects by key whenever ANY row holding them was removed.
+ * That blanked live avatars sharing the key: a 404 GLB in the viewer, a broken
+ * thumbnail in the gallery, /pulse and every agent card. api/_lib/avatars.js now
+ * reference-counts before deleting, so no new orphans appear; this script cleans
+ * up the ones already on disk.
+ *
+ * What it does:
+ * • Probes each candidate row's objects with a credentialed HEAD against the
+ * bucket (authoritative, not a public-URL guess).
+ * • --apply clears a dangling thumbnail_key. That is a repair, not a loss: a
+ * null thumbnail_key is exactly what api/_lib/avatar-thumbs.js claims, so
+ * the thumbnail cron re-renders the poster from the GLB on its next pass.
+ * • A dangling storage_key (the model itself) is REPORTED, never written. The
+ * bytes are unrecoverable from here and what to do with the row is the
+ * owner's call, not this script's.
+ *
+ * Usage (needs DATABASE_URL + S3_*, both in .env):
+ *
+ * node --env-file=.env scripts/repair-orphaned-avatar-assets.mjs
+ * node --env-file=.env scripts/repair-orphaned-avatar-assets.mjs --apply
+ * node --env-file=.env scripts/repair-orphaned-avatar-assets.mjs --all --limit=2000
+ *
+ * Flags:
+ * --apply clear dangling thumbnail_key values (default: dry run)
+ * --all probe every live avatar, not just rows sharing a key with
+ * a soft-deleted row (the population the delete bug hit)
+ * --limit=N cap rows probed (default: no cap targeted, 2000 with --all)
+ * --concurrency=N parallel HEAD probes (default 8)
+ */
+
+import { sql } from '../api/_lib/db.js';
+import { headObject } from '../api/_lib/r2.js';
+
+const argv = process.argv.slice(2);
+const has = (name) => argv.includes(`--${name}`);
+const num = (name, fallback) => {
+ const hit = argv.find((a) => a.startsWith(`--${name}=`));
+ const n = hit ? Number(hit.split('=')[1]) : NaN;
+ return Number.isFinite(n) && n > 0 ? n : fallback;
+};
+
+const APPLY = has('apply');
+const ALL = has('all');
+const LIMIT = num('limit', ALL ? 2000 : 0);
+const CONCURRENCY = Math.max(1, num('concurrency', 8));
+
+// Keys that are already absolute URLs live outside the bucket (first-party
+// /avatars/*.glb, externally hosted models). headObject returns null for them,
+// which would read as "missing". Skip them instead of inventing a repair.
+const isBucketKey = (k) => typeof k === 'string' && k.length > 0 && !/^https?:\/\//i.test(k);
+
+async function candidates() {
+ const rows = ALL
+ ? await sql`
+ select id, name, visibility, storage_key, thumbnail_key
+ from avatars
+ where deleted_at is null
+ order by created_at desc
+ limit ${LIMIT}
+ `
+ : await sql`
+ select id, name, visibility, storage_key, thumbnail_key
+ from avatars a
+ where a.deleted_at is null
+ and (
+ exists (select 1 from avatars b
+ where b.deleted_at is not null and b.storage_key = a.storage_key)
+ or exists (select 1 from avatars c
+ where c.deleted_at is not null and c.thumbnail_key = a.thumbnail_key)
+ )
+ order by a.created_at desc
+ `;
+ return LIMIT && rows.length > LIMIT ? rows.slice(0, LIMIT) : rows;
+}
+
+// One HEAD per distinct key, memoised: sibling rows share keys by definition here.
+const probed = new Map();
+async function exists(key) {
+ if (!isBucketKey(key)) return true;
+ if (!probed.has(key)) probed.set(key, headObject(key).then((o) => o != null));
+ return probed.get(key);
+}
+
+async function mapWithConcurrency(items, fn) {
+ const out = new Array(items.length);
+ let next = 0;
+ await Promise.all(
+ Array.from({ length: Math.min(CONCURRENCY, items.length) }, async () => {
+ while (next < items.length) {
+ const i = next++;
+ out[i] = await fn(items[i]);
+ }
+ }),
+ );
+ return out;
+}
+
+async function main() {
+ const rows = await candidates();
+ console.log(
+ `Probing ${rows.length} live avatar row(s) [${ALL ? 'all' : 'shared-key at-risk set'}], ` +
+ `concurrency ${CONCURRENCY}, ${APPLY ? 'APPLY' : 'dry run'}`,
+ );
+ if (!rows.length) {
+ console.log('Nothing to probe.');
+ return;
+ }
+
+ const checked = await mapWithConcurrency(rows, async (r) => ({
+ ...r,
+ modelMissing: !(await exists(r.storage_key)),
+ thumbMissing: isBucketKey(r.thumbnail_key) ? !(await exists(r.thumbnail_key)) : false,
+ }));
+
+ const deadThumbs = checked.filter((r) => r.thumbMissing);
+ const deadModels = checked.filter((r) => r.modelMissing);
+
+ if (deadModels.length) {
+ console.log(`\n${deadModels.length} avatar(s) whose MODEL object is gone (reported only):`);
+ for (const r of deadModels) {
+ console.log(` ${r.id} ${r.visibility.padEnd(8)} ${r.storage_key} (${r.name || 'unnamed'})`);
+ }
+ }
+
+ if (!deadThumbs.length) {
+ console.log('\nNo dangling thumbnail_key values found.');
+ } else {
+ console.log(`\n${deadThumbs.length} avatar(s) with a dangling thumbnail_key:`);
+ for (const r of deadThumbs) {
+ console.log(` ${r.id} ${r.visibility.padEnd(8)} ${r.thumbnail_key} (${r.name || 'unnamed'})`);
+ }
+ if (!APPLY) {
+ console.log('\nDry run: re-run with --apply to clear them so the thumbnail cron re-renders.');
+ } else {
+ const ids = deadThumbs.map((r) => r.id);
+ const updated = await sql`
+ update avatars set thumbnail_key = null, updated_at = now()
+ where id = any(${ids}::uuid[]) and deleted_at is null
+ returning id
+ `;
+ console.log(`\nCleared thumbnail_key on ${updated.length} row(s); the thumbnail backfill will re-render them.`);
+ }
+ }
+
+ console.log(
+ `\nSummary: ${rows.length} probed · ${probed.size} distinct object(s) checked · ` +
+ `${deadModels.length} missing model(s) · ${deadThumbs.length} missing thumbnail(s)`,
+ );
+}
+
+main().catch((err) => {
+ console.error(err?.stack || err?.message || err);
+ process.exit(1);
+});
diff --git a/tests/api/avatars-delete-shared-keys.test.js b/tests/api/avatars-delete-shared-keys.test.js
new file mode 100644
index 000000000..49ec28e49
--- /dev/null
+++ b/tests/api/avatars-delete-shared-keys.test.js
@@ -0,0 +1,101 @@
+// Tests for deleteAvatar's R2 cleanup: the reference check that keeps a
+// soft-deleted copy from blanking the live avatar it shares objects with.
+//
+// A copy, remix or forge variant reuses the source avatar's storage_key and
+// thumbnail_key rather than duplicating the bytes, so deleting objects by key
+// alone used to 404 live avatars' models and thumbnails. DB and R2 are mocked
+// so the suite runs offline.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const sqlState = {
+ deletedRow: { storage_key: 'u/user-1/orbit.glb', thumbnail_key: 'thumb/orbit.png' },
+ // Keys some OTHER live avatar row still points at.
+ stillReferenced: [],
+ refCheckError: null,
+};
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings) => {
+ const text = Array.isArray(strings) ? strings.join('?') : String(strings);
+ if (/update avatars set deleted_at/i.test(text)) {
+ return sqlState.deletedRow ? [sqlState.deletedRow] : [];
+ }
+ if (/select storage_key/i.test(text)) {
+ if (sqlState.refCheckError) throw sqlState.refCheckError;
+ return sqlState.stillReferenced.map((k) => ({ k }));
+ }
+ return [];
+ }),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const deleteObject = vi.fn(async () => {});
+vi.mock('../../api/_lib/r2.js', () => ({
+ deleteObject: (...a) => deleteObject(...a),
+ publicUrl: (key) => `https://cdn.test/${key}`,
+ thumbnailUrl: (key) => `https://cdn.test/${key}`,
+ presignGet: async (key) => `https://cdn.test/${key}?signed`,
+}));
+
+const { deleteAvatar } = await import('../../api/_lib/avatars.js');
+
+// deleteAvatar schedules its cleanup on a microtask that then awaits the DB, so
+// give the queue a few turns before asserting on the bucket calls.
+const settle = async () => {
+ for (let i = 0; i < 5; i++) await new Promise((r) => setTimeout(r, 0));
+};
+
+describe('deleteAvatar object cleanup', () => {
+ beforeEach(() => {
+ deleteObject.mockClear();
+ sqlState.deletedRow = { storage_key: 'u/user-1/orbit.glb', thumbnail_key: 'thumb/orbit.png' };
+ sqlState.stillReferenced = [];
+ sqlState.refCheckError = null;
+ });
+
+ it('deletes both objects when no live avatar references them', async () => {
+ expect(await deleteAvatar({ id: 'a1', userId: 'user-1' })).toBe(true);
+ await settle();
+ expect(deleteObject.mock.calls.map((c) => c[0]).sort()).toEqual([
+ 'thumb/orbit.png',
+ 'u/user-1/orbit.glb',
+ ]);
+ });
+
+ it('keeps a thumbnail another live avatar still points at', async () => {
+ sqlState.stillReferenced = ['thumb/orbit.png'];
+ await deleteAvatar({ id: 'a1', userId: 'user-1' });
+ await settle();
+ expect(deleteObject.mock.calls.map((c) => c[0])).toEqual(['u/user-1/orbit.glb']);
+ });
+
+ it('keeps the model a live copy still points at', async () => {
+ sqlState.stillReferenced = ['u/user-1/orbit.glb', 'thumb/orbit.png'];
+ await deleteAvatar({ id: 'a1', userId: 'user-1' });
+ await settle();
+ expect(deleteObject).not.toHaveBeenCalled();
+ });
+
+ it('keeps every object when the reference check itself fails', async () => {
+ sqlState.refCheckError = new Error('db unavailable');
+ await deleteAvatar({ id: 'a1', userId: 'user-1' });
+ await settle();
+ expect(deleteObject).not.toHaveBeenCalled();
+ });
+
+ it('skips the bucket entirely when the row has no keys', async () => {
+ sqlState.deletedRow = { storage_key: null, thumbnail_key: null };
+ expect(await deleteAvatar({ id: 'a1', userId: 'user-1' })).toBe(true);
+ await settle();
+ expect(deleteObject).not.toHaveBeenCalled();
+ });
+
+ it('returns false and touches nothing when the row is not the caller’s', async () => {
+ sqlState.deletedRow = null;
+ expect(await deleteAvatar({ id: 'a1', userId: 'someone-else' })).toBe(false);
+ await settle();
+ expect(deleteObject).not.toHaveBeenCalled();
+ });
+});