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

fix: ack-track bundled music-video track tombstones so GC can't strand a delete (#1922)

[._.]/ Adam Eivy92997270597d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a0e95fe42d..f8d0ec86a4 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -39,6 +39,7 @@
## Fixed
+- **[issue-1922] Music-video federation's bundled track tombstone is now ack-tracked, closing a narrow track-GC strand window** — #1858 bundles a music-video project's linked track record (`linkedTrack`) so a Music-Videos-only peer (no `track` subscription) can resolve it, and a track delete fans the tombstone out the same way. But `computeAckedDeletesFromPayload` (`peerSyncReceive.js`) only looked at `record`/`issues`, never `linkedTrack`, so such a peer could never ack a bundled track delete through any cursor — and the sender's `track`-tombstone GC cohort (`tombstoneGc.js`) only ever waited on peers with a direct `track` subscription, so it was entirely blind to a musicVideoProjects-only peer regardless of the ack fix. Implemented option (a) from the deferred #1858 review: `computeAckedDeletesFromPayload` now folds in a bundled `linkedTrack` tombstone's `deletedAt`, and the `track` GC cutoff additionally folds `musicVideoProject` subscribers into its cohort, reading their confirmed-delivery floor off a new bundle-specific `lastConfirmedTrackBundleAtMs` (stamped only when the bundled track merge actually succeeded — not the generic `lastConfirmedPushedAt`, which advances even when the bundle failed or was stripped for a legacy peer). Local subscription-state addition only; no wire-payload shape change, so no schema-version bump. (#1922)
- **[issue-1858] Music-video federation now ships the linked track to a Music-Videos-only subscriber** — a music-video project created the normal way stores a `trackId` with `uploadedAudioFilename: null`, so a peer subscribed to the **Music Videos** category only (not Music/Tracks) received the project and scene clips but no master audio, and its render failed with `Linked track not found` / `AUDIO_MISSING`. Because the receiver's `resolveMasterAudioPath()` looks the track up by id *before* touching any file, shipping the bytes alone wasn't enough — the push now bundles the linked **track record** itself (`linkedTrack`, merged via `mergeTracksFromSync` and gated by the same tombstone/opt-out rules as `linkedCollection`) *and* its `audioFilename` bytes in the music-video asset manifest. Additive optional payload key, so no schema-version bump and older peers ignore it; dedup-by-`music:<filename>` keeps a separately-federated track from double-shipping. A linked-track edit now also fans a push out to every music-video project that links it (so the bundled audio stays fresh on a Music-Videos-only peer), the receiver requires the bundle's id to match the project's `trackId` (no smuggling an unrelated track), and the bundle rides the push hash + schema gate + delivery-pending ack exactly like the existing `linkedCollection`/`manuscriptReview` bundles. (#1858)
- **[issue-1845] Client fetch hygiene — effect fetches now abort on cleanup and `window` is read lazily** — `StagePromptModelPicker` fired two effect `fetch`es guarded only by a `cancelled` flag, so rapid `stageName` changes wasted in-flight round-trips; it now passes an `AbortController` `signal` to both and aborts on cleanup. `LocalSetupPanel`'s `/setup/check` fetch had no abort and its `setChecking(false)` `finally` could fire after unmount; it now aborts the prior/in-flight check (so a stale response can't clobber a newer one) and guards every state set behind a `mountedRef`. `VoiceCapture` read `window.SpeechRecognition` at module scope — a `ReferenceError` when the file is imported in an SSR/Node test context — now resolved lazily via a `useState` initializer that only runs in the browser. And `useArmedAction`'s `fire` is wrapped in `useCallback` so memoized children stay stable. (#1845)
- **`useEscapeKey`/`useClickOutside` no longer thrash their global listener on every render** — both hooks kept the caller's `handler`/`onOutside` in the effect dep array, so the `window` keydown/mousedown listener was removed and re-added on every parent render while open. Since most call sites pass a fresh inline arrow (`() => setOpenCommentId(null)`), that meant a full detach+reattach on *every keystroke* in editors like `PipelineManuscriptEditor`/`AnnotatedManuscriptSection` and on every render of `SceneCard`/`WorkEditor`/`UniverseBuilder`. Both hooks now read the handler through a ref (the same pattern `useKeyboardShortcuts` already uses), so the listener subscribes only when `active` (and, for `useClickOutside`, `ref`) changes while still always invoking the latest handler. Behavior-preserving; covered by new hook tests. (#1844)
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 523cb72e5c..7d248d3ead 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -222,6 +222,12 @@ export async function subscribePeer({ peerId, recordKind, recordId }, opts = {})
// line. Lives on the row → cleaned up for free when the row is
// removed (`unsubscribePeer`), no separate storage to leak.
lastConfirmedPushedAt: null,
+ // #1922: same contract as `lastConfirmedPushedAt`, scoped to confirmed
+ // delivery of a BUNDLED `linkedTrack` tombstone/record (#1858) on a
+ // musicVideoProject subscription — see peerSyncPush.js
+ // `persistPushSuccess` and tombstoneGc.js's `track` cutoff. Stays
+ // `null` for every other recordKind.
+ lastConfirmedTrackBundleAtMs: null,
adoptedFromReverse: opts.adoptedFromReverse === true,
};
state.subscriptions.push(existing);
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index d1a160db93..ff474037d9 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -2425,6 +2425,62 @@ describe('peerSync', () => {
expect(captured.assetManifest.filter(a => a.kind === 'music')).toEqual([]);
});
+ it('stamps lastConfirmedTrackBundleAtMs on a confirmed push whose bundled track merge succeeded (#1922)', async () => {
+ // tombstoneGc's `track` cutoff reads this bundle-specific floor off
+ // musicVideoProject subscription rows (a peer with no `track`
+ // subscription of its own would otherwise be invisible to track GC).
+ enableMusicVideoPeer();
+ vi.mocked(getTrack).mockResolvedValue({
+ id: 'track-10', title: 'Bundled', audioFilename: 'linked.mp3',
+ updatedAt: '2026-06-28T00:00:00Z', deleted: false, deletedAt: null,
+ });
+ vi.mocked(getMusicVideoProject).mockResolvedValue({
+ id: 'mv-10', name: 'Bundled', mode: 'director', trackId: 'track-10',
+ uploadedAudioFilename: null, scenes: [],
+ updatedAt: '2026-06-28T00:00:00Z', deleted: false, deletedAt: null,
+ });
+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({ missingAssets: [] }) });
+ const before = Date.now();
+ const sub = await subscribePeer(
+ { peerId: 'peer-a', recordKind: 'musicVideoProject', recordId: 'mv-10' },
+ { adoptedFromReverse: true },
+ );
+ expect(sub.lastConfirmedTrackBundleAtMs).toBeNull();
+ await pushRecordToPeer(sub);
+ const refreshed = await findPeerSubscription('peer-a', 'musicVideoProject', 'mv-10');
+ expect(refreshed.lastConfirmedTrackBundleAtMs).toBeGreaterThanOrEqual(before);
+ });
+
+ it('does NOT stamp lastConfirmedTrackBundleAtMs when the bundled track merge failed on the receiver (#1922)', async () => {
+ // trackSyncPending means the receiver applied the project but the
+ // bundled track merge threw — the peer never actually got the track,
+ // so the bundle-specific floor must stay unset (the generic
+ // lastConfirmedPushedAt still advances; that's a separate water-mark
+ // for the project record itself, not the bundled track).
+ enableMusicVideoPeer();
+ vi.mocked(getTrack).mockResolvedValue({
+ id: 'track-11', title: 'Pending', audioFilename: 'linked.mp3',
+ updatedAt: '2026-06-28T00:00:00Z', deleted: false, deletedAt: null,
+ });
+ vi.mocked(getMusicVideoProject).mockResolvedValue({
+ id: 'mv-11', name: 'Pending', mode: 'director', trackId: 'track-11',
+ uploadedAudioFilename: null, scenes: [],
+ updatedAt: '2026-06-28T00:00:00Z', deleted: false, deletedAt: null,
+ });
+ vi.mocked(peerFetch).mockResolvedValue({
+ ok: true,
+ json: async () => ({ missingAssets: [], trackSyncPending: true }),
+ });
+ const sub = await subscribePeer(
+ { peerId: 'peer-a', recordKind: 'musicVideoProject', recordId: 'mv-11' },
+ { adoptedFromReverse: true },
+ );
+ await pushRecordToPeer(sub);
+ const refreshed = await findPeerSubscription('peer-a', 'musicVideoProject', 'mv-11');
+ expect(refreshed.lastConfirmedTrackBundleAtMs).toBeNull();
+ expect(refreshed.lastConfirmedPushedAt).toBeTruthy();
+ });
+
it('omits linkedTrack when the project has no linked track', async () => {
enableMusicVideoPeer();
vi.mocked(getMusicVideoProject).mockResolvedValue({
@@ -2955,6 +3011,33 @@ describe('peerSync', () => {
expect(result.ackedDeletesUpTo).toBe(Date.parse('2026-03-01T00:00:00Z'));
});
+ it('folds a bundled linkedTrack tombstone into ackedDeletesUpTo (#1922)', async () => {
+ // Regression: a musicVideoProjects-only peer has no independent `track`
+ // subscription, so the bundled linkedTrack tombstone (#1858) was the
+ // ONLY way it could ever ack a track delete. Before this fix,
+ // computeAckedDeletesFromPayload ignored `linkedTrack` entirely, so the
+ // sender's track-tombstone GC cohort never waited on this peer at all.
+ const result = await applyIncomingPush({
+ kind: 'musicVideoProject',
+ record: { id: 'mv-12', trackId: 'track-12', deleted: false, deletedAt: null },
+ linkedTrack: { id: 'track-12', deleted: true, deletedAt: '2026-04-01T00:00:00Z' },
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ expect(result.ackedDeletesUpTo).toBe(Date.parse('2026-04-01T00:00:00Z'));
+ });
+
+ it('does NOT fold a LIVE bundled linkedTrack into ackedDeletesUpTo (only tombstones count)', async () => {
+ const result = await applyIncomingPush({
+ kind: 'musicVideoProject',
+ record: { id: 'mv-13', trackId: 'track-13', deleted: false, deletedAt: null },
+ linkedTrack: { id: 'track-13', deleted: false, deletedAt: null },
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ });
+ expect(result.ackedDeletesUpTo).toBe(0);
+ });
+
it('auto-creates a reverse subscription back to the sender', async () => {
// The merge path actually landed the record locally, so the
// classifyLocalRecord('universe', 'u1') call inside
diff --git a/server/services/sharing/peerSyncPush.js b/server/services/sharing/peerSyncPush.js
index 4005e7b953..91558a1f22 100644
--- a/server/services/sharing/peerSyncPush.js
+++ b/server/services/sharing/peerSyncPush.js
@@ -422,7 +422,19 @@ export async function pushRecordToPeer(sub, options = {}) {
// the tombstone's deletedAt once it lands. The `missingAssets` case still
// counts as confirmed delivery of the RECORD (merge ran on the receiver);
// only the asset-stranded hash is withheld, not the confirmation mark.
- await persistPushSuccess(sub.id, (missingCount > 0 || reviewSyncPending || outlineSyncPending || trackSyncPending) ? null : hash, { confirmedAtMs: Date.now() });
+ //
+ // #1922: a musicVideoProject subscription is also a delivery vehicle for
+ // its bundled `linkedTrack` (#1858) — the receiver has no independent
+ // `track` subscription to ack through. Stamp a SEPARATE floor
+ // (`trackBundleConfirmed`) tombstoneGc's `track` cutoff reads off
+ // musicVideoProject rows, distinct from `lastConfirmedPushedAt` because the
+ // latter advances even when the bundled track merge failed or was stripped
+ // for a legacy peer (`trackSyncPending`) — using it here would let GC treat
+ // an unconfirmed bundled tombstone as delivered.
+ await persistPushSuccess(sub.id, (missingCount > 0 || reviewSyncPending || outlineSyncPending || trackSyncPending) ? null : hash, {
+ confirmedAtMs: Date.now(),
+ trackBundleConfirmed: sub.recordKind === 'musicVideoProject' && !trackSyncPending,
+ });
if (Number.isFinite(body?.ackedDeletesUpTo) && body.ackedDeletesUpTo > 0) {
await ackDeletesUpTo(sub.peerId, body.ackedDeletesUpTo).catch(() => {});
}
@@ -472,7 +484,7 @@ export async function pushRecordToPeer(sub, options = {}) {
};
}
-async function persistPushSuccess(subId, hash, { confirmedAtMs = Date.now() } = {}) {
+async function persistPushSuccess(subId, hash, { confirmedAtMs = Date.now(), trackBundleConfirmed = false } = {}) {
await withStateLock(async () => {
const state = await readState();
const sub = state.subscriptions.find((s) => s.id === subId);
@@ -488,6 +500,13 @@ async function persistPushSuccess(subId, hash, { confirmedAtMs = Date.now() } =
if (Number.isFinite(confirmedAtMs) && confirmedAtMs > (sub.lastConfirmedPushedAt ?? 0)) {
sub.lastConfirmedPushedAt = confirmedAtMs;
}
+ // #1922: same monotonic-floor treatment, but scoped to confirmed delivery
+ // of a BUNDLED linkedTrack (musicVideoProject subscriptions only — see the
+ // call site). tombstoneGc's `track` cutoff reads this instead of
+ // `lastConfirmedPushedAt` for musicVideoProject rows.
+ if (trackBundleConfirmed && Number.isFinite(confirmedAtMs) && confirmedAtMs > (sub.lastConfirmedTrackBundleAtMs ?? 0)) {
+ sub.lastConfirmedTrackBundleAtMs = confirmedAtMs;
+ }
// A successful push (or even a no-asset-stranded push) clears any prior
// schema-version block — the peer can receive again.
if (sub.blockedBySchema) delete sub.blockedBySchema;
diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.js
index 439ce73c78..34098c2a3a 100644
--- a/server/services/sharing/peerSyncReceive.js
+++ b/server/services/sharing/peerSyncReceive.js
@@ -399,7 +399,12 @@ export async function applyIncomingPush(payload) {
const missingAssets = localEphemeral ? [] : await diffAssetManifestAgainstLocal(assetManifest);
// Compute the deletedAt water-mark we can ack. Use the maximum across the
- // record + its issues (a single push can carry multiple tombstones).
+ // record + its issues + a bundled linkedTrack tombstone (#1858 bundles the
+ // music-video project's linked track; #1922 folds its deletedAt into this
+ // water-mark too — without it, a musicVideoProjects-only peer with no
+ // independent `track` subscription would never ack a bundled track delete
+ // through ANY cursor, so the sender's track-tombstone GC could prune the
+ // tombstone before a transient delivery failure got a chance to retry).
// We return this to the sender so THEY can advance THEIR cursor (which
// tracks what we — the receiver — have acked of THEIR pushes). We do
// NOT call ackDeletesUpTo here: that would write
@@ -411,7 +416,7 @@ export async function applyIncomingPush(payload) {
// seen them — even though peer-A is just telling us about ITS own
// tombstones. In bidirectional sync, that lets peer-A's stale live
// records resurrect after GC drops our tombstones.
- const ackedDeletesUpTo = computeAckedDeletesFromPayload(record, issues);
+ const ackedDeletesUpTo = computeAckedDeletesFromPayload(record, issues, linkedTrack);
// Best-effort reverse subscription. Failures don't fail the push — the
// record is already merged and the response will tell the sender what
@@ -479,7 +484,7 @@ export async function applyIncomingPush(payload) {
};
}
-function computeAckedDeletesFromPayload(record, issues) {
+function computeAckedDeletesFromPayload(record, issues, linkedTrack) {
let max = 0;
const consider = (rec) => {
if (!rec?.deleted || !isStr(rec.deletedAt)) return;
@@ -488,6 +493,7 @@ function computeAckedDeletesFromPayload(record, issues) {
};
consider(record);
if (Array.isArray(issues)) for (const i of issues) consider(i);
+ consider(linkedTrack);
return max;
}
diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.js
index 7a3e8ecc79..03b34abbd4 100644
--- a/server/services/sharing/tombstoneGc.js
+++ b/server/services/sharing/tombstoneGc.js
@@ -24,6 +24,16 @@
* Issues piggyback on the series subscription model — an issue tombstone
* is only pushed alongside its parent series's push, so the relevant ack
* cohort for issue tombstones is "peers subscribed to series".
+ *
+ * Tracks have a similar piggyback case (#1922): a musicVideoProject push
+ * bundles its linked track record (#1858) so a peer subscribed to
+ * musicVideoProjects only — no independent `track` subscription — can still
+ * resolve and render it. Such a peer is invisible to a `track`-subscription-
+ * only ack cohort, so the `track` cutoff also folds in peers subscribed to
+ * `musicVideoProject`, reading their confirmed-delivery floor off the
+ * bundle-specific `lastConfirmedTrackBundleAtMs` (not the generic
+ * `lastConfirmedPushedAt`, which advances even when the bundled track merge
+ * failed). See `TRACK_COHORT_KINDS` / `confirmedFloorForSub` below.
*/
import { pruneTombstonedUniverses, listUniverses } from '../universeBuilder.js';
@@ -135,11 +145,27 @@ function eligiblePeerIdSet(peers) {
);
}
+// #1922: a musicVideoProject subscription is also a delivery vehicle for its
+// linked track's tombstone (#1858 bundles `linkedTrack` on the project push).
+// A peer subscribed to musicVideoProjects only (no `track` subscription of
+// its own) is otherwise INVISIBLE to the `track` cutoff cohort below — so
+// without this, track-tombstone GC never waited on such a peer at all, and
+// could prune the tombstone before a transient bundled-delivery retry landed.
+// Fold musicVideoProject subscribers into the `track` cohort; the precise
+// per-record floor for THEIR rows comes from `lastConfirmedTrackBundleAtMs`
+// (see `confirmedFloorForSub` below), not the generic `lastConfirmedPushedAt`.
+const TRACK_COHORT_KINDS = Object.freeze(['track', 'musicVideoProject']);
+
+function cohortKindsFor(recordKind) {
+ return recordKind === 'track' ? TRACK_COHORT_KINDS : [recordKind];
+}
+
function peerIdsSubscribedToKind(subs, peers, recordKind) {
+ const cohortKinds = cohortKindsFor(recordKind);
const eligible = eligiblePeerIdSet(peers);
return [...new Set(
subs
- .filter((s) => s.recordKind === recordKind)
+ .filter((s) => cohortKinds.includes(s.recordKind))
.map((s) => s.peerId)
.filter((id) => id && eligible.has(id)),
)];
@@ -165,20 +191,40 @@ function peerIdsSubscribedToKind(subs, peers, recordKind) {
// An unparseable `createdAt` (hand-edited / legacy row) floors to 0 — fully
// conservative, never a false prune.
//
+// #1922: which field on a subscription row holds its confirmed-delivery
+// water-mark FOR `targetKind`. Only a musicVideoProject row standing in for
+// the `track` cutoff (i.e. `targetKind === 'track'`) reads the bundle-specific
+// `lastConfirmedTrackBundleAtMs` — its generic `lastConfirmedPushedAt`
+// advances on every successful project push REGARDLESS of whether the
+// bundled track merge succeeded (`trackSyncPending`), so reusing it here
+// would let GC treat an unconfirmed bundled tombstone as delivered. The SAME
+// row's protection of its OWN `musicVideoProject` tombstone (when
+// `targetKind === 'musicVideoProject'`) still reads `lastConfirmedPushedAt`,
+// unchanged. Every other recordKind/targetKind pairing also keeps using
+// `lastConfirmedPushedAt` as before.
+function confirmedFloorForSub(sub, targetKind) {
+ const field = (targetKind === 'track' && sub.recordKind === 'musicVideoProject')
+ ? 'lastConfirmedTrackBundleAtMs'
+ : 'lastConfirmedPushedAt';
+ let confirmed = sub[field];
+ if (!Number.isFinite(confirmed)) {
+ // Never confirmed → floor to createdAt (0 if unparseable). See header.
+ const createdMs = Date.parse(sub.createdAt || '');
+ confirmed = Number.isFinite(createdMs) ? createdMs : 0;
+ }
+ return confirmed;
+}
+
// Returns Infinity when there are no eligible rows for the kind (no per-record
// constraint → the snapshot-coverage + per-peer-ack checks alone govern).
function minConfirmedPushedAtForKind(subs, peers, recordKind) {
+ const cohortKinds = cohortKindsFor(recordKind);
const eligible = eligiblePeerIdSet(peers);
let min = Infinity;
for (const s of subs) {
- if (s.recordKind !== recordKind) continue;
+ if (!cohortKinds.includes(s.recordKind)) continue;
if (!s.peerId || !eligible.has(s.peerId)) continue;
- let confirmed = s.lastConfirmedPushedAt;
- if (!Number.isFinite(confirmed)) {
- // Never confirmed → floor to createdAt (0 if unparseable). See header.
- const createdMs = Date.parse(s.createdAt || '');
- confirmed = Number.isFinite(createdMs) ? createdMs : 0;
- }
+ const confirmed = confirmedFloorForSub(s, recordKind);
if (confirmed < min) min = confirmed;
}
return min;
diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.js
index 501047da6d..2becbd1a2b 100644
--- a/server/services/sharing/tombstoneGc.test.js
+++ b/server/services/sharing/tombstoneGc.test.js
@@ -790,3 +790,110 @@ describe('sweepTombstones — mediaCollection GC (Task 1.10b)', () => {
expect(result.collections).toBe(0);
});
});
+
+describe('sweepTombstones — track GC cohort widened by musicVideoProject bundling (#1922)', () => {
+ // #1858 bundles a music-video project's linked track record on the project
+ // push so a peer subscribed to musicVideoProjects ONLY (no `track`
+ // subscription) can still resolve it. Before #1922, such a peer was
+ // entirely invisible to the `track` cutoff cohort — its ack/confirm never
+ // gated track-tombstone GC at all, so a transient bundled-delivery failure
+ // plus GC pruning the tombstone before a retry could strand stale audio on
+ // that peer forever.
+ it('includes a musicVideoProject-only peer in the track ack cohort (peer has no track subscription)', async () => {
+ mockSubs({ musicVideoProject: [{ peerId: 'peer-a', lastConfirmedTrackBundleAtMs: NOW }] });
+ getPeers.mockResolvedValue([{ instanceId: 'peer-a', enabled: true }]);
+ getMinAckAcrossPeers.mockResolvedValue(NOW - 1000);
+ await sweepTombstones({ now: NOW });
+ // peerIdsSubscribedToKind('track') must include peer-a even though peer-a
+ // has zero `track`-kind subscription rows.
+ const trackAckCall = getMinAckAcrossPeers.mock.calls.find((call) => call[0].includes('peer-a'));
+ expect(trackAckCall).toBeTruthy();
+ });
+
+ it('does NOT prune a track tombstone until the musicVideoProject peer confirms the bundled delivery', async () => {
+ // The per-peer ack cursor (getMinAckAcrossPeers) is already past the
+ // tombstone — mimics #1922's failure mode where the coarse cursor jumped
+ // ahead via an unrelated push. The musicVideoProject row's bundle-specific
+ // floor (lastConfirmedTrackBundleAtMs absent → floors to createdAt) must
+ // still hold the cutoff back.
+ getMinAckAcrossPeers.mockResolvedValue(NOW);
+ getPeers.mockResolvedValue([{ instanceId: 'peer-a', enabled: true }]);
+ const createdAt = NOW - 30 * 60 * 1000;
+ mockSubs({
+ musicVideoProject: [
+ // No lastConfirmedTrackBundleAtMs yet (bundle never confirmed) — floors
+ // to createdAt, NOT the mockSubs lastConfirmedPushedAt default.
+ { peerId: 'peer-a', createdAt: new Date(createdAt).toISOString(), lastConfirmedTrackBundleAtMs: null },
+ ],
+ });
+ await sweepTombstones({ now: NOW, graceMs: 0 });
+ const cutoff = pruneTombstonedTracks.mock.calls[0][0];
+ expect(cutoff).toBe(createdAt + 1);
+ });
+
+ it('prunes a track tombstone once the musicVideoProject peer confirms the bundled track merge', async () => {
+ getMinAckAcrossPeers.mockResolvedValue(NOW);
+ getPeers.mockResolvedValue([{ instanceId: 'peer-a', enabled: true }]);
+ mockSubs({
+ musicVideoProject: [
+ { peerId: 'peer-a', createdAt: new Date(NOW - 60 * 60 * 1000).toISOString(), lastConfirmedTrackBundleAtMs: NOW },
+ ],
+ });
+ await sweepTombstones({ now: NOW, graceMs: 0 });
+ const cutoff = pruneTombstonedTracks.mock.calls[0][0];
+ expect(cutoff).toBe(NOW + 1);
+ });
+
+ it('does NOT release the track cutoff off a musicVideoProject row whose bundled merge never confirmed, even though lastConfirmedPushedAt (the generic field) is fresh', async () => {
+ // Regression for the field-confusion bug: mockSubs defaults
+ // lastConfirmedPushedAt to NOW (every push lands), but that field reflects
+ // confirmed delivery of the PROJECT record, not the bundled TRACK — using
+ // it for the `track` cutoff would let GC treat an unconfirmed bundled
+ // tombstone as delivered.
+ getMinAckAcrossPeers.mockResolvedValue(NOW);
+ getPeers.mockResolvedValue([{ instanceId: 'peer-a', enabled: true }]);
+ const createdAt = NOW - 30 * 60 * 1000;
+ mockSubs({
+ // lastConfirmedPushedAt defaults to NOW via mockSubs; only
+ // lastConfirmedTrackBundleAtMs is left unset here.
+ musicVideoProject: [{ peerId: 'peer-a', createdAt: new Date(createdAt).toISOString() }],
+ });
+ await sweepTombstones({ now: NOW, graceMs: 0 });
+ const cutoff = pruneTombstonedTracks.mock.calls[0][0];
+ expect(cutoff).toBe(createdAt + 1); // floors to createdAt, ignores the fresh lastConfirmedPushedAt
+ });
+
+ it('does NOT widen the musicVideoProject cutoff cohort itself (only `track` borrows musicVideoProject rows)', async () => {
+ // The OWN musicVideoProject cutoff must keep reading lastConfirmedPushedAt
+ // (its own record's confirmed-delivery floor) — confirming this isn't
+ // accidentally redirected to the bundle-specific field too.
+ getMinAckAcrossPeers.mockResolvedValue(NOW);
+ getPeers.mockResolvedValue([{ instanceId: 'peer-a', enabled: true }]);
+ const stuckConfirm = NOW - 40 * 60 * 1000;
+ mockSubs({
+ musicVideoProject: [
+ {
+ peerId: 'peer-a',
+ createdAt: new Date(NOW - 60 * 60 * 1000).toISOString(),
+ lastConfirmedPushedAt: stuckConfirm,
+ lastConfirmedTrackBundleAtMs: NOW, // fresh — must NOT be what gates the project's own cutoff
+ },
+ ],
+ });
+ await sweepTombstones({ now: NOW, graceMs: 0 });
+ const cutoff = pruneTombstonedMusicVideoProjects.mock.calls[0][0];
+ expect(cutoff).toBe(stuckConfirm + 1);
+ });
+
+ it('a peer with only a track subscription (no musicVideoProject) still gates track GC as before', async () => {
+ const minAck = NOW - 10 * 60 * 1000;
+ mockSubs({ track: [{ peerId: 'peer-a', lastConfirmedPushedAt: NOW }] });
+ getPeers.mockResolvedValue([{ instanceId: 'peer-a', enabled: true }]);
+ getMinAckAcrossPeers.mockImplementation(async (peerIds) => {
+ if (peerIds.includes('peer-a')) return minAck;
+ return Infinity;
+ });
+ await sweepTombstones({ now: NOW, graceMs: 0 });
+ expect(pruneTombstonedTracks).toHaveBeenCalledWith(minAck + 1);
+ });
+});