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: surface federation sync failures on stderr and stop advancing lastSyncAt on a failed cycle (#7943)

[._.]/ Adam Eivyb34e18783f93
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index b46ab05d24..643a38e77b 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -868,6 +868,15 @@ function SyncStatusSection({ peer, syncStatus, syncing = false }) {
<span className="text-[10px] text-gray-600 ml-auto">{timeAgo(cursor.lastSyncAt)}</span>
)}
</div>
+ {/* A cycle in which every category failed leaves lastSyncAt at its old
+ value and records why (#7943) — without this the card read "synced N
+ seconds ago" while cross-machine sync had been broken for weeks. */}
+ {cursor?.lastSyncError && (
+ <div role="status" className="flex items-start gap-1.5 mb-1.5 text-[10px] text-port-error" title={cursor.lastSyncError}>
+ <AlertCircle size={12} className="shrink-0 mt-px" />
+ <span className="truncate">Last sync failed: {cursor.lastSyncError}</span>
+ </div>
+ )}
<div className="grid grid-cols-2 gap-x-3 gap-y-0.5">
{showBrain && (
<SyncStatusBadge
@@ -1175,7 +1184,9 @@ export function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo, parityRepor
// (`handleSync`) does its own authoritative refetch on the awaited POST,
// so a no-op manual sync still settles; this branch covers the
// records-moved case for both manual and background syncs.
- if (payload.totalApplied > 0) onRefresh();
+ // A failed cycle applies nothing, so the totalApplied gate alone would
+ // never pull the new `lastSyncError` onto the card (#7943).
+ if (payload.totalApplied > 0 || payload.error) onRefresh();
}
// `applied` events are informational (and drive the server-side log) —
// the global `syncing` flag already animates every badge, so the client
diff --git a/client/src/pages/Instances.test.jsx b/client/src/pages/Instances.test.jsx
index 56adf7e2ac..d084e5e782 100644
--- a/client/src/pages/Instances.test.jsx
+++ b/client/src/pages/Instances.test.jsx
@@ -279,6 +279,44 @@ describe('PeerCard snapshot progress', () => {
expect(screen.queryByText('Coverage unavailable')).not.toBeInTheDocument();
});
+ // #7943: a cycle in which every category failed leaves lastSyncAt at its
+ // previous value and records lastSyncError. Without rendering it, the card
+ // showed "synced N minutes ago" for a peer that had been broken for weeks.
+ it('renders lastSyncError beside the timestamp, and nothing when the cycle was clean', async () => {
+ const failed = {
+ cursors: {
+ [peer.instanceId]: {
+ checksums: { universe: 'old', pipeline: 'same' },
+ lastSyncAt: '2026-01-01T00:00:00.000Z',
+ lastSyncError: 'universe: peer DB was rebuilt',
+ },
+ },
+ };
+ const view = renderUI(<PeerCard peer={peer} syncStatus={failed} onRefresh={vi.fn()} />);
+ await act(async () => {});
+ expect(screen.getByText(/Last sync failed: universe: peer DB was rebuilt/)).toBeInTheDocument();
+
+ view.rerender(<PeerCard peer={peer} syncStatus={syncStatus} onRefresh={vi.fn()} />);
+ expect(screen.queryByText(/Last sync failed/)).not.toBeInTheDocument();
+ });
+
+ // A failed cycle applies nothing, so a totalApplied-only refetch gate would
+ // never pull the new error string onto the card.
+ it('refetches on a complete event that carries an error but applied nothing', async () => {
+ const onRefresh = vi.fn();
+ renderUI(<PeerCard peer={peer} syncStatus={syncStatus} onRefresh={onRefresh} />);
+ await act(async () => {});
+ const [, handleProgress] = socket.on.mock.calls.find(([event]) => event === 'sync:progress');
+
+ await act(async () => handleProgress({ phase: 'complete', peerId: peer.instanceId, totalApplied: 0, error: null }));
+ expect(onRefresh).not.toHaveBeenCalled();
+
+ await act(async () => handleProgress({
+ phase: 'complete', peerId: peer.instanceId, totalApplied: 0, error: 'universe: peer DB was rebuilt',
+ }));
+ expect(onRefresh).toHaveBeenCalledTimes(1);
+ });
+
// A slow or failed subscription endpoint must not hide a known mismatch.
it('shows known status while subscriptions are unresolved and after they fail', async () => {
let rejectSubscriptions;
diff --git a/docs/API.md b/docs/API.md
index 256af75632..7c51d8609b 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -74,7 +74,7 @@ credentials, local paths, or build identity to these responses.
|--------|----------|--------------------------------------|
| GET | `/system/health/details` | Returns an object containing `instanceId` and `version` (each may be `null`) for peer identity and compatibility display. The health summary remains an object so an older prober can retain it as its last-known health snapshot. |
| GET | `/apps?view=probe` | The periodic probe requests `view=probe`; returns either the legacy app array or `{ apps: [...] }`. Each app entry used by peers retains `id`, `name`, `icon`, `overallStatus`, `uiPort`, `apiPort`, and `type`; fields may be absent or `null` when unknown. Older peers may ignore the query and return the legacy enriched list, which remains compatible with the same field mapping. |
-| GET | `/instances/sync-status?forPeer=<instance-id>` | `forPeer` is optional and remains lenient: an unknown or legacy identifier, blank value, or omitted value must degrade to the unscoped status response rather than fail the probe. A recognized peer receives its `cursorForYou` alongside the normal sync status. |
+| GET | `/instances/sync-status?forPeer=<instance-id>` | `forPeer` is optional and remains lenient: an unknown or legacy identifier, blank value, or omitted value must degrade to the unscoped status response rather than fail the probe. A recognized peer receives its `cursorForYou` alongside the normal sync status — with this install's own `lastSyncError` / `lastSyncSucceeded` stripped, since those carry local diagnostics and the endpoint is reachable by any tailnet machine. |
The separate `/federation/media/v1` surface is already versioned and has its
own wire contract in [FEDERATED_MEDIA_PROVIDERS.md](./FEDERATED_MEDIA_PROVIDERS.md).
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index ff1119ffec..e19099f763 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -28,6 +28,7 @@ import { existsSync } from 'fs';
import { EventEmitter } from 'events';
import { PATHS, copyFileGuarded, ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
import { isSafeRecordId } from '../../lib/validation.js';
+import { logFailureWithStack } from '../../lib/failureLogging.js';
import { getBucket, bucketBlobPath, bucketBlobSidecarPath, bucketRecordsDir, bucketRecordPath, imageSidecarName, isHexHash } from './buckets.js';
import { readManifest, markProcessed, readCursor, hasBeenProcessed, forgetProcessed } from './manifest.js';
import { SHARING_SCHEMA_VERSION, isManifestCompatible } from './version.js';
@@ -134,7 +135,7 @@ async function mergeCollectionPayload(payload, availableAssetKeys = null) {
universeName,
description: payload.description || '',
}).catch((err) => {
- console.log(`⚠️ sharing.importer: findOrCreateUniverseCollection failed: ${err.message}`);
+ logFailureWithStack('⚠️ sharing.importer: findOrCreateUniverseCollection failed', err);
return null;
});
} else {
@@ -167,7 +168,7 @@ async function mergeCollectionPayload(payload, availableAssetKeys = null) {
universeName: localUniverse.name,
description: payload.description || '',
}).catch((err) => {
- console.log(`⚠️ sharing.importer: findOrCreateUniverseCollection (series re-route) failed: ${err.message}`);
+ logFailureWithStack('⚠️ sharing.importer: findOrCreateUniverseCollection (series re-route) failed', err);
return null;
});
} else {
@@ -181,7 +182,7 @@ async function mergeCollectionPayload(payload, availableAssetKeys = null) {
seriesName,
description: payload.description || '',
}).catch((err) => {
- console.log(`⚠️ sharing.importer: findOrCreateSeriesCollection failed: ${err.message}`);
+ logFailureWithStack('⚠️ sharing.importer: findOrCreateSeriesCollection failed', err);
return null;
});
}
@@ -197,7 +198,7 @@ async function mergeCollectionPayload(payload, availableAssetKeys = null) {
}
const result = await addCollectionItem(collection.id, item).catch((err) => {
if (err?.code === COLLECTION_ERR_DUPLICATE) return null;
- console.log(`⚠️ sharing.importer: addCollectionItem failed for ${item.ref}: ${err.message}`);
+ logFailureWithStack(`⚠️ sharing.importer: addCollectionItem failed for ${item.ref}`, err);
return null;
});
if (result) added += 1;
@@ -236,7 +237,7 @@ function manifestAssetRefs(manifest) {
const entry = { kind, ref: filename };
if (raw.hash !== undefined && raw.hash !== null) {
if (!isHexHash(raw.hash)) {
- console.log(`⚠️ sharing.importer: dropping asset ref with invalid hash: ${kind}/${filename}`);
+ console.error(`⚠️ sharing.importer: dropping asset ref with invalid hash: ${kind}/${filename}`);
return;
}
entry.hash = raw.hash;
@@ -309,7 +310,7 @@ async function copyAssetsLocally(bucketPath, assetRefs) {
const sidecarTarget = join(targetDir, imageSidecarName(filename));
if (!existsSync(sidecarTarget)) await copyFileGuarded(sidecarPath, sidecarTarget);
}
- if (kind === 'image') await import('../mediaAssetIndex/index.js').then(m => m.indexImage({ filename })).catch(err => console.error(`❌ Media index imported asset refresh: ${err.message}`));
+ if (kind === 'image') await import('../mediaAssetIndex/index.js').then(m => m.indexImage({ filename })).catch(err => logFailureWithStack('❌ Media index imported asset refresh', err));
}));
return { copied, available, missing };
}
@@ -543,7 +544,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
// Unexpected failure: the record did NOT land. Record it so the
// manifest stays pending and retries — incrementing `applied` and
// advancing the cursor here would silently drop the record.
- console.log(`⚠️ sharing.importer: insertWithId(${kind}=${record.id}) failed: ${err.message}`);
+ logFailureWithStack(`⚠️ sharing.importer: insertWithId(${kind}=${record.id}) failed`, err);
failedInserts.push(`${kind}:${record.id}`);
return false;
});
@@ -655,7 +656,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
}
const r = await applyLegacySeriesCanonToUniverse(s).catch((err) => {
- console.log(`⚠️ sharing.importer: legacy series canon migration for ${s.id} failed: ${err.message}`);
+ logFailureWithStack(`⚠️ sharing.importer: legacy series canon migration for ${s.id} failed`, err);
return null;
});
if (!r) {
@@ -668,7 +669,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
continue;
}
if (r.skipped === 'missing-universe') {
- console.log(`⚠️ sharing.importer: skipping series ${s.id} merge — missing universe ${r.universeId}`);
+ console.error(`⚠️ sharing.importer: skipping series ${s.id} merge — missing universe ${r.universeId}`);
skipSeriesMerge.add(s.id);
if (r.universeId) legacyCanonPendingUniverses.push(r.universeId);
continue;
@@ -720,7 +721,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
const review = await readJSONFile(bucketRecordPath(bucket.path, 'reviews', s.id), null, { logError: false });
if (review) {
await mergeReviewFromSync(s.id, review).catch((err) => {
- console.log(`⚠️ sharing.importer: manuscript-review merge for ${s.id} failed: ${err.message}`);
+ logFailureWithStack(`⚠️ sharing.importer: manuscript-review merge for ${s.id} failed`, err);
reviewMergeFailures.push(s.id);
});
}
@@ -741,7 +742,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
const outline = await readJSONFile(bucketRecordPath(bucket.path, 'outlines', s.id), null, { logError: false });
if (outline) {
await mergeOutlineFromSync(s.id, outline).catch((err) => {
- console.log(`⚠️ sharing.importer: reverse-outline merge for ${s.id} failed: ${err.message}`);
+ logFailureWithStack(`⚠️ sharing.importer: reverse-outline merge for ${s.id} failed`, err);
outlineMergeFailures.push(s.id);
});
}
@@ -789,7 +790,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
...inboundSub,
lastManifestId: manifest.id,
}).catch((err) => {
- console.log(`⚠️ sharing.importer: adopt subscription failed for ${inboundSub.recordKind}/${inboundSub.recordId}: ${err.message}`);
+ logFailureWithStack(`⚠️ sharing.importer: adopt subscription failed for ${inboundSub.recordKind}/${inboundSub.recordId}`, err);
return null;
});
}
@@ -974,7 +975,7 @@ export async function processManifest(bucketId, manifestFilename) {
producedByVersion: manifest.producedByVersion || 'unknown',
source: manifest.source || 'unknown',
});
- console.log(`⚠️ sharing: bucket=${bucket.name} manifest=${manifest.id} schemaVersion=${remoteVersion} > local=${SHARING_SCHEMA_VERSION} — refusing import (peer producedBy=${manifest.producedByVersion || 'unknown'})`);
+ console.error(`⚠️ sharing: bucket=${bucket.name} manifest=${manifest.id} schemaVersion=${remoteVersion} > local=${SHARING_SCHEMA_VERSION} — refusing import (peer producedBy=${manifest.producedByVersion || 'unknown'})`);
return { skipped: true, reason: 'incompatible-version', remoteVersion, localVersion: SHARING_SCHEMA_VERSION };
}
// PORTOS SCHEMA-VERSION GATE — even when the share-protocol schemaVersion
@@ -1086,7 +1087,7 @@ export async function processManifest(bucketId, manifestFilename) {
if (collectionTombstonedUniverse) {
await markProcessed(bucketId, manifestFilename, manifest.id);
sharingEvents.emit('manifest-processed', { bucketId, manifestId: manifest.id, manifestFilename, outcome });
- console.log(`⚠️ sharing: bucket=${bucket.name} manifest=${manifest.id} kind=${manifest.kind} collectionUniverse=${collectionTombstonedUniverse} is deleted locally — ${outcome.collectionItemsDeferred ?? 0} item(s) skipped; restore universe to import`);
+ console.error(`⚠️ sharing: bucket=${bucket.name} manifest=${manifest.id} kind=${manifest.kind} collectionUniverse=${collectionTombstonedUniverse} is deleted locally — ${outcome.collectionItemsDeferred ?? 0} item(s) skipped; restore universe to import`);
return { processed: true, manifest, outcome };
}
// Each row is checked once for "is this still pending?", assigned onto
@@ -1185,7 +1186,7 @@ export async function processBacklog(bucketId) {
const bucket = await getBucket(bucketId);
const localInstanceId = await getInstanceId().catch(() => null);
await pruneSelfAuthoredInbox(bucket, localInstanceId).catch((err) => {
- console.log(`⚠️ sharing.importer: pruneSelfAuthoredInbox failed: ${err.message}`);
+ logFailureWithStack('⚠️ sharing.importer: pruneSelfAuthoredInbox failed', err);
});
const manifestsDir = join(bucket.path, 'manifests');
if (!existsSync(manifestsDir)) return { processed: 0 };
@@ -1195,7 +1196,7 @@ export async function processBacklog(bucketId) {
let processed = 0;
for (const f of filenames) {
const res = await processManifest(bucketId, f).catch((err) => {
- console.log(`⚠️ sharing.importer: processManifest failed for ${f}: ${err.message}`);
+ logFailureWithStack(`⚠️ sharing.importer: processManifest failed for ${f}`, err);
return null;
});
if (res?.processed) processed++;
diff --git a/server/services/sharing/peerCosSync.js b/server/services/sharing/peerCosSync.js
index 3c81f6032b..e876340af1 100644
--- a/server/services/sharing/peerCosSync.js
+++ b/server/services/sharing/peerCosSync.js
@@ -15,6 +15,7 @@ import { readdir } from 'fs/promises';
import { createHash } from 'crypto';
import { PATHS, atomicWrite, ensureDir, sha256File, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';
import { isPlainObject } from '../../lib/objects.js';
+import { logFailureWithStack } from '../../lib/failureLogging.js';
import { peerBaseUrl } from '../../lib/peerUrl.js';
import { peerFetch } from '../../lib/peerHttpClient.js';
import { withAbortTimeout } from '../../lib/abortTimeout.js';
@@ -112,7 +113,7 @@ export async function buildCosHistoryManifest() {
}
}
if (truncated) {
- console.log(`⚠️ peerSync: cos-history manifest hit the ${COS_HISTORY_MANIFEST_CAP}-entry cap — truncating (some archives won't federate; pagination is a follow-up)`);
+ console.error(`⚠️ peerSync: cos-history manifest hit the ${COS_HISTORY_MANIFEST_CAP}-entry cap — truncating (some archives won't federate; pagination is a follow-up)`);
}
// Deterministic order so the manifestHash converges across machines regardless
// of readdir order. (date, agentId already sorted above; sort by file too.)
@@ -155,14 +156,14 @@ async function pullMissingCosArchives(senderInstanceId, missing) {
if (!isStr(senderInstanceId) || !Array.isArray(missing) || missing.length === 0) return [];
const peer = await findPeerById(senderInstanceId);
if (!peer) {
- console.log(`⚠️ peerSync: can't pull cos archives — peer ${senderInstanceId} not in registry`);
+ console.error(`⚠️ peerSync: can't pull cos archives — peer ${senderInstanceId} not in registry`);
return [];
}
const base = peerBaseUrl(peer);
const landed = [];
for (const entry of missing) {
const pair = await pullOneCosArchiveFile(peer, base, entry).catch((err) => {
- console.log(`⚠️ peerSync: cos-archive pull ${entry?.agentId}/${entry?.file} from ${peer.name || senderInstanceId} failed: ${err.message}`);
+ logFailureWithStack(`⚠️ peerSync: cos-archive pull ${entry?.agentId}/${entry?.file} from ${peer.name || senderInstanceId} failed`, err);
return null;
});
if (pair) landed.push(pair);
@@ -186,7 +187,7 @@ async function pullOneCosArchiveFile(peer, base, entry) {
// Integrity: discard a corrupt/wrong download instead of writing it.
const bufHash = createHash('sha256').update(buffer).digest('hex');
if (bufHash !== sha256) {
- console.log(`⚠️ peerSync: cos archive ${safeLabel} hash mismatch — discarding (got ${bufHash.slice(0, 8)}, want ${String(sha256).slice(0, 8)})`);
+ console.error(`⚠️ peerSync: cos archive ${safeLabel} hash mismatch — discarding (got ${bufHash.slice(0, 8)}, want ${String(sha256).slice(0, 8)})`);
return null;
}
const destDir = join(cosAgentsDir(), date, agentId);
@@ -223,7 +224,7 @@ async function reconcileCosHistoryIndex(entries) {
const mod = await import('../cosAgentIndex.js').catch(() => null);
if (!mod?.addAgentArchivesToIndex) return;
await mod.addAgentArchivesToIndex(pairs).catch((err) => {
- console.log(`⚠️ peerSync: cos-history index merge failed: ${err.message}`);
+ logFailureWithStack('⚠️ peerSync: cos-history index merge failed', err);
});
}
@@ -249,13 +250,13 @@ export async function syncCosHistoryFromPeer(peer) {
if (!res || !res.ok) return { pulled: 0, skipped: 'unreachable' };
const declaredLen = Number(res.headers?.get?.('content-length'));
if (Number.isFinite(declaredLen) && declaredLen > COS_HISTORY_MANIFEST_MAX_BYTES) {
- console.log(`⚠️ peerSync: cos-history manifest from ${peer.name || peer.instanceId} too large (${declaredLen} > ${COS_HISTORY_MANIFEST_MAX_BYTES}) — skipping`);
+ console.error(`⚠️ peerSync: cos-history manifest from ${peer.name || peer.instanceId} too large (${declaredLen} > ${COS_HISTORY_MANIFEST_MAX_BYTES}) — skipping`);
return { pulled: 0, skipped: 'too-large' };
}
const body = await res.json().catch(() => null);
const parsed = peerCosHistoryManifestSchema.safeParse(body);
if (!parsed.success) {
- console.log(`⚠️ peerSync: cos-history manifest from ${peer.name || peer.instanceId} failed validation — skipping`);
+ console.error(`⚠️ peerSync: cos-history manifest from ${peer.name || peer.instanceId} failed validation — skipping`);
return { pulled: 0, skipped: 'invalid' };
}
const manifest = parsed.data;
@@ -303,7 +304,7 @@ export async function syncCosHistoryFromPeer(peer) {
// Partial pull — do NOT record the hash, so the next tick re-diffs and
// retries the still-missing files; the index is reconciled once the
// manifest is fully present (above), never from a half-pulled agent.
- console.log(`⚠️ peerSync: cos-history sweep from ${peer.name || peer.instanceId} — pulled ${pulled}/${requested}, ${stillMissing.length} still missing; retrying next tick`);
+ console.error(`⚠️ peerSync: cos-history sweep from ${peer.name || peer.instanceId} — pulled ${pulled}/${requested}, ${stillMissing.length} still missing; retrying next tick`);
}
return { pulled, missing: stillMissing.length };
} finally {
@@ -320,7 +321,7 @@ export async function syncCosHistoryWithAllPeers() {
const fullSyncPeers = peers.filter((p) => p?.fullSync === true && p?.enabled !== false && isStr(p.instanceId));
for (const peer of fullSyncPeers) {
await syncCosHistoryFromPeer(peer).catch((err) => {
- console.log(`⚠️ peerSync: cos-history sweep for ${peer.name || peer.instanceId} failed: ${err.message}`);
+ logFailureWithStack(`⚠️ peerSync: cos-history sweep for ${peer.name || peer.instanceId} failed`, err);
});
}
}
@@ -393,7 +394,7 @@ export async function buildCosTasksPayload() {
...((cosRes?.tasks || []).filter((t) => !isMachineLocalCosTask(t)).map((t) => taskToWireEntry(t, 'internal'))),
];
if (entries.length > COS_TASKS_ENTRY_CAP) {
- console.log(`⚠️ peerSync: cos-tasks payload hit the ${COS_TASKS_ENTRY_CAP}-entry cap — truncating (some tasks won't federate this tick)`);
+ console.error(`⚠️ peerSync: cos-tasks payload hit the ${COS_TASKS_ENTRY_CAP}-entry cap — truncating (some tasks won't federate this tick)`);
entries = entries.slice(0, COS_TASKS_ENTRY_CAP);
}
// Deterministic order so the listHash is stable across ticks regardless of
@@ -436,11 +437,11 @@ async function mergeCosTasksFromPayload(tasks) {
// resolved/removed from a file converges — an empty list still merges (union
// keeps local-only tasks, so it never wipes the local backlog).
const userRes = await mod.mergePeerTasks('user', user).catch((err) => {
- console.log(`⚠️ peerSync: cos-tasks user merge failed: ${err.message}`); return null;
+ logFailureWithStack('⚠️ peerSync: cos-tasks user merge failed', err); return null;
});
if (userRes?.changed) changed++;
const internalRes = await mod.mergePeerTasks('internal', internal).catch((err) => {
- console.log(`⚠️ peerSync: cos-tasks internal merge failed: ${err.message}`); return null;
+ logFailureWithStack('⚠️ peerSync: cos-tasks internal merge failed', err); return null;
});
if (internalRes?.changed) changed++;
return changed;
@@ -468,13 +469,13 @@ export async function syncCosTasksFromPeer(peer) {
if (!res || !res.ok) return { merged: 0, skipped: 'unreachable' };
const declaredLen = Number(res.headers?.get?.('content-length'));
if (Number.isFinite(declaredLen) && declaredLen > COS_TASKS_MAX_BYTES) {
- console.log(`⚠️ peerSync: cos-tasks payload from ${peer.name || peer.instanceId} too large (${declaredLen} > ${COS_TASKS_MAX_BYTES}) — skipping`);
+ console.error(`⚠️ peerSync: cos-tasks payload from ${peer.name || peer.instanceId} too large (${declaredLen} > ${COS_TASKS_MAX_BYTES}) — skipping`);
return { merged: 0, skipped: 'too-large' };
}
const body = await res.json().catch(() => null);
const parsed = peerCosTasksSchema.safeParse(body);
if (!parsed.success) {
- console.log(`⚠️ peerSync: cos-tasks payload from ${peer.name || peer.instanceId} failed validation — skipping`);
+ console.error(`⚠️ peerSync: cos-tasks payload from ${peer.name || peer.instanceId} failed validation — skipping`);
return { merged: 0, skipped: 'invalid' };
}
const payload = parsed.data;
@@ -516,7 +517,7 @@ export async function syncCosTasksWithAllPeers() {
const fullSyncPeers = peers.filter((p) => p?.fullSync === true && p?.enabled !== false && isStr(p.instanceId));
for (const peer of fullSyncPeers) {
await syncCosTasksFromPeer(peer).catch((err) => {
- console.log(`⚠️ peerSync: cos-tasks sweep for ${peer.name || peer.instanceId} failed: ${err.message}`);
+ logFailureWithStack(`⚠️ peerSync: cos-tasks sweep for ${peer.name || peer.instanceId} failed`, err);
});
}
}
\ No newline at end of file
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 5af9d08a3c..19bd7581b6 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -25,6 +25,7 @@ import { peerBaseUrl } from '../../lib/peerUrl.js';
import { peerFetch } from '../../lib/peerHttpClient.js';
import { RESPONSE_TOO_LARGE } from '../../lib/httpClient.js';
import { withAbortTimeout } from '../../lib/abortTimeout.js';
+import { logFailureWithStack } from '../../lib/failureLogging.js';
import { flushBaseHashes, withBaseHashFlushBatch } from '../../lib/conflictJournal.js';
import { recordEvents, registerSubscriptionAdapter } from './recordEvents.js';
import { getPeers, enqueueReciprocalSync } from '../instances.js';
@@ -143,7 +144,7 @@ export async function autoSubscribeRecordToAllPeers(recordKind, recordId) {
await withBaseHashFlushBatch(async () => {
for (const peer of targets) {
const sub = await subscribePeer({ peerId: peer.instanceId, recordKind, recordId }, { awaitInitialPush: true }).catch((err) => {
- console.log(`⚠️ peerSync: auto-subscribe ${recordKind}/${recordId} → ${peer.name || peer.instanceId} failed: ${err.message}`);
+ logFailureWithStack(`⚠️ peerSync: auto-subscribe ${recordKind}/${recordId} → ${peer.name || peer.instanceId} failed`, err);
return null;
});
if (sub && sub.created) {
@@ -246,7 +247,7 @@ export async function autoSubscribePeerToAllRecords(peerId, recordKind) {
const peer = peers.find(p => p.instanceId === peerId);
if (!peer || !peerAllowsOutbound(peer) || !peerHasCategory(peer, recordKind)) return [];
const records = await listRecordsForKind(recordKind).catch(() => {
- console.log(`⚠️ peerSync: backfill inventory unavailable for ${recordKind}/records`);
+ console.error(`⚠️ peerSync: backfill inventory unavailable for ${recordKind}/records`);
return [];
});
if (records.length === 0) return [];
@@ -280,7 +281,7 @@ export async function autoSubscribePeerToAllRecords(peerId, recordKind) {
await withBaseHashFlushBatch(async () => {
for (const rec of missing) {
const sub = await subscribePeer({ peerId, recordKind, recordId: rec.id }, { skipCursorInit: cursorInited, awaitInitialPush: true }).catch((err) => {
- console.log(`⚠️ peerSync: backfill-subscribe ${recordKind}/${rec.id} → ${peerId} failed: ${err.message}`);
+ logFailureWithStack(`⚠️ peerSync: backfill-subscribe ${recordKind}/${rec.id} → ${peerId} failed`, err);
return null;
});
if (sub && sub.created) created.push({ recordId: rec.id, subscriptionId: sub.id });
@@ -318,7 +319,7 @@ export async function getFullSyncCoverageForPeer(peerId) {
const failedReads = results.flatMap((result, index) => {
if (result.status === 'fulfilled') return [];
const operation = index === 0 ? 'records' : 'subscriptions';
- console.log(`⚠️ peerSync: full-sync coverage unavailable for ${kind}/${operation}`);
+ console.error(`⚠️ peerSync: full-sync coverage unavailable for ${kind}/${operation}`);
return [{ kind, operation }];
});
const records = results[0].status === 'fulfilled' ? results[0].value : [];
@@ -364,7 +365,7 @@ export async function unsubscribeAllForPeer(peerId) {
const removed = [];
for (const sub of matching) {
await unsubscribePeer(sub.id).catch((err) => {
- console.log(`⚠️ peerSync: unsubscribe-all failed for ${sub.id}: ${err.message}`);
+ logFailureWithStack(`⚠️ peerSync: unsubscribe-all failed for ${sub.id}`, err);
});
removed.push(sub.id);
}
@@ -396,7 +397,7 @@ export async function unsubscribeAllForRecord(recordKind, recordId) {
const failed = [];
for (const sub of matching) {
const ok = await unsubscribePeer(sub.id).then(() => true).catch((err) => {
- console.log(`⚠️ peerSync: unsubscribe-for-record failed for ${sub.id}: ${err.message}`);
+ logFailureWithStack(`⚠️ peerSync: unsubscribe-for-record failed for ${sub.id}`, err);
return false;
});
if (ok) {
@@ -441,7 +442,7 @@ export async function pruneOrphanedPeerSubscriptions(resolver) {
const exists = await resolver(sub.recordKind, sub.recordId).catch(() => true);
if (exists) continue;
const ok = await unsubscribePeer(sub.id).then(() => true).catch((err) => {
- console.log(`⚠️ peerSync: orphan-subscription sweep failed for ${sub.id}: ${err.message}`);
+ logFailureWithStack(`⚠️ peerSync: orphan-subscription sweep failed for ${sub.id}`, err);
return false;
});
if (ok) removed.push(sub.id);
@@ -481,7 +482,7 @@ export async function triggerPushForRecord(recordKind, recordId) {
// newer hash. Reading the live record by id makes the debounced fire
// safe against all three.
trackBackgroundOperation(pushFromFreshSubscription(subId).catch((err) => {
- console.log(`⚠️ peerSync: scheduled push failed for ${subId}: ${err.message}`);
+ logFailureWithStack(`⚠️ peerSync: scheduled push failed for ${subId}`, err);
}));
}, DEBOUNCE_MS);
if (typeof t.unref === 'function') t.unref();
@@ -603,7 +604,7 @@ export async function retryPendingPushesForPeer(peerId) {
// may have upgraded since the last 409). Edit-triggered pushes still
// respect the cooldown.
const result = await pushRecordToPeer(sub, { bypassSchemaCooldown: true }).catch((err) => {
- console.log(`⚠️ peerSync: retry push failed for ${sub.id}: ${err.message}`);
+ logFailureWithStack(`⚠️ peerSync: retry push failed for ${sub.id}`, err);
return null;
});
if (result?.pushed) pushed += 1;
@@ -676,7 +677,7 @@ export async function pullRecordFromPeer(peerId, recordKind, recordId) {
.catch((err) => {
if (err?.code === RESPONSE_TOO_LARGE) {
tooLarge = true; // HTTPS shim tripped the cap — same condition as the Content-Length check
- console.log(`⚠️ peerSync: pull-record ${recordKind}/${recordId} exceeded payload cap — ${err.message}`);
+ logFailureWithStack(`⚠️ peerSync: pull-record ${recordKind}/${recordId} exceeded payload cap`, err);
}
return null;
});
@@ -688,7 +689,7 @@ export async function pullRecordFromPeer(peerId, recordKind, recordId) {
// Content-Length on JSON — reject an oversized declared body before buffering.
const declaredLen = Number(res.headers?.get?.('content-length'));
if (Number.isFinite(declaredLen) && declaredLen > RECORD_PAYLOAD_MAX_BYTES) {
- console.log(`⚠️ peerSync: pull-record ${recordKind}/${recordId} declared ${declaredLen} bytes > cap`);
+ console.error(`⚠️ peerSync: pull-record ${recordKind}/${recordId} declared ${declaredLen} bytes > cap`);
return { pulled: false, reason: 'payload-too-large' };
}
@@ -727,12 +728,12 @@ export async function syncNowForPeer(peerId) {
for (const kind of PEER_SUBSCRIBABLE_KINDS) {
if (peerHasCategory(peer, kind)) {
await autoSubscribePeerToAllRecords(peer.instanceId, kind).catch(() => {
- console.log(`⚠️ peerSync: syncNow backfill failed for ${kind}`);
+ console.error(`⚠️ peerSync: syncNow backfill failed for ${kind}`);
});
}
}
await retryPendingPushesForPeer(peer.instanceId).catch((err) => {
- console.log(`⚠️ peerSync: syncNow retry pushes → ${peerId} failed: ${err.message}`);
+ logFailureWithStack(`⚠️ peerSync: syncNow retry pushes → ${peerId} failed`, err);
});
return { ok: true };
}
@@ -746,7 +747,7 @@ export function installPeerSyncListener() {
if (onUpdated) return;
onUpdated = ({ recordKind, recordId }) => {
trackBackgroundOperation(triggerPushForRecord(recordKind, recordId).catch((err) => {
- console.log(`⚠️ peerSync: listener error for ${recordKind}/${recordId}: ${err.message}`);
+ logFailureWithStack(`⚠️ peerSync: listener error for ${recordKind}/${recordId}`, err);
}));
};
recordEvents.on('updated', onUpdated);
@@ -765,7 +766,7 @@ export function installPeerSyncListener() {
// `forPeerId` scoping.)
onDeleted = ({ recordKind, recordId }) => {
trackBackgroundOperation(triggerPushForRecord(recordKind, recordId).catch((err) => {
- console.log(`⚠️ peerSync: delete listener error for ${recordKind}/${recordId}: ${err.message}`);
+ logFailureWithStack(`⚠️ peerSync: delete listener error for ${recordKind}/${recordId}`, err);
}));
};
recordEvents.on('deleted', onDeleted);
@@ -800,7 +801,7 @@ export function installPeerSyncListener() {
// subscribes every kind here.
if (peerHasCategory(peer, kind)) {
await autoSubscribePeerToAllRecords(peer.instanceId, kind).catch(() => {
- console.log(`⚠️ peerSync: peer:online backfill failed for ${kind}`);
+ console.error(`⚠️ peerSync: peer:online backfill failed for ${kind}`);
});
}
}
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index a3b8f26b11..458d084917 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -675,6 +675,9 @@ describe('peerSync', () => {
// An inventory failure must survive both lazy and direct lister boundaries.
it('marks failed inventories unavailable even when the remaining subset is confirmed', async () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ // Inventory failures log to stderr (#7943); both streams are checked so
+ // the redaction contract can't be satisfied by moving the leak elsewhere.
+ const errorLog = vi.spyOn(console, 'error').mockImplementation(() => {});
vi.mocked(listUniverses).mockRejectedValue(new Error('private database details'));
vi.mocked(listAuthors).mockRejectedValue(new Error('private author contents'));
vi.mocked(listSeries).mockResolvedValue([{ id: 's1' }]);
@@ -689,9 +692,10 @@ describe('peerSync', () => {
]);
expect(cov.byKind.universe).toMatchObject({ partial: true });
expect(JSON.stringify(cov)).not.toContain('private');
- expect(log.mock.calls.flat().join(' ')).not.toContain('private');
- expect(log.mock.calls.filter(([message]) => message.includes('coverage unavailable'))).toHaveLength(2);
+ expect([...log.mock.calls, ...errorLog.mock.calls].flat().join(' ')).not.toContain('private');
+ expect(errorLog.mock.calls.filter(([message]) => message.includes('coverage unavailable'))).toHaveLength(2);
log.mockRestore();
+ errorLog.mockRestore();
});
it('reports unavailable when subscription storage cannot be read, including empty inventories', async () => {
@@ -1261,6 +1265,7 @@ describe('peerSync', () => {
it('continues peer-online backfill after a kind inventory fails without logging private errors', async () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const errorLog = vi.spyOn(console, 'error').mockImplementation(() => {});
const { instanceEvents } = await import('../instanceEvents.js');
const { installPeerSyncListener } = await import('./peerSync.js');
installPeerSyncListener();
@@ -1274,9 +1279,10 @@ describe('peerSync', () => {
});
await __drainForTests();
expect(await findPeerSubscription('peer-a', 'series', 's1')).not.toBeNull();
- expect(log).toHaveBeenCalledWith('⚠️ peerSync: backfill inventory unavailable for universe/records');
- expect(log.mock.calls.flat().join(' ')).not.toContain('private inventory details');
+ expect(errorLog).toHaveBeenCalledWith('⚠️ peerSync: backfill inventory unavailable for universe/records');
+ expect([...log.mock.calls, ...errorLog.mock.calls].flat().join(' ')).not.toContain('private inventory details');
log.mockRestore();
+ errorLog.mockRestore();
});
it('converges from peer:online when the toggle fired before instanceId was known', async () => {
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index 02f9ea4b9b..b586e99ee6 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -10,6 +10,7 @@ import { access } from 'fs/promises';
import { join } from 'path';
import { readJSONFile, ensureDir, PATHS, dataPath, atomicWrite, writeFileGuarded } from '../lib/fileUtils.js';
import { createMutex } from '../lib/asyncMutex.js';
+import { logFailureWithStack } from '../lib/failureLogging.js';
import { instanceEvents } from './instanceEvents.js';
import { getPeers, resolveEffectiveCategories, updatePeer } from './instances.js';
import { getInstanceId, UNKNOWN_INSTANCE_ID } from './instanceIdentity.js';
@@ -181,11 +182,22 @@ export async function getSyncStatus({ includeChecksums = false, forPeer = null }
// us, so the requesting peer can render an outbound "N to push" count without
// us tracking its local max. Null when we've never synced that peer.
if (isNonBlankStr(forPeer)) {
- result.cursorForYou = cursors[forPeer] ?? null;
+ result.cursorForYou = redactLocalCursorState(cursors[forPeer] ?? null);
}
return result;
}
+// Our own last-failure string is LOCAL diagnostics: it carries whatever an
+// exception on this machine happened to say (paths, hostnames, DB errors), and
+// `/api/instances/sync-status` is reachable by any tailnet machine, not just a
+// peer in our list. The self-view (`cursors`, served to our own browser) keeps
+// it; the peer-facing `cursorForYou` projection drops it.
+function redactLocalCursorState(cursor) {
+ if (!cursor || typeof cursor !== 'object') return cursor;
+ const { lastSyncError, lastSyncSucceeded, ...rest } = cursor;
+ return rest;
+}
+
// --- Sync logic ---
/**
@@ -365,7 +377,7 @@ async function syncCatalogFromPeer(peer, peerId, cursor) {
const ahead = Array.isArray(err.diff?.ahead) ? err.diff.ahead : [];
await recordPeerSchemaGap(peerId, 'catalog', {
ahead, behind: [], senderPortosVersion: data?.portosMeta?.portosVersion ?? null,
- }).catch((e) => console.log(`⚠️ syncOrchestrator: persist catalog schema gap failed: ${e.message}`));
+ }).catch((e) => logFailureWithStack('⚠️ syncOrchestrator: persist catalog schema gap failed', e));
break;
}
throw err;
@@ -404,7 +416,7 @@ async function syncCatalogFromPeer(peer, peerId, cursor) {
// block this cycle.
if (!blockedBySchema) {
await clearPeerSchemaGap(peerId, 'catalog')
- .catch((err) => console.log(`⚠️ syncOrchestrator: clear catalog schema gap failed: ${err.message}`));
+ .catch((err) => logFailureWithStack('⚠️ syncOrchestrator: clear catalog schema gap failed', err));
}
return { catalogSeqs, totalApplied, blockedBySchema };
@@ -532,7 +544,7 @@ async function syncDataCategoryFromPeer(peer, peerId, category, cachedChecksums,
});
if (result.blockedBySchema) {
await recordPeerSchemaGap(peerId, category, result.blockedBySchema)
- .catch((err) => console.log(`⚠️ syncOrchestrator: persist schema gap failed: ${err.message}`));
+ .catch((err) => logFailureWithStack('⚠️ syncOrchestrator: persist schema gap failed', err));
// Don't advance the cached checksum — when the user upgrades, the
// category will look "changed" again and we'll re-try the apply.
return { totalApplied: 0, checksum: null, blockedBySchema: result.blockedBySchema };
@@ -547,7 +559,7 @@ async function syncDataCategoryFromPeer(peer, peerId, category, cachedChecksums,
// either upgraded or the older check was transient. Best-effort; failures
// don't fail the apply (we already merged successfully).
await clearPeerSchemaGap(peerId, category)
- .catch((err) => console.log(`⚠️ syncOrchestrator: clear schema gap failed: ${err.message}`));
+ .catch((err) => logFailureWithStack('⚠️ syncOrchestrator: clear schema gap failed', err));
// Cache the MANIFEST's checksum when we took the per-slot path: it is the
// state we actually diffed against and converged to. The snapshot's own
@@ -731,6 +743,29 @@ export async function syncWithPeer(peer) {
// Track whether the normal `complete` emit fired, so the `finally` can settle
// a card whose sync threw mid-flight instead of leaving it spinning forever.
let completed = false;
+ // Set when the cycle is known to have failed outright, so the `finally`'s
+ // fallback `complete` emit carries the reason instead of a silent zero.
+ let lastSyncErrorEmit = null;
+
+ // Per-cycle failure ledger (#7943). A snapshot category that throws is caught
+ // per-category so one bad category can't abort the rest — which used to make
+ // a fully-broken peer indistinguishable from a healthy one, because the
+ // consolidated cursor write stamped `lastSyncAt` unconditionally afterwards.
+ // We now count what we ATTEMPTED against what FAILED: only a cycle in which
+ // every attempted category failed withholds the timestamp and records the
+ // error. A cycle that attempted nothing (all categories off, or a non-Postgres
+ // install whose enabled categories all need Postgres) is a healthy no-op, not
+ // a failure.
+ let attemptedCategories = 0;
+ const categoryFailures = [];
+ const recordCategoryFailure = (category, err) => {
+ categoryFailures.push(`${category}: ${err?.message ?? String(err)}`);
+ };
+ // Null unless EVERY attempted category failed — the cursor write and the
+ // terminal `complete` emit must agree on that verdict.
+ const cycleFailure = () => (attemptedCategories > 0 && categoryFailures.length === attemptedCategories
+ ? summarizeSyncFailure(categoryFailures)
+ : null);
// Everything after acquiring the lock runs inside the try so the `finally`
// ALWAYS releases `syncingPeers` and emits a terminal `complete` — even if
@@ -762,6 +797,7 @@ export async function syncWithPeer(peer) {
// --- Brain sync (delta-based) ---
let brainResult = { brainSeq: cursor.brainSeq ?? 0, totalApplied: 0 };
if (categories.brain) {
+ attemptedCategories += 1;
brainResult = await syncBrainFromPeer(peer, cursor);
reportApplied('brain', brainResult.totalApplied);
}
@@ -771,6 +807,7 @@ export async function syncWithPeer(peer) {
if (categories.memory) {
const isPostgres = getBackendName() === 'postgres';
if (isPostgres) {
+ attemptedCategories += 1;
memoryResult = await syncMemoryFromPeer(peer, cursor);
reportApplied('memory', memoryResult.totalApplied);
}
@@ -781,6 +818,7 @@ export async function syncWithPeer(peer) {
if (categories.catalog) {
const isPostgres = getBackendName() === 'postgres';
if (isPostgres) {
+ attemptedCategories += 1;
catalogResult = await syncCatalogFromPeer(peer, peerId, cursor);
reportApplied('catalog', catalogResult.totalApplied);
}
@@ -808,11 +846,13 @@ export async function syncWithPeer(peer) {
const cachedChecksums = cursor.checksums || {};
if (enabledDataCats.length > 0) {
+ attemptedCategories += enabledDataCats.length;
const settled = await Promise.allSettled(
enabledDataCats.map(cat =>
syncDataCategoryFromPeer(peer, peerId, cat, cachedChecksums, scopedInstanceId)
.catch(err => {
- console.error(`⚠️ ${cat} sync with ${peer.name} failed: ${err.message}`);
+ logFailureWithStack(`⚠️ ${cat} sync with ${peer.name} failed`, err);
+ recordCategoryFailure(cat, err);
return { totalApplied: 0, checksum: null };
})
)
@@ -853,7 +893,7 @@ export async function syncWithPeer(peer) {
for (const [cat, result] of Object.entries(dataCategoryResults)) {
if (result.checksum) cursors[peerId].checksums[cat] = result.checksum;
}
- cursors[peerId].lastSyncAt = new Date().toISOString();
+ applySyncOutcome(cursors[peerId], cycleFailure());
});
// Log summary
@@ -872,15 +912,65 @@ export async function syncWithPeer(peer) {
+ catalogResult.totalApplied
+ Object.values(dataCategoryResults).reduce((sum, r) => sum + (r?.totalApplied || 0), 0);
completed = true;
- emitSyncProgress({ phase: 'complete', peerId, totalApplied });
+ // The card must not animate to "done" on a cycle where every category
+ // failed — `error` is what lets it render the failure instead (#7943).
+ emitSyncProgress({ phase: 'complete', peerId, totalApplied, error: cycleFailure() });
return { brain: brainResult, memory: memoryResult, catalog: catalogResult, ...dataCategoryResults };
+ } catch (err) {
+ // A delta category (brain/memory/catalog) throws straight out of the body,
+ // so the consolidated cursor write above never runs and `lastSyncAt` is
+ // correctly left alone — but nothing recorded WHY. Persist the reason on
+ // the peer cursor before re-throwing, best-effort: a cursor write that
+ // itself fails must not mask the original error.
+ lastSyncErrorEmit = summarizeSyncFailure([...categoryFailures, err?.message ?? String(err)]);
+ await withCursors((cursors) => {
+ if (!cursors[peerId]) cursors[peerId] = {};
+ applySyncOutcome(cursors[peerId], lastSyncErrorEmit);
+ }).catch((writeErr) => logFailureWithStack('⚠️ syncOrchestrator: persist peer sync failure state failed', writeErr));
+ throw err;
} finally {
syncingPeers.delete(peerId);
// If the sync threw before the normal complete emit, still settle the card
// out of its "syncing" state (a stuck spinner is worse than a silent stop).
- if (!completed) emitSyncProgress({ phase: 'complete', peerId, totalApplied: 0 });
+ if (!completed) emitSyncProgress({ phase: 'complete', peerId, totalApplied: 0, error: lastSyncErrorEmit });
+ }
+}
+
+// Keep the persisted failure string bounded — cursors.json is rewritten every
+// sync cycle, and an unbounded stack-carrying message would grow it without
+// limit. The stack already went to stderr via logFailureWithStack; this is the
+// one-line version the peer card renders.
+const SYNC_ERROR_MAX_CHARS = 300;
+
+function summarizeSyncFailure(messages) {
+ const joined = messages.filter(Boolean).join('; ');
+ if (!joined) return null;
+ return joined.length > SYNC_ERROR_MAX_CHARS
+ ? `${joined.slice(0, SYNC_ERROR_MAX_CHARS - 1)}…`
+ : joined;
+}
+
+/**
+ * Stamp the success/failure half of a per-peer cursor.
+ *
+ * `lastSyncAt` is a SUCCESS marker, not a "we tried" marker — advancing it on a
+ * cycle where every category failed is exactly what made a persistently broken
+ * peer read as healthy (#7943). A failed cycle leaves the previous timestamp
+ * in place (still true: that IS when we last synced) and records the reason.
+ *
+ * @param {object} cursor - The per-peer cursor record, mutated in place
+ * @param {string|null} error - The cycle's failure summary, or null when it succeeded
+ */
+function applySyncOutcome(cursor, error) {
+ if (error) {
+ cursor.lastSyncSucceeded = false;
+ cursor.lastSyncError = error;
+ return;
}
+ cursor.lastSyncSucceeded = true;
+ delete cursor.lastSyncError;
+ cursor.lastSyncAt = new Date().toISOString();
}
/**
@@ -969,7 +1059,7 @@ export function initSyncOrchestrator() {
peerOnlineHandler = (peer) => {
if (!hasAnySyncEnabled(peer)) return;
syncWithPeer(peer).catch(err => {
- console.error(`❌ Sync with ${peer.name} failed: ${err.message}`);
+ logFailureWithStack(`❌ Sync with ${peer.name} failed`, err);
});
};
instanceEvents.on('peer:online', peerOnlineHandler);
@@ -980,20 +1070,20 @@ export function initSyncOrchestrator() {
// sharing a tick keeps the wake-up cost flat.
syncTimer = setInterval(() => {
syncAllPeers().catch(err => {
- console.error(`❌ Periodic sync failed: ${err.message}`);
+ logFailureWithStack('❌ Periodic sync failed', err);
});
// The outer `.catch` is non-optional — runTombstoneSweep is async and
// can reject BEFORE its inner .catch fires (e.g. if the dynamic import
// of tombstoneGc.js itself fails). An unhandled rejection on the
// interval tick would crash the Node process under default settings.
runTombstoneSweep().catch(err => {
- console.error(`❌ Tombstone sweep tick failed: ${err.message}`);
+ logFailureWithStack('❌ Tombstone sweep tick failed', err);
});
// Brain entity tombstones ride the same tick but are gated to their much
// slower grace-period cadence. The outer catch owns unexpected failures
// (such as a rejected dynamic import) so the interval never leaks one.
runBrainTombstoneSweep().catch(err => {
- console.error(`❌ Brain tombstone sweep tick failed: ${err.message}`);
+ logFailureWithStack('❌ Brain tombstone sweep tick failed', err);
});
}, SYNC_INTERVAL_MS);
@@ -1025,7 +1115,7 @@ async function runTombstoneSweep() {
const result = await import('./sharing/tombstoneGc.js')
.then(({ sweepTombstones }) => sweepTombstones())
.catch((err) => {
- console.error(`❌ Tombstone sweep failed: ${err.message}`);
+ logFailureWithStack('❌ Tombstone sweep failed', err);
lastTombstoneSweepAt = 0;
return null;
});
@@ -1057,7 +1147,7 @@ async function runBrainTombstoneSweep() {
const result = await import('./brainTombstoneGc.js')
.then(({ sweepBrainTombstones }) => sweepBrainTombstones())
.catch((err) => {
- console.error(`❌ Brain tombstone sweep failed: ${err.message}`);
+ logFailureWithStack('❌ Brain tombstone sweep failed', err);
return null;
});
if (result && result.pruned > 0) {
diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.js
index 53ec3e7e09..e9a0ee7f21 100644
--- a/server/services/syncOrchestrator.test.js
+++ b/server/services/syncOrchestrator.test.js
@@ -119,7 +119,7 @@ vi.mock('./brainTombstoneGc.js', () => ({
sweepBrainTombstones: vi.fn().mockResolvedValue({ pruned: 0 }),
}));
-import { readJSONFile } from '../lib/fileUtils.js';
+import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';
import { sweepTombstones } from './sharing/tombstoneGc.js';
import { sweepBrainTombstones } from './brainTombstoneGc.js';
import { getPeers } from './instances.js';
@@ -687,6 +687,162 @@ describe('syncOrchestrator', () => {
});
});
+ // #7943: a persistently broken peer used to be indistinguishable from a
+ // healthy one — every failure path logged to stdout with only the message,
+ // and the consolidated cursor write stamped `lastSyncAt` whether or not
+ // anything actually synced.
+ describe('failure visibility (#7943)', () => {
+ const cursorWrites = () => atomicWrite.mock.calls
+ .filter(([path]) => String(path).includes('instances_sync_cursors'))
+ .map(([, payload]) => payload);
+ const lastCursor = () => cursorWrites().at(-1)?.['peer-inst-1'];
+ const completeEvent = () => instanceEvents.emit.mock.calls
+ .filter(([event]) => event === 'sync:progress')
+ .map(([, payload]) => payload)
+ .find((p) => p.phase === 'complete');
+
+ // Serve a category snapshot the sync will try to APPLY. A transport failure
+ // is NOT a failure for these purposes — fetchPeer degrades it to null and an
+ // unreachable peer is a legitimately quiet no-op. What must be visible is an
+ // apply that throws.
+ const serveSnapshots = () => mockFetch.mockImplementation(async (url) => {
+ if (url.includes('/checksum')) return { ok: true, json: async () => ({ checksum: 'remote' }) };
+ if (url.includes('/snapshot')) return { ok: true, json: async () => ({ data: { instances: {} }, checksum: 'remote' }) };
+ return { ok: true, json: async () => ({}) };
+ });
+
+ let dataSync;
+ let errorSpy;
+ beforeEach(async () => {
+ dataSync = await import('./dataSync.js');
+ dataSync.getSupportedCategories.mockReturnValue(['usage']);
+ dataSync.getChecksum.mockResolvedValue({ checksum: 'local' });
+ dataSync.applyRemote.mockResolvedValue({ applied: true, count: 1 });
+ errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ serveSnapshots();
+ });
+
+ afterEach(() => errorSpy.mockRestore());
+
+ it('logs a failed category to stderr WITH a stack frame', async () => {
+ dataSync.applyRemote.mockRejectedValue(new Error('peer refused the usage snapshot'));
+
+ await syncWithPeer({ ...mockPeer, syncCategories: { usage: true } });
+
+ const logged = errorSpy.mock.calls.find(([msg]) => String(msg).includes('usage sync with test-peer failed'));
+ expect(logged).toBeTruthy();
+ // The stack rides as a second argument (logFailureWithStack), so the
+ // failure names a frame instead of collapsing to one message-only line.
+ expect(String(logged[1])).toContain('Error: peer refused the usage snapshot');
+ expect(String(logged[1])).toMatch(/\n\s+at /);
+ });
+
+ it('records lastSyncError and does NOT advance lastSyncAt when every attempted category fails', async () => {
+ readJSONFile.mockImplementation(async () => ({
+ 'peer-inst-1': { lastSyncAt: '2026-01-01T00:00:00.000Z' },
+ }));
+ dataSync.applyRemote.mockRejectedValue(new Error('peer DB was rebuilt'));
+
+ await syncWithPeer({ ...mockPeer, syncCategories: { usage: true } });
+
+ const cursor = lastCursor();
+ expect(cursor.lastSyncSucceeded).toBe(false);
+ expect(cursor.lastSyncError).toContain('peer DB was rebuilt');
+ // The stale timestamp stays exactly as it was — it IS when we last
+ // successfully synced. Advancing it is what made the peer read healthy.
+ expect(cursor.lastSyncAt).toBe('2026-01-01T00:00:00.000Z');
+ });
+
+ it('carries the failure on the terminal sync:progress complete so the card does not animate to done', async () => {
+ dataSync.applyRemote.mockRejectedValue(new Error('inbox disk full'));
+
+ await syncWithPeer({ ...mockPeer, syncCategories: { usage: true } });
+
+ expect(completeEvent().error).toContain('inbox disk full');
+ });
+
+ it('clears lastSyncError and advances lastSyncAt on a clean cycle', async () => {
+ readJSONFile.mockImplementation(async () => ({
+ 'peer-inst-1': {
+ lastSyncAt: '2026-01-01T00:00:00.000Z',
+ lastSyncError: 'peer DB was rebuilt',
+ lastSyncSucceeded: false,
+ },
+ }));
+
+ await syncWithPeer({ ...mockPeer, syncCategories: { usage: true } });
+
+ const cursor = lastCursor();
+ expect(cursor.lastSyncSucceeded).toBe(true);
+ expect(cursor).not.toHaveProperty('lastSyncError');
+ expect(cursor.lastSyncAt).not.toBe('2026-01-01T00:00:00.000Z');
+ expect(completeEvent().error).toBeNull();
+ });
+
+ it('treats a partial failure as a successful cycle — one live category still advances the clock', async () => {
+ dataSync.getSupportedCategories.mockReturnValue(['goals', 'usage']);
+ dataSync.applyRemote.mockImplementation(async (category) => {
+ if (category === 'goals') throw new Error('goals is broken');
+ return { applied: true, count: 1 };
+ });
+ readJSONFile.mockImplementation(async () => ({
+ 'peer-inst-1': { lastSyncAt: '2026-01-01T00:00:00.000Z' },
+ }));
+
+ await syncWithPeer({ ...mockPeer, syncCategories: { goals: true, usage: true } });
+
+ const cursor = lastCursor();
+ expect(cursor.lastSyncSucceeded).toBe(true);
+ expect(cursor).not.toHaveProperty('lastSyncError');
+ expect(cursor.lastSyncAt).not.toBe('2026-01-01T00:00:00.000Z');
+ });
+
+ it('persists lastSyncError when a delta category throws straight out of the sync body', async () => {
+ // brain/memory/catalog reject out of syncWithPeer rather than being caught
+ // per-category, so the consolidated cursor write never runs — nothing used
+ // to record WHY the peer stopped syncing.
+ readJSONFile.mockImplementation(async () => ({
+ 'peer-inst-1': { brainSeq: 7, lastSyncAt: '2026-01-01T00:00:00.000Z' },
+ }));
+ mockFetch.mockImplementation(async (url) => {
+ if (url.includes('/api/brain/sync')) {
+ return { ok: true, json: async () => ({ changes: [{ id: 'b1' }], maxSeq: 8, hasMore: false }) };
+ }
+ return { ok: true, json: async () => ({}) };
+ });
+ applyBrainChanges.mockRejectedValue(new Error('brain log unreadable'));
+
+ await expect(syncWithPeer({ ...mockPeer, syncCategories: { brain: true } }))
+ .rejects.toThrow('brain log unreadable');
+
+ const cursor = lastCursor();
+ expect(cursor.lastSyncSucceeded).toBe(false);
+ expect(cursor.lastSyncError).toContain('brain log unreadable');
+ expect(cursor.lastSyncAt).toBe('2026-01-01T00:00:00.000Z');
+ // The pre-existing cursor is preserved, not clobbered by the failure write.
+ expect(cursor.brainSeq).toBe(7);
+ });
+
+ it('withholds our local failure string from the peer-facing cursorForYou projection', async () => {
+ // /api/instances/sync-status is reachable by any tailnet machine, and the
+ // stored message is whatever an exception on THIS host happened to say.
+ readJSONFile.mockImplementation(async () => ({
+ 'peer-A': {
+ brainSeq: 88,
+ lastSyncAt: '2026-01-01T00:00:00.000Z',
+ lastSyncError: 'ENOENT: /Users/someone/private/path',
+ lastSyncSucceeded: false,
+ },
+ }));
+
+ const status = await getSyncStatus({ forPeer: 'peer-A' });
+
+ expect(status.cursorForYou).toEqual({ brainSeq: 88, lastSyncAt: '2026-01-01T00:00:00.000Z' });
+ // The self-view (our own browser, which renders the peer card) keeps it.
+ expect(status.cursors['peer-A'].lastSyncError).toBe('ENOENT: /Users/someone/private/path');
+ });
+ });
+
describe('sync:progress events', () => {
it('emits start → applied → complete around a sync that moves records', async () => {
mockFetch
@@ -719,7 +875,7 @@ describe('syncOrchestrator', () => {
.filter(([event]) => event === 'sync:progress')
.map(([, payload]) => payload);
expect(progress).toContainEqual({ phase: 'start', peerId: 'peer-inst-1' });
- expect(progress).toContainEqual({ phase: 'complete', peerId: 'peer-inst-1', totalApplied: 0 });
+ expect(progress).toContainEqual({ phase: 'complete', peerId: 'peer-inst-1', totalApplied: 0, error: expect.any(String) });
// Lock released: a subsequent sync is NOT short-circuited by syncingPeers.
mockFetch.mockResolvedValue({ ok: true, json: async () => ({ changes: [], maxSeq: 0, hasMore: false }) });
@@ -739,7 +895,7 @@ describe('syncOrchestrator', () => {
.map(([, payload]) => payload);
const completes = progress.filter(p => p.phase === 'complete');
// Exactly one complete, and no spurious second one from the finally guard.
- expect(completes).toEqual([{ phase: 'complete', peerId: 'peer-inst-1', totalApplied: 0 }]);
+ expect(completes).toEqual([{ phase: 'complete', peerId: 'peer-inst-1', totalApplied: 0, error: null }]);
// No `applied` events when nothing moved.
expect(progress.some(p => p.phase === 'applied')).toBe(false);
});