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

add manual tombstone GC trigger so mass-deletes leave disk before the 24h orchestrator sweep

[._.]/ Adam Eivyc3e3ee0f8039
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3b54c7d1fd..cca7237cb9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,6 +1,7 @@
# Unreleased Changes
## Added
+- **Manual tombstone GC trigger.** The 60s `syncOrchestrator` sweep buffers tombstones for 24h to give every peer time to ack a deletion before the bytes leave disk — fine for normal use, painful right after a mass-delete. New `POST /api/sync/tombstones/sweep` (Zod-validated optional `{ graceMs }` clamped to `[0, 24h]`) calls `sweepTombstones({ graceMs })` so callers can shrink the buffer; the per-kind null-cutoff refusal (snapshot-mode peer with no per-record subscription) still fires independently of `graceMs` to preserve resurrection safety. Companion `GET /api/sync/tombstones/status` returns the dry-run refusal status without invoking the prune helpers. A new "GC tombstones now" section on the Instances page (between SelfCard/AddPeer and the peers list) POSTs `graceMs: 0` and surfaces per-kind prune counts + any refusals in a toast; the button is disabled only when every kind is refused. `scripts/gc-tombstones-now.js` is the equivalent CLI path (dry-run by default; `--apply` to prune) for headless cleanups — uses the same "stop the server first, single-process write-tail isn't cross-process safe" wording as `cleanup-test-data.js`. `sweepTombstones` now returns `{ universes, series, issues, refused }` so the manual trigger can explain why a kind didn't shrink. The orchestrator path keeps the 24h default behavior unchanged.
- `server/lib/collectionStore.js` — per-type, per-record JSON storage helper with explicit type-level `schemaVersion` stamping. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `listIds` / `loadAll` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. Per-id write queue means writes to different records run in parallel — the win over a single-file write queue. `verifyCollectionVersions([store, ...])` is called at server boot after `runMigrations()` so a missed migration produces a loud, single-line log per collection (does not crash — PortOS is single-user).
- New layout `data/universes/{id}/index.json` for the universe builder, plus a type-level `data/universes/index.json` carrying `{ schemaVersion: 5, type, updatedAt, config: { runs } }`. Migration 034 (`scripts/migrations/034-split-universe-builder-to-per-uuid.js`) splits the legacy monolithic `data/universe-builder.json` (1.4MB / ~30 universes that previously rewrote in full on every mutation) into per-record files at boot. The legacy file is renamed to `universe-builder.json.bak-034` (not deleted) as a recovery path. Idempotent — partial-completion re-runs finish the split; full-completion re-runs are no-ops.
- **Cross-instance sync now gates on schema version.** New `server/lib/schemaVersions.js` is the single source of truth for the per-category storage-layout contract (`PORTOS_SCHEMA_VERSIONS = { universes: 5 }`); future category bumps add entries. Every outbound sync payload (federated peer push, 60s snapshot sync, share-bucket manifest) carries a `portosMeta { portosVersion, schemaVersions }` envelope. Receivers run `compareSchemaVersions(sender, local)`; when the sender is **ahead** on any category the receiver REJECTS — federated peer push returns 409 + `{ code: PEER_SYNC_SCHEMA_VERSION_AHEAD, context: { details: { ahead, behind, senderPortosVersion, receiverSchemaVersions } } }`, snapshot sync surfaces `blockedBySchema` on the peer record, share-bucket import skips the manifest with reason `portos-schema-ahead` and emits a `sharing:portos-schema-ahead` socket event. Senders persist the gap (`sub.blockedBySchema` on peer subscriptions, `peer.schemaGaps[category]` on peer records via `updatePeer`) and pause retries (5-minute cooldown; `peer:online` reconnect bypasses to re-probe in case the peer upgraded). Legacy senders without `portosMeta` pass through unchanged. The Instances page renders a new `<SchemaGapBadge>` per peer card explaining the gap in both directions: "Peer X is on an older PortOS — they need to update before we can sync universes" / "Peer X is on a newer PortOS — update PortOS to receive their universe updates." A "sender behind" mismatch DOES NOT gate — the existing sanitizer chain backfills older inputs.
diff --git a/PLAN.md b/PLAN.md
index 2cfb7ffef4..d782c7aaea 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -25,7 +25,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
- [ ] [apple-health-integration-live-sync] **Apple Health integration for MeatSpace.** iOS live sync (HealthKit Shortcut → `POST /api/meatspace/apple-health` endpoint) plus a bulk historical import path for an exported `export.xml`. Wire into existing MeatSpace tabs so steps / sleep / heart rate / VO2 max / resting HR show alongside the alcohol / blood / body / epigenetic tracks already shipped. GOALS.md flags this as a documented Secondary Goal ("Apple Health integration planned") but no implementation tracking existed until this entry.
- [ ] [ref-watch-phosphene-mlx-post-decode-os-exit] **Bypass MLX post-decode deallocator hang via `os._exit(0)`.** From `reference-watch` review of phosphene (commits `adc1cd25` + `94bd6965`, 2026-05-22). At PortOS's current `LTX2_PIN=f8f20c83` the bug isn't reachable, but the moment a user updates `ltx-2-mlx` or PortOS bumps the pin past the May 9 refactor, every Distilled / Extend / two-stage render stalls 5–15 min after the upstream "Decoding done in X.Xs" log while Metal command-buffer completion handlers hold the GIL through frame teardown. Fix: in `scripts/generate_ltx2.py` `main()`, after `print(json.dumps(...))`, call `os._exit(0)` instead of returning normally — mp4 is on disk, stdout was flushed, skipping deallocator teardown saves up to 15 min. Document why in the file's docstring. Subsumes any in-helper watchdog approach.
- [ ] [ref-watch-phosphene-broaden-negative-prompt-override] **Broaden `DEFAULT_NEGATIVE_PROMPT` override to every module that defines it.** From `reference-watch` review of phosphene (commit `4e6129b7`, 2026-05-22). `scripts/generate_ltx2.py:55-70` `configure_negative_prompt()` only patches `ti2vid_one_stage.DEFAULT_NEGATIVE_PROMPT`. At PortOS's current pin this happens to cover every pipeline (the constant resolves against `ti2vid_one_stage` for the base class), but post-May-9 the constant moves to `ltx_pipelines_mlx._base` and `utils.constants` — and the PortOS override silently no-ops on Q8 / two-stage / HQ paths with no error for the user to chase. Fix: rewrite `configure_negative_prompt()` to probe `ti2vid_one_stage`, `_base`, and `utils.constants`, monkey-patch every module that has the constant. Keep PortOS's *replace* semantics (don't switch to phosphene's append-with-comma). No contextmanager needed — the helper is short-lived.
-- [ ] [tombstone-gc-manual-trigger-ui] **Wire a manual "GC tombstones now" button on the Instances page.** Today `sharing/tombstoneGc.js#sweepTombstones` only fires from the 60s `syncOrchestrator` interval and uses a hard-coded `GRACE_MS = 24 * 60 * 60 * 1000`, so a user who just mass-deleted records has to wait 24h for them to disappear from `data/universe-builder.json` / `data/pipeline-series.json` / `data/pipeline-issues.json` (even when every subscribed peer has already acked them). Wiring goals: (1) parameterize `sweepTombstones({ now, graceMs })` so callers can override the 24h buffer — keep the 24h default so the orchestrator path is unchanged. (2) Expose `POST /api/sync/tombstones/sweep` with optional `{ graceMs }` body (Zod-validated; clamp to `[0, 24*60*60*1000]` so the button can only shrink the grace, never bypass the ack horizon). The route still calls `cutoffForKind` for each kind so the existing safety checks (peer-ack horizon, refuse-when-snapshot-peer-uncovered) keep firing. (3) Add a "GC tombstones now" button under the Instances page's Sync Status section that POSTs with `graceMs: 0`. Disabled when any enabled peer has snapshot-mode coverage for a kind it isn't subscribed to (mirror the route's null-cutoff refusal). Surfaces the per-kind prune count in a toast (`pruned N universes / M series / K issues` — quiet when zero). (4) One-shot CLI script in `scripts/gc-tombstones-now.js` for headless cleanups (the inline-Node prune we ran 2026-05-23 for the post-Echoes-cleanup batch is the seed). Use `scripts/cleanup-test-data.js`'s pm2-stop-required wording in the header — the prune helpers serialize through per-file write tails that don't cross processes. Surfaced 2026-05-23 during the media-collections sync PR: peer null had acked 82 universe + 192 series tombstones from a same-day mass-delete and the user wanted them off-disk early.
- [ ] [peer-sync-ephemeralize-then-delete-stalls-tombstone] **A previously-shared universe/series that's marked ephemeral, then deleted, never propagates the tombstone when the peer still has other subscriptions of that kind.** Codex iter-8 in v2.7.0 release review (P2). The ephemeralize step's `unsubscribeAllForRecord` removes the per-record sub for that record; the subsequent delete fires `recordEvents.deleted` but there's no sub to push it. The snapshot path in `syncOrchestrator.categoriesCoveredByPeerSync` then suppresses the whole-category snapshot for that peer (because ANY other per-record sub for that kind exists), so the tombstone has no fallback transport either. The peer keeps the old live copy indefinitely. Same root cause as `[peer-sync-snapshot-skip-too-coarse-for-partial-subscriptions]` — the snapshot-skip fix needs to either send the snapshot with subscribed records excluded (so tombstones for unsubscribed-but-previously-known records can still ride it), or detect the ephemeralize-then-delete sequence and proactively push the tombstone before tearing down the sub.
- [ ] [peer-sync-per-record-tombstone-ack-cursor] **Tombstone ack cursor is per-peer but should be per-(peer,record).** Codex iter-6 in v2.7.0 release review (P2). Today `ackDeletesUpTo(peerId, deletedAt)` writes a single high-water-mark per peer. If push for record-A fails and a later push for record-B succeeds, the receiver returns `ackedDeletesUpTo = B.deletedAt > A.deletedAt`; the sender then advances the cursor past A's deletedAt even though A was never confirmed delivered. After grace, `tombstoneGc` treats A as acked, prunes it, and A's stale live copy on the receiver resurrects on the next sync that lands. Fix options: (a) per-`(peer, kind, recordId)` cursor (storage proliferation; needs cleanup on record GC); (b) per-(peer, kind) cursor advanced only when the push response cumulatively confirms every-tombstone-up-to-that-deletedAt was delivered (requires receiver to track-and-respond with "I have all your tombstones up to T"); (c) keep current cursor but also persist a per-record `lastConfirmedPushedAt` on each subscription row, and let GC's `cutoffForKind` use `min(min-of-lastConfirmedPushedAt-across-all-records-of-this-kind)`. Option (c) is the smallest behavioral change. Defer because under the dominant single-writer/single-reader pattern in PortOS, push failures are rare and re-tried on the next event tick.
- [ ] [peer-sync-medialightbox-use-mediaimage-for-syncing-assets] **`MediaLightbox.jsx` uses a raw `<img src=...>` for the main media element — peer-synced images that haven't been pulled yet show a broken image and don't get the `peerSync:asset-arrived` placeholder/live-swap.** Codex iter-6 in v2.7.0 release review (P2). The `MediaImage` component was added specifically to handle this, but only thumbnail/card paths use it. Replace the lightbox's `<img>` with `MediaImage` so opening an image during the sync window shows the "Syncing" placeholder and atomically swaps to bytes when they land. Cross-check every `<img>` in `MediaPreview.jsx`, `MediaCollectionDetail.jsx`, `UniverseBuilder.jsx` for the same gap. Defer because the lightbox is reached after the user clicks a thumbnail — by then the thumbnail's MediaImage has likely already swapped to live bytes, so the lightbox typically sees the same.
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 946386c716..5356029a61 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -15,12 +15,20 @@ import {
getInstances, updateSelfInstance, addPeer, updatePeer,
removePeer, connectPeer, probePeer, getTailnetInfo, provisionTailnetCert,
listPeerSubscriptions, unsubscribeFromPeer,
+ getTombstoneSweepStatus, sweepTombstonesNow,
} from '../services/api';
import PeerAppsList from '../components/instances/PeerAppsList';
import PeerAgentsSection from '../components/instances/PeerAgentsSection';
import { SchemaGapBadge } from '../components/instances/SchemaGapBadge';
import { timeAgo } from '../utils/formatters';
import { useLocalStorageBool } from '../hooks/useLocalStorageBool';
+import { useAsyncAction } from '../hooks/useAsyncAction';
+
+// Plural labels for tombstone record kinds — shared between the in-page
+// TombstoneGcSection toast and `scripts/gc-tombstones-now.js` (the CLI
+// echoes the same wording). The dedupe in the rendering call sites handles
+// the series/issue cohort coupling.
+const TOMBSTONE_KIND_PLURAL = { universe: 'universes', series: 'series', issue: 'issues' };
const STATUS_COLORS = {
online: 'text-port-success',
@@ -1018,6 +1026,75 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {
);
}
+// Manual "GC tombstones now" trigger. The 60s orchestrator sweep keeps its
+// 24h grace — this button passes graceMs:0 so a user who just mass-deleted
+// doesn't wait a day for the bytes to leave disk. The button disables only
+// when every cohort is refused (snapshot-mode peer with no per-record sub
+// in both `universe` and `pipeline`): partial progress is still useful.
+function TombstoneGcSection() {
+ const [refused, setRefused] = useState(null); // null = still loading
+
+ useEffect(() => {
+ let cancelled = false;
+ getTombstoneSweepStatus({ silent: true })
+ .then((r) => { if (!cancelled && Array.isArray(r?.refused)) setRefused(r.refused); })
+ .catch(() => { if (!cancelled) setRefused([]); });
+ return () => { cancelled = true; };
+ }, []);
+
+ const [runSweep, sweeping] = useAsyncAction(async () => {
+ const result = await sweepTombstonesNow({ graceMs: 0 }, { silent: true });
+ if (!result) return null;
+ const { universes = 0, series = 0, issues = 0, refused: refusedKinds = [] } = result;
+ const totalPruned = universes + series + issues;
+ if (totalPruned > 0) {
+ const parts = [];
+ if (universes) parts.push(`${universes} universe${universes === 1 ? '' : 's'}`);
+ if (series) parts.push(`${series} series`);
+ if (issues) parts.push(`${issues} issue${issues === 1 ? '' : 's'}`);
+ toast.success(`Pruned ${parts.join(' / ')}`);
+ } else if (refusedKinds.length === 0) {
+ toast('No tombstones eligible for pruning');
+ }
+ if (refusedKinds.length > 0) {
+ const refusedLabel = [...new Set(refusedKinds.map((k) => TOMBSTONE_KIND_PLURAL[k] ?? k))].join(', ');
+ toast.warning(`Refused: ${refusedLabel} — a snapshot-mode peer has no per-record subscription for this kind. Resolve to enable pruning.`);
+ }
+ setRefused(refusedKinds);
+ return result;
+ }, { errorMessage: 'Tombstone sweep failed' });
+
+ // Every cohort refused iff both `universe` (its own cohort) and `series`
+ // (the pipeline cohort representative — issues always travel with series)
+ // are in the refused set.
+ const allRefused = refused != null && refused.includes('universe') && refused.includes('series');
+ const disabled = sweeping || refused == null || allRefused;
+ const title = allRefused
+ ? 'Every kind has an enabled snapshot-mode peer with no per-record subscription — pruning would risk resurrection. Subscribe the peer or disable it to enable GC.'
+ : 'Prune tombstones acked by every subscribed peer (skips the 24h grace).';
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-xl p-4 flex items-center justify-between gap-3">
+ <div className="flex items-center gap-2 text-sm text-gray-300">
+ <Trash2 size={14} className="text-gray-500" />
+ <span className="text-gray-400 uppercase tracking-wider text-xs font-medium">Tombstone GC</span>
+ <span className="text-gray-500 text-xs">
+ Run on demand instead of waiting for the 24h orchestrator sweep.
+ </span>
+ </div>
+ <button
+ onClick={runSweep}
+ disabled={disabled}
+ title={title}
+ className="bg-port-accent hover:bg-port-accent/80 disabled:opacity-40 disabled:cursor-not-allowed text-white px-3 py-1.5 rounded text-xs font-medium transition-colors flex items-center gap-1.5"
+ >
+ <Trash2 size={12} />
+ {sweeping ? 'Pruning…' : 'GC tombstones now'}
+ </button>
+ </div>
+ );
+}
+
export default function Instances() {
const [self, setSelf] = useState(null);
const [peers, setPeers] = useState([]);
@@ -1084,6 +1161,8 @@ export default function Instances() {
<AddPeerForm onAdd={fetchData} />
</div>
+ <TombstoneGcSection />
+
{peers.length > 0 && (
<div>
<h2 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-3">
diff --git a/client/src/services/apiPeerSync.js b/client/src/services/apiPeerSync.js
index 423ed783a4..cbda541c1c 100644
--- a/client/src/services/apiPeerSync.js
+++ b/client/src/services/apiPeerSync.js
@@ -39,3 +39,17 @@ export const unsubscribeFromPeer = (subscriptionId, options) =>
method: 'DELETE',
...options,
});
+
+// Tombstone GC manual-trigger endpoints. The ack horizon used to decide
+// what's safe to prune comes from the per-record subscription cursors that
+// the rest of this file already manages — hence the colocation.
+
+export const getTombstoneSweepStatus = (options) =>
+ request('/sync/tombstones/status', options);
+
+export const sweepTombstonesNow = ({ graceMs } = {}, options) =>
+ request('/sync/tombstones/sweep', {
+ method: 'POST',
+ body: JSON.stringify(graceMs !== undefined ? { graceMs } : {}),
+ ...options,
+ });
diff --git a/scripts/gc-tombstones-now.js b/scripts/gc-tombstones-now.js
new file mode 100644
index 0000000000..bdc3e29685
--- /dev/null
+++ b/scripts/gc-tombstones-now.js
@@ -0,0 +1,82 @@
+/**
+ * One-shot tombstone garbage collection.
+ *
+ * Drives `sweepTombstones({ graceMs: 0 })` from a CLI so a headless cleanup
+ * (post-mass-delete, scripted reset, server-stopped maintenance window) can
+ * shrink `data/universe-builder.json` + `data/pipeline-series.json` +
+ * `data/pipeline-issues.json` immediately rather than waiting up to 24h for
+ * the orchestrator's next scheduled sweep.
+ *
+ * The existing per-kind safety still fires: a snapshot-mode peer that's
+ * enabled for `universe` / `pipeline` without a per-record subscription will
+ * cause that kind's cutoff to come back null and the prune to be skipped
+ * (the resurrection-safety check is independent of graceMs).
+ *
+ * IMPORTANT — STOP THE SERVER BEFORE RUNNING. This script invokes the
+ * service-layer prune helpers in a SEPARATE Node process from any running
+ * portos-server. The service-layer write tails (per-file `writeState`
+ * queues) are in-process — they do NOT serialize across processes, so a
+ * concurrent `portos-server` write can clobber this script's prune
+ * (last-writer-wins on the JSON file). Always:
+ *
+ * pm2 stop portos-server # 1. stop the server
+ * node scripts/gc-tombstones-now.js # dry-run first (no --apply)
+ * node scripts/gc-tombstones-now.js --apply
+ * pm2 start portos-server # 2. restart
+ *
+ * Seed for this script: the 2026-05-23 inline-Node prune we ran for the
+ * post-Echoes-cleanup batch (82 universe + 192 series tombstones acked by
+ * peer null from a same-day mass-delete that the user wanted off disk early).
+ */
+import { sweepTombstones, getSweepStatus } from '../server/services/sharing/tombstoneGc.js';
+
+// Mirrors `TOMBSTONE_KIND_PLURAL` in the Instances UI so the CLI output
+// matches the toast wording. Dedupe handles the series/issue cohort.
+const KIND_PLURAL = { universe: 'universes', series: 'series', issue: 'issues' };
+const labelKinds = (kinds) => [...new Set(kinds.map((k) => KIND_PLURAL[k] ?? k))].join(', ');
+
+function parseArgs(argv) {
+ const out = { apply: false };
+ for (const arg of argv.slice(2)) {
+ if (arg === '--apply') out.apply = true;
+ }
+ return out;
+}
+
+async function main() {
+ const { apply } = parseArgs(process.argv);
+ if (!apply) {
+ console.log('🧪 DRY-RUN — pass --apply to actually prune tombstones\n');
+ } else {
+ console.log('⚠️ --apply: STOP the server before continuing or prunes may be clobbered');
+ console.log('⚠️ Run `pm2 stop portos-server` first, then `pm2 start portos-server` after\n');
+ }
+
+ // Dry-run path: report the refusal status only. The prune counts depend
+ // on iterating tombstone records (which means reading the same JSON files
+ // the actual prune would write to) so we deliberately don't preview them
+ // — too easy to misread "would prune N" as "did prune N".
+ const status = await getSweepStatus();
+ if (status.refused.length > 0) {
+ console.log(`⚠️ Refused kinds: ${labelKinds(status.refused)}`);
+ console.log(' (a snapshot-mode peer has no per-record subscription for this kind — resurrection risk)');
+ } else {
+ console.log('✅ No refusals — every kind has an ack horizon');
+ }
+
+ if (!apply) {
+ console.log('\n🧪 DRY-RUN complete — re-run with --apply to prune');
+ return;
+ }
+
+ const result = await sweepTombstones({ graceMs: 0 });
+ console.log(`\n🗑️ Pruned: ${result.universes} universe(s), ${result.series} series, ${result.issues} issue(s)`);
+ if (result.refused.length > 0) {
+ console.log(`⚠️ Skipped: ${labelKinds(result.refused)} (resurrection-safety refusal)`);
+ }
+}
+
+main().catch((err) => {
+ console.error(`❌ gc-tombstones-now failed: ${err.message}`);
+ process.exit(1);
+});
diff --git a/server/routes/dataSync.js b/server/routes/dataSync.js
index be27f5ca9a..1d369b7f3b 100644
--- a/server/routes/dataSync.js
+++ b/server/routes/dataSync.js
@@ -8,12 +8,39 @@
import { Router } from 'express';
import { z } from 'zod';
import * as dataSync from '../services/dataSync.js';
+import { sweepTombstones, getSweepStatus, TOMBSTONE_GRACE_MS } from '../services/sharing/tombstoneGc.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
const router = Router();
const categoryParam = z.enum(['goals', 'character', 'digitalTwin', 'meatspace', 'universe', 'pipeline', 'mediaCollections']);
+// Tombstone GC manual trigger. Declared BEFORE `/:category/*` so the literal
+// "tombstones" segment wins Express's first-match lookup (categoryParam's
+// Zod enum would otherwise 400 before our handler runs). graceMs is clamped
+// to [0, 24h] — the trigger can only SHRINK the grace, never bypass the ack
+// horizon; the per-kind null-cutoff refusal still fires regardless.
+const tombstoneSweepBodySchema = z.object({
+ graceMs: z.number().int().min(0).max(TOMBSTONE_GRACE_MS).optional(),
+}).strict();
+
+router.get('/tombstones/status', asyncHandler(async (req, res) => {
+ const status = await getSweepStatus();
+ res.json(status);
+}));
+
+router.post('/tombstones/sweep', asyncHandler(async (req, res) => {
+ const parsed = tombstoneSweepBodySchema.safeParse(req.body || {});
+ if (!parsed.success) {
+ throw new ServerError(
+ `Validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`,
+ { status: 400, code: 'VALIDATION_ERROR' },
+ );
+ }
+ const result = await sweepTombstones(parsed.data);
+ res.json(result);
+}));
+
// GET /api/sync/:category/checksum — return checksum only (lightweight)
router.get('/:category/checksum', asyncHandler(async (req, res) => {
const category = categoryParam.parse(req.params.category);
diff --git a/server/routes/dataSync.test.js b/server/routes/dataSync.test.js
new file mode 100644
index 0000000000..f602a669e1
--- /dev/null
+++ b/server/routes/dataSync.test.js
@@ -0,0 +1,89 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+// Only the tombstone-sweep helpers are exercised here — the snapshot-sync
+// routes have their own coverage via `dataSync` service tests + the
+// peer-sync integration tests.
+vi.mock('../services/sharing/tombstoneGc.js', () => ({
+ sweepTombstones: vi.fn(),
+ getSweepStatus: vi.fn(),
+ TOMBSTONE_GRACE_MS: 24 * 60 * 60 * 1000,
+}));
+vi.mock('../services/dataSync.js', () => ({
+ getChecksum: vi.fn(),
+ getSnapshot: vi.fn(),
+ applyRemote: vi.fn(),
+ getSupportedCategories: vi.fn(() => []),
+}));
+
+import { sweepTombstones, getSweepStatus } from '../services/sharing/tombstoneGc.js';
+import dataSyncRoutes from './dataSync.js';
+
+const buildApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/sync', dataSyncRoutes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+describe('GET /api/sync/tombstones/status', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('proxies the dry-run status straight through', async () => {
+ getSweepStatus.mockResolvedValue({ refused: ['universe'] });
+ const res = await request(buildApp()).get('/api/sync/tombstones/status');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ refused: ['universe'] });
+ expect(getSweepStatus).toHaveBeenCalledOnce();
+ });
+
+ it("wins the lookup against /:category/* (literal 'tombstones' is not a category)", async () => {
+ // Regression: if the tombstone routes were declared AFTER `/:category/*`,
+ // Express would try to parse "tombstones" as a category and the Zod
+ // enum check would 400 before our handler runs.
+ getSweepStatus.mockResolvedValue({ refused: [] });
+ const res = await request(buildApp()).get('/api/sync/tombstones/status');
+ expect(res.status).toBe(200);
+ });
+});
+
+describe('POST /api/sync/tombstones/sweep', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('returns the per-kind prune counts + refused list with no body (default graceMs)', async () => {
+ sweepTombstones.mockResolvedValue({ universes: 3, series: 1, issues: 7, refused: [] });
+ const res = await request(buildApp()).post('/api/sync/tombstones/sweep').send({});
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ universes: 3, series: 1, issues: 7, refused: [] });
+ expect(sweepTombstones).toHaveBeenCalledWith({});
+ });
+
+ it('forwards graceMs:0 to the service so the UI button can skip the 24h buffer', async () => {
+ sweepTombstones.mockResolvedValue({ universes: 0, series: 0, issues: 0, refused: [] });
+ const res = await request(buildApp()).post('/api/sync/tombstones/sweep').send({ graceMs: 0 });
+ expect(res.status).toBe(200);
+ expect(sweepTombstones).toHaveBeenCalledWith({ graceMs: 0 });
+ });
+
+ it('rejects graceMs > 24h so the manual trigger can only SHRINK the grace', async () => {
+ const tooBig = 25 * 60 * 60 * 1000;
+ const res = await request(buildApp()).post('/api/sync/tombstones/sweep').send({ graceMs: tooBig });
+ expect(res.status).toBe(400);
+ expect(sweepTombstones).not.toHaveBeenCalled();
+ });
+
+ it('rejects negative graceMs', async () => {
+ const res = await request(buildApp()).post('/api/sync/tombstones/sweep').send({ graceMs: -1 });
+ expect(res.status).toBe(400);
+ expect(sweepTombstones).not.toHaveBeenCalled();
+ });
+
+ it('rejects unknown fields (strict schema — prevents typos like graceMS from silently no-op-ing)', async () => {
+ const res = await request(buildApp()).post('/api/sync/tombstones/sweep').send({ graceMS: 0 });
+ expect(res.status).toBe(400);
+ expect(sweepTombstones).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.js
index 1d7124194e..19300f7c3b 100644
--- a/server/services/sharing/tombstoneGc.js
+++ b/server/services/sharing/tombstoneGc.js
@@ -12,9 +12,10 @@
* 1. Every peer currently subscribed to the record's kind has acked a
* deletedAt at least as recent as the tombstone (so we know every
* subscriber has received and applied this specific deletion).
- * 2. At least GRACE_MS has elapsed since the tombstone was created — a
+ * 2. At least `graceMs` has elapsed since the tombstone was created — a
* buffer for transient replay / disconnect cases that haven't shown
- * up in the ack water-mark yet.
+ * up in the ack water-mark yet. The orchestrator path uses the 24h
+ * default; the manual-trigger UI / CLI passes `graceMs: 0`.
*
* When a record's kind has NO subscribed peers, condition (1) is trivially
* satisfied (`getMinAckAcrossPeers([])` returns Infinity), so the sweep
@@ -23,10 +24,6 @@
* 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".
- *
- * Wired into the syncOrchestrator interval; runs once per cycle (~60s)
- * since the math is cheap (read 3 small JSONs + cursor map) and prunes
- * in place when there's anything to drop.
*/
import { pruneTombstonedUniverses } from '../universeBuilder.js';
@@ -36,78 +33,48 @@ import { listPeerSubscriptions } from './peerSync.js';
import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';
import { getPeers } from '../instances.js';
-const GRACE_MS = 24 * 60 * 60 * 1000; // 24h grace
+const GRACE_MS = 24 * 60 * 60 * 1000;
-/**
- * Resolve the set of peer ids currently subscribed to a given record kind.
- * The result feeds `getMinAckAcrossPeers` to compute the GC water-mark.
- *
- * Returns an array of unique instance ids; an empty array means "no
- * subscribers — fall back to time-only grace."
- */
-async function peerIdsSubscribedToKind(recordKind) {
- const subs = await listPeerSubscriptions({ recordKind });
- // Filter against the live peer registry — but only against peers
- // ELIGIBLE TO SYNC. Three filters in lockstep with snapshotPeerIdsForKind:
- // (1) Live in the registry — peer_subscriptions.json rows outlive peer
- // removal (no cleanup hook on instance delete), so an unfiltered
- // removed peer would freeze the cursor at its last ack (often 0)
- // and refuse to prune.
- // (2) p.enabled — disabled peers receive no pushes; their cursor
- // never advances and would otherwise stall GC.
- // (3) p.syncEnabled !== false — globally-silenced peers same as (2).
- // Without (2) and (3), a per-record subscription belonging to a
- // disabled/silenced peer would treat it as an active blocker even
- // though it can't move.
- const eligiblePeerIds = new Set(
- (await getPeers().catch(() => []))
+// `peer_subscriptions.json` rows outlive peer removal (no cleanup hook on
+// instance delete), and disabled / globally-silenced peers never advance
+// their ack cursor. Filtering against this set keeps a stale sub from
+// freezing the GC water-mark at peer-removal time.
+function eligiblePeerIdSet(peers) {
+ return new Set(
+ peers
.filter((p) => p?.enabled && p.syncEnabled !== false)
.map((p) => p.instanceId)
.filter(Boolean),
);
- return [...new Set(subs.map((s) => s.peerId).filter((id) => id && eligiblePeerIds.has(id)))];
}
-/**
- * Map a record kind to the snapshot-sync category that ships it on the wire.
- * Universe records ride the 'universe' snapshot category; series + issues
- * both ride the 'pipeline' snapshot category (which bundles them together
- * — see `dataSync.getPipelineSnapshot`).
- */
+function peerIdsSubscribedToKind(subs, peers, recordKind) {
+ const eligible = eligiblePeerIdSet(peers);
+ return [...new Set(
+ subs
+ .filter((s) => s.recordKind === recordKind)
+ .map((s) => s.peerId)
+ .filter((id) => id && eligible.has(id)),
+ )];
+}
+
function snapshotCategoryForKind(recordKind) {
if (recordKind === 'universe') return 'universe';
if (recordKind === 'series' || recordKind === 'issue') return 'pipeline';
return null;
}
-/**
- * Returns the set of enabled peer instance-ids that can still send us a
- * snapshot of this record kind via the 60s snapshot loop in `dataSync.js`.
- *
- * The snapshot path has NO per-peer ack water-mark — peerTombstoneCursors
- * only tracks acks from the per-record push pipeline. So for every peer in
- * this set that's NOT also covered by a per-record subscription, we have
- * zero proof they've received any deletion we want to prune. An offline
- * peer with an older LIVE copy could come back, push its snapshot, and
- * `merge*FromSync` would INSERT the resurrected record (the merge path
- * inserts records the local file is missing).
- *
- * Legacy peers without an explicit `syncCategories` map fall back to
- * brain+memory only (see syncOrchestrator.getEffectiveCategories), so
- * they can't send universe/pipeline snapshots — excluded from the set.
- */
-async function snapshotPeerIdsForKind(recordKind) {
+// Peers that can resurrect a pruned tombstone via the 60s snapshot loop.
+// The snapshot path has no per-peer ack water-mark, so any peer in this set
+// that's NOT also covered by a per-record subscription makes pruning unsafe.
+// Legacy peers without `syncCategories` fall back to brain+memory only
+// (syncOrchestrator.getEffectiveCategories), so they're excluded.
+function snapshotPeerIdsForKind(peers, recordKind) {
const category = snapshotCategoryForKind(recordKind);
if (!category) return [];
- const peers = await getPeers().catch(() => []);
return peers
.filter((p) => {
if (!p?.enabled) return false;
- // Mirror syncOrchestrator's syncAllPeers gate — a globally-silenced
- // peer (syncEnabled === false) never receives snapshots, so it can't
- // resurrect a pruned tombstone. Without this filter, a silenced peer's
- // stale syncCategories map permanently stalls GC by reporting "snapshot
- // peer not covered by per-record sub" → cutoff = null → refuse to prune.
if (p.syncEnabled === false) return false;
const cats = p.syncCategories;
return !!cats && typeof cats === 'object' && cats[category] === true;
@@ -116,61 +83,57 @@ async function snapshotPeerIdsForKind(recordKind) {
.filter(Boolean);
}
-/**
- * Compute the cutoff timestamp: tombstones with `deletedAt < cutoff` are
- * safe to prune. The cutoff is the EARLIER of "now - grace" and
- * "minAck - grace" — i.e. we subtract the grace buffer from whichever
- * water-mark is lower, so we never prune past the laggiest peer's ack.
- *
- * Returns `null` to mean "refuse to prune" — used when ANY snapshot-mode
- * peer for this kind is NOT covered by a per-record subscription. The
- * snapshot path has no ack water-mark, so an uncovered snapshot peer
- * can resurrect a pruned tombstone on its next snapshot push. This
- * applies BOTH to "no per-record subs at all" AND to "mixed deployment
- * where peer-A has per-record subs but peer-B is snapshot-only" — both
- * cases leave at least one peer un-acked, so both must refuse.
- *
- * Otherwise: subtract grace from `min(now, minAckedAcrossPeers)`. The
- * `Math.min` collapses the two safe branches into one formula:
- * - no peers at all (no subs, no snapshot peers) → minAck=Infinity →
- * cutoff = now - grace
- * - every snapshot peer also has a per-record sub → minAck < now →
- * cutoff = minAck - grace
- *
- * @returns {number|null} the cutoff ms-epoch (or null to refuse).
- */
-async function cutoffForKind(recordKind, { now = Date.now() } = {}) {
- const peerIds = await peerIdsSubscribedToKind(recordKind);
- const snapshotPeerIds = await snapshotPeerIdsForKind(recordKind);
- // Snapshot-mode peers NOT covered by per-record subscriptions have no
- // ack horizon — refuse to prune until every snapshot peer is covered
- // OR they're disabled (the filter in snapshotPeerIdsForKind drops them).
+// Returns null when ANY snapshot-mode peer for this kind isn't covered by
+// a per-record subscription — without an ack horizon, an offline peer could
+// resurrect a pruned tombstone via its next snapshot push. Otherwise the
+// cutoff is `min(now, minAck) - graceMs`.
+async function cutoffForKind(recordKind, { peers, subs, now, graceMs }) {
+ const peerIds = peerIdsSubscribedToKind(subs, peers, recordKind);
+ const snapshotPeerIds = snapshotPeerIdsForKind(peers, recordKind);
const subbed = new Set(peerIds);
- const uncovered = snapshotPeerIds.filter((id) => !subbed.has(id));
- if (uncovered.length > 0) return null;
+ if (snapshotPeerIds.some((id) => !subbed.has(id))) return null;
const minAck = await getMinAckAcrossPeers(peerIds);
- const threshold = Math.min(minAck, now);
- return threshold - GRACE_MS;
+ return Math.min(minAck, now) - graceMs;
+}
+
+// Single point of disk I/O for peer registry + subscription rows. Both
+// `sweepTombstones` and `getSweepStatus` read these once and thread them
+// through the pure helpers, so the orchestrator's 60s loop hits the file
+// system twice per cycle instead of six times.
+async function loadState() {
+ const [peers, subs] = await Promise.all([
+ getPeers().catch(() => []),
+ listPeerSubscriptions(),
+ ]);
+ return { peers, subs };
+}
+
+function refusedFromCutoffs(universeCutoff, seriesCutoff) {
+ const refused = [];
+ if (universeCutoff === null) refused.push('universe');
+ // Issue tombstones ride series pushes — refused exactly when series is.
+ if (seriesCutoff === null) {
+ refused.push('series');
+ refused.push('issue');
+ }
+ return refused;
}
/**
- * One sweep cycle. Runs all three kinds in parallel — each prune call is
- * already serialized through its own service's write queue, so concurrent
- * kicks don't race local writers.
+ * One sweep cycle. Returns `{ universes, series, issues, refused }`.
*
- * Returns `{ universes, series, issues }` with the prune count per kind so
- * the orchestrator can log a single-line summary on non-zero cycles and
- * stay quiet otherwise.
+ * `graceMs` defaults to 24h so the orchestrator path is unchanged; the
+ * manual-trigger UI / CLI passes 0 to skip the post-delete buffer. The
+ * per-kind null-cutoff refusal (snapshot-mode peer with no per-record sub)
+ * fires independently of graceMs — `refused` lists kinds we couldn't touch.
*/
-export async function sweepTombstones({ now = Date.now() } = {}) {
+export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } = {}) {
+ const { peers, subs } = await loadState();
const [universeCutoff, seriesCutoff] = await Promise.all([
- cutoffForKind('universe', { now }),
- cutoffForKind('series', { now }),
+ cutoffForKind('universe', { peers, subs, now, graceMs }),
+ cutoffForKind('series', { peers, subs, now, graceMs }),
]);
- // Issue tombstones ride series pushes — same ack cohort, same cutoff.
const issueCutoff = seriesCutoff;
- // Skip the prune entirely when cutoff is null (snapshot-mode peer exists
- // for the kind, no ack horizon → refuse to prune to avoid resurrection).
const [u, s, i] = await Promise.all([
universeCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedUniverses(universeCutoff),
seriesCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedSeries(seriesCutoff),
@@ -180,9 +143,20 @@ export async function sweepTombstones({ now = Date.now() } = {}) {
universes: u.pruned,
series: s.pruned,
issues: i.pruned,
+ refused: refusedFromCutoffs(universeCutoff, seriesCutoff),
};
}
-// Constants exported for tests; module-level so future tuning doesn't
-// require a code search to find the magic number.
+// Dry-run companion to `sweepTombstones` — returns the refused kinds
+// without pruning. Refusal is independent of graceMs (only snapshot
+// coverage matters), so this hardcodes graceMs:0 internally.
+export async function getSweepStatus({ now = Date.now() } = {}) {
+ const { peers, subs } = await loadState();
+ const [universeCutoff, seriesCutoff] = await Promise.all([
+ cutoffForKind('universe', { peers, subs, now, graceMs: 0 }),
+ cutoffForKind('series', { peers, subs, now, graceMs: 0 }),
+ ]);
+ return { refused: refusedFromCutoffs(universeCutoff, seriesCutoff) };
+}
+
export const TOMBSTONE_GRACE_MS = GRACE_MS;
diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.js
index e2b6efdf64..5e81405c10 100644
--- a/server/services/sharing/tombstoneGc.test.js
+++ b/server/services/sharing/tombstoneGc.test.js
@@ -25,6 +25,7 @@ vi.mock('../instances.js', () => ({
import {
sweepTombstones,
+ getSweepStatus,
TOMBSTONE_GRACE_MS,
} from './tombstoneGc.js';
import { pruneTombstonedUniverses } from '../universeBuilder.js';
@@ -36,14 +37,22 @@ import { getPeers } from '../instances.js';
const NOW = 1_700_000_000_000; // arbitrary epoch ms anchor
+// Helper: tombstoneGc now reads subscriptions ONCE per sweep without a
+// per-kind filter, so tests should hand the full sub list with each row
+// carrying its own `recordKind` tag. The previous per-kind mock shape
+// (`mockImplementation(({ recordKind }) => ...)`) is replaced by this.
+const mockSubs = (subsByKind) => {
+ const rows = [];
+ for (const [recordKind, peers] of Object.entries(subsByKind)) {
+ for (const p of peers) rows.push({ ...p, recordKind });
+ }
+ listPeerSubscriptions.mockResolvedValue(rows);
+};
+
beforeEach(() => {
vi.clearAllMocks();
- // Default: no peer subscriptions (empty array → getMinAckAcrossPeers
- // returns Infinity in the real implementation; mirror that here).
listPeerSubscriptions.mockResolvedValue([]);
getMinAckAcrossPeers.mockResolvedValue(Infinity);
- // Default: no snapshot-mode peers either — clears the resurrection-safety
- // gate so the cutoff defaults to `now - GRACE`.
getPeers.mockResolvedValue([]);
});
@@ -70,10 +79,7 @@ describe('sweepTombstones — peers behind', () => {
// subsequent push from that peer would resurrect the record under its
// older `updatedAt`.
const minAck = NOW - 48 * 60 * 60 * 1000; // 48h behind now
- listPeerSubscriptions.mockImplementation(async ({ recordKind }) => {
- if (recordKind === 'universe') return [{ peerId: 'peer-a' }];
- return [];
- });
+ mockSubs({ universe: [{ peerId: 'peer-a' }] });
// peerIdsSubscribedToKind now filters against live peers (removed-peer
// subscriptions otherwise stall GC forever). Register peer-a so the
// sub passes the registry filter.
@@ -95,10 +101,7 @@ describe('sweepTombstones — peers behind', () => {
// subscribable) — but issues need to wait for series-subscribed peers
// to ack their parent series's push.
const seriesAck = NOW - 72 * 60 * 60 * 1000;
- listPeerSubscriptions.mockImplementation(async ({ recordKind }) => {
- if (recordKind === 'series') return [{ peerId: 'peer-a' }];
- return [];
- });
+ mockSubs({ series: [{ peerId: 'peer-a' }] });
getPeers.mockResolvedValue([{ instanceId: 'peer-a', enabled: true }]);
getMinAckAcrossPeers.mockImplementation(async (peerIds) => {
if (peerIds.includes('peer-a')) return seriesAck;
@@ -117,10 +120,8 @@ describe('sweepTombstones — peers behind', () => {
// not move into the future — otherwise we'd prune tombstones the
// local user just created.
const ahead = NOW + 24 * 60 * 60 * 1000;
- listPeerSubscriptions.mockImplementation(async ({ recordKind }) => {
- if (recordKind === 'universe') return [{ peerId: 'peer-a' }];
- return [];
- });
+ mockSubs({ universe: [{ peerId: 'peer-a' }] });
+ getPeers.mockResolvedValue([{ instanceId: 'peer-a', enabled: true }]);
getMinAckAcrossPeers.mockImplementation(async () => ahead);
await sweepTombstones({ now: NOW });
expect(pruneTombstonedUniverses).toHaveBeenCalledWith(NOW - TOMBSTONE_GRACE_MS);
@@ -130,15 +131,12 @@ describe('sweepTombstones — peers behind', () => {
// Subscriptions are per-record, so one peer can appear in many sub
// rows. Pass the deduped set to the cursor query — otherwise a peer
// subscribed to 50 universes would over-count itself.
- listPeerSubscriptions.mockImplementation(async ({ recordKind }) => {
- if (recordKind === 'universe') {
- return [
- { peerId: 'peer-a' },
- { peerId: 'peer-a' }, // same peer, different record
- { peerId: 'peer-b' },
- ];
- }
- return [];
+ mockSubs({
+ universe: [
+ { peerId: 'peer-a' },
+ { peerId: 'peer-a' }, // same peer, different record
+ { peerId: 'peer-b' },
+ ],
});
getPeers.mockResolvedValue([
{ instanceId: 'peer-a', enabled: true },
@@ -161,10 +159,7 @@ describe('sweepTombstones — peers behind', () => {
// frozen-at-removal ack (often 0), and the cutoff would clamp to
// `0 - GRACE` — refusing to prune any tombstone for this kind
// indefinitely.
- listPeerSubscriptions.mockImplementation(async ({ recordKind }) => {
- if (recordKind === 'universe') return [{ peerId: 'peer-ghost' }, { peerId: 'peer-live' }];
- return [];
- });
+ mockSubs({ universe: [{ peerId: 'peer-ghost' }, { peerId: 'peer-live' }] });
// peer-ghost was removed; only peer-live is still in the registry.
getPeers.mockResolvedValue([{ instanceId: 'peer-live', enabled: true }]);
getMinAckAcrossPeers.mockResolvedValue(NOW - 1000);
@@ -180,13 +175,12 @@ describe('sweepTombstones — peers behind', () => {
// (syncEnabled:false) receive no pushes, so their ack cursor never
// advances. Including them in getMinAckAcrossPeers would freeze the
// cutoff at their last ack (often 0) and stall GC indefinitely.
- listPeerSubscriptions.mockImplementation(async ({ recordKind }) => {
- if (recordKind === 'universe') return [
+ mockSubs({
+ universe: [
{ peerId: 'peer-disabled' },
{ peerId: 'peer-silenced' },
{ peerId: 'peer-active' },
- ];
- return [];
+ ],
});
getPeers.mockResolvedValue([
{ instanceId: 'peer-disabled', enabled: false },
@@ -208,7 +202,80 @@ describe('sweepTombstones — return shape', () => {
pruneTombstonedSeries.mockResolvedValueOnce({ pruned: 0 });
pruneTombstonedIssues.mockResolvedValueOnce({ pruned: 5 });
const result = await sweepTombstones({ now: NOW });
- expect(result).toEqual({ universes: 2, series: 0, issues: 5 });
+ expect(result).toEqual({ universes: 2, series: 0, issues: 5, refused: [] });
+ });
+
+ it('lists kinds whose cutoff was null in `refused` so the manual-trigger UI can explain why nothing pruned', async () => {
+ listPeerSubscriptions.mockResolvedValue([]);
+ getPeers.mockResolvedValue([
+ { instanceId: 'peer-a', enabled: true, syncCategories: { universe: true, pipeline: true } },
+ ]);
+ const result = await sweepTombstones({ now: NOW });
+ expect(result.refused.sort()).toEqual(['issue', 'series', 'universe']);
+ expect(result.universes).toBe(0);
+ expect(result.series).toBe(0);
+ expect(result.issues).toBe(0);
+ });
+});
+
+describe('sweepTombstones — graceMs override (manual trigger / CLI path)', () => {
+ it('passes the override through to the cutoff so callers can shrink the 24h buffer', async () => {
+ // Regression: the orchestrator path keeps the 24h default; the manual
+ // "GC now" button passes graceMs:0 so a user who just mass-deleted
+ // records doesn't have to wait 24h. The cutoff math must use the
+ // caller's graceMs, not the module-level GRACE_MS, when overridden.
+ await sweepTombstones({ now: NOW, graceMs: 0 });
+ expect(pruneTombstonedUniverses).toHaveBeenCalledWith(NOW);
+ expect(pruneTombstonedSeries).toHaveBeenCalledWith(NOW);
+ expect(pruneTombstonedIssues).toHaveBeenCalledWith(NOW);
+ });
+
+ it('defaults to TOMBSTONE_GRACE_MS when graceMs is omitted (orchestrator path unchanged)', async () => {
+ await sweepTombstones({ now: NOW });
+ expect(pruneTombstonedUniverses).toHaveBeenCalledWith(NOW - TOMBSTONE_GRACE_MS);
+ });
+
+ it('still clamps to min-ack even with graceMs:0 (per-record sub safety preserved)', async () => {
+ // graceMs:0 only removes the time buffer — the ack-horizon clamp must
+ // still fire, otherwise a manual trigger would prune past the laggiest
+ // peer's ack and resurrection would follow.
+ const minAck = NOW - 1000;
+ mockSubs({ universe: [{ peerId: 'peer-a' }] });
+ getPeers.mockResolvedValue([{ instanceId: 'peer-a', enabled: true }]);
+ getMinAckAcrossPeers.mockResolvedValue(minAck);
+ await sweepTombstones({ now: NOW, graceMs: 0 });
+ expect(pruneTombstonedUniverses).toHaveBeenCalledWith(minAck);
+ });
+
+ it('still refuses to prune snapshot-uncovered kinds even with graceMs:0', async () => {
+ // The snapshot-mode-peer gate is independent of graceMs — a manual
+ // trigger must not bypass the resurrection-safety check.
+ listPeerSubscriptions.mockResolvedValue([]);
+ getPeers.mockResolvedValue([
+ { instanceId: 'peer-a', enabled: true, syncCategories: { universe: true } },
+ ]);
+ const result = await sweepTombstones({ now: NOW, graceMs: 0 });
+ expect(pruneTombstonedUniverses).not.toHaveBeenCalled();
+ expect(result.refused).toContain('universe');
+ });
+});
+
+describe('getSweepStatus — dry-run for UI button gating', () => {
+ it('returns refused kinds without invoking any prune helper', async () => {
+ listPeerSubscriptions.mockResolvedValue([]);
+ getPeers.mockResolvedValue([
+ { instanceId: 'peer-a', enabled: true, syncCategories: { universe: true, pipeline: true } },
+ ]);
+ const result = await getSweepStatus({ now: NOW });
+ expect(result.refused.sort()).toEqual(['issue', 'series', 'universe']);
+ expect(pruneTombstonedUniverses).not.toHaveBeenCalled();
+ expect(pruneTombstonedSeries).not.toHaveBeenCalled();
+ expect(pruneTombstonedIssues).not.toHaveBeenCalled();
+ });
+
+ it('returns an empty refused list when every kind has an ack horizon', async () => {
+ const result = await getSweepStatus({ now: NOW });
+ expect(result.refused).toEqual([]);
});
});
@@ -247,10 +314,7 @@ describe('sweepTombstones — resurrection safety against snapshot-mode peers',
it('still prunes when per-record subscriptions exist (their min-ack water-mark provides the safety we need)', async () => {
// Snapshot peers are also subscribed via per-record: the ack cursor
// tracks every push they receive, so we have a horizon and CAN prune.
- listPeerSubscriptions.mockImplementation(async ({ recordKind }) => {
- if (recordKind === 'universe') return [{ peerId: 'peer-a' }];
- return [];
- });
+ mockSubs({ universe: [{ peerId: 'peer-a' }] });
getMinAckAcrossPeers.mockResolvedValue(NOW - 1000);
getPeers.mockResolvedValue([
{ instanceId: 'peer-a', enabled: true, syncCategories: { universe: true, pipeline: true } },
@@ -266,10 +330,7 @@ describe('sweepTombstones — resurrection safety against snapshot-mode peers',
// has no ack horizon — its next snapshot push could still resurrect
// a record we pruned based on peer-A's ack alone. The fix now checks
// for ANY uncovered snapshot peer.
- listPeerSubscriptions.mockImplementation(async ({ recordKind }) => {
- if (recordKind === 'universe') return [{ peerId: 'peer-a' }];
- return [];
- });
+ mockSubs({ universe: [{ peerId: 'peer-a' }] });
getMinAckAcrossPeers.mockResolvedValue(NOW - 1000);
getPeers.mockResolvedValue([
{ instanceId: 'peer-a', enabled: true, syncCategories: { universe: true } },