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([issue-1328]): treat a peer's unknown-kind 400 as a schema-version block, not a bare http-400 retry

[._.]/ Adam Eivy252d869ca7d0
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 9ec21eb2cd..438e63d4aa 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -1024,6 +1024,43 @@ export async function pushRecordToPeer(sub, options = {}) {
res = await postPayload(legacyPayload);
}
}
+ // UNKNOWN-KIND 400 → schema-version block (NOT a bare http-400 retry). When we
+ // introduce a NEW federated record kind (authors did this; mediaCollection had
+ // the same gap when it landed), a peer on an older PortOS whose
+ // `peerSyncPushSchema` discriminated union has no arm for that `kind` rejects
+ // the push at Zod validation with a generic 400 — BEFORE `applyIncomingPush`'s
+ // version gate (the 409 path below) ever runs. So unlike the strip-retry above
+ // there's no smuggled envelope key to drop: the record KIND itself is what the
+ // peer can't parse, and retrying changes nothing. Treat it like the 409:
+ // persist an (empty-gap) `peer-pre-feature` block so the SchemaGapBadge surfaces
+ // "peer needs to update PortOS to sync <kind>" and the edit-push cooldown engages,
+ // instead of letting the sub churn as a bare `http-400` the UI never explains.
+ // The block clears on the next successful push once the peer upgrades (same
+ // recovery as the 409 path). Signal: a VALIDATION_ERROR whose offending field is
+ // the `kind` discriminator — a value WE always send as a valid literal, so the
+ // only reason a receiver faults on `kind` is that its schema doesn't know this
+ // record kind yet (Zod reports `path: ['kind']` with an "Invalid discriminator
+ // value" / "Invalid enum value" message; `validateRequest` keeps path + message).
+ if (res && res.status === 400) {
+ const errBody = await res.clone().json().catch(() => null);
+ const details = Array.isArray(errBody?.context?.details) ? errBody.context.details : [];
+ const unknownKind = errBody?.code === 'VALIDATION_ERROR'
+ && details.some((d) => d?.path === 'kind' && /discriminator|enum/i.test(d?.message || ''));
+ if (unknownKind) {
+ await persistSchemaVersionBlock(sub.id, {
+ ahead: [],
+ behind: [],
+ peerPortosVersion: null,
+ peerSchemaVersions: null,
+ reason: 'peer-pre-feature',
+ });
+ console.warn(
+ `⚠️ peerSync: ${peer.name || peer.instanceId} rejected push — its PortOS doesn't recognize the ` +
+ `'${sub.recordKind}' record kind yet. Re-tries pause until they upgrade.`,
+ );
+ return { pushed: false, reason: 'peer-schema-behind', blockedBySchema: true };
+ }
+ }
// 409 with `code: SCHEMA_VERSION_AHEAD` means the receiver is on an OLDER
// PortOS and can't parse our newer storage layout. Persist the gap on the
// subscription so the Instances UI can surface "Peer X needs to update
@@ -1186,7 +1223,7 @@ async function persistPushSuccess(subId, hash, { confirmedAtMs = Date.now() } =
* what the peer has that we don't — informational) along with the peer's
* PortOS version string for the user-visible message.
*/
-async function persistSchemaVersionBlock(subId, { ahead, behind, peerPortosVersion, peerSchemaVersions }) {
+async function persistSchemaVersionBlock(subId, { ahead, behind, peerPortosVersion, peerSchemaVersions, reason = 'schema-version-ahead' }) {
// Capture peerId inside the lock so the emitted event carries it — lets each
// Instances PeerCard filter on its own peer instead of every card refetching.
let blockedPeerId = null;
@@ -1198,6 +1235,13 @@ async function persistSchemaVersionBlock(subId, { ahead, behind, peerPortosVersi
const now = new Date().toISOString();
sub.blockedBySchema = {
detectedAt: now,
+ // `schema-version-ahead` = the 409 version-gate path (the peer parsed our
+ // envelope but its per-category gate rejected an ahead schema). `peer-pre-feature`
+ // = the 400 unknown-kind path below (the peer's push schema has no arm for
+ // this record kind at all, so it 400s at Zod before the gate runs). Both
+ // surface the same SchemaGapBadge + engage the same cooldown; the marker just
+ // distinguishes them in state/logs.
+ reason,
ahead: Array.isArray(ahead) ? ahead : [],
behind: Array.isArray(behind) ? behind : [],
peerPortosVersion: peerPortosVersion || null,
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 08c5ae17ed..23375a8bab 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -3000,6 +3000,89 @@ describe('peerSync', () => {
// Only ONE call — no retry.
expect(vi.mocked(peerFetch).mock.calls.length).toBe(1);
});
+
+ it('records a peer-pre-feature blockedBySchema marker when a peer rejects an unknown record kind (400 invalid discriminator)', async () => {
+ // A peer on an older PortOS whose `peerSyncPushSchema` discriminated
+ // union has no arm for this record kind (authors / mediaCollection when
+ // they first landed) rejects the push at Zod with a generic 400 whose
+ // offending field is the `kind` discriminator — BEFORE its version gate
+ // (the 409 path) ever runs. The sender must NOT treat this as a bare
+ // http-400 (which churns silently); it routes the sub into an empty-gap
+ // schema-version block so the SchemaGapBadge surfaces "peer needs to
+ // update" and the edit-push cooldown engages, exactly like the 409 path.
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });
+ const errBody = { ok: false, status: 400, json: async () => ({
+ code: 'VALIDATION_ERROR',
+ message: 'Validation failed',
+ context: { details: [{ path: 'kind', message: "Invalid discriminator value. Expected 'universe' | 'series'" }] },
+ }) };
+ errBody.clone = () => errBody;
+ vi.mocked(peerFetch).mockResolvedValueOnce(errBody);
+ const sub = await subscribePeer({
+ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',
+ }, { adoptedFromReverse: true });
+ const result = await pushRecordToPeer(sub);
+ expect(result.pushed).toBe(false);
+ expect(result.reason).toBe('peer-schema-behind');
+ expect(result.blockedBySchema).toBe(true);
+ // No retry — the kind itself is unrecognized, so re-sending changes nothing.
+ expect(vi.mocked(peerFetch).mock.calls.length).toBe(1);
+ // Block persisted with the pre-feature marker + an empty gap (the peer
+ // 400'd before sending any schemaVersions to populate ahead/behind).
+ const after = await findPeerSubscription('peer-a', 'universe', 'u1');
+ expect(after.blockedBySchema).toBeDefined();
+ expect(after.blockedBySchema.reason).toBe('peer-pre-feature');
+ expect(after.blockedBySchema.ahead).toEqual([]);
+ expect(after.blockedBySchema.behind).toEqual([]);
+ expect(after.blockedBySchema.peerPortosVersion).toBeNull();
+ expect(typeof after.blockedBySchema.detectedAt).toBe('string');
+ // lastPushedHash must NOT have advanced — the record didn't land.
+ expect(after.lastPushedHash).toBeFalsy();
+ });
+
+ it('engages the push cooldown after a pre-feature block so the next edit-push short-circuits', async () => {
+ // The pre-feature block must behave like the 409 block: a subsequent
+ // push (no bypass) short-circuits on the cooldown instead of re-probing
+ // the peer on every local edit.
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });
+ const errBody = { ok: false, status: 400, json: async () => ({
+ code: 'VALIDATION_ERROR',
+ message: 'Validation failed',
+ context: { details: [{ path: 'kind', message: 'Invalid discriminator value. Expected ...' }] },
+ }) };
+ errBody.clone = () => errBody;
+ vi.mocked(peerFetch).mockResolvedValue(errBody);
+ const sub = await subscribePeer({
+ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',
+ }, { adoptedFromReverse: true });
+ await pushRecordToPeer(sub);
+ const callsAfterFirst = vi.mocked(peerFetch).mock.calls.length;
+ const blocked = await findPeerSubscription('peer-a', 'universe', 'u1');
+ const result = await pushRecordToPeer(blocked);
+ expect(result.reason).toBe('peer-schema-behind-cooldown');
+ expect(vi.mocked(peerFetch).mock.calls.length).toBe(callsAfterFirst);
+ });
+
+ it('does NOT misclassify a non-discriminator field 400 as a pre-feature block', async () => {
+ // Guard: only a `kind`-path discriminator/enum error is the unknown-kind
+ // signal. A 400 on any other field (oversized record, etc.) stays a
+ // genuine http-400 — not a silently-swallowed schema block.
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });
+ const errBody = { ok: false, status: 400, json: async () => ({
+ code: 'VALIDATION_ERROR',
+ message: 'Validation failed',
+ context: { details: [{ path: 'record.name', message: 'String too long' }] },
+ }) };
+ errBody.clone = () => errBody;
+ vi.mocked(peerFetch).mockResolvedValueOnce(errBody);
+ const sub = await subscribePeer({
+ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',
+ }, { adoptedFromReverse: true });
+ const result = await pushRecordToPeer(sub);
+ expect(result.reason).toBe('http-400');
+ const after = await findPeerSubscription('peer-a', 'universe', 'u1');
+ expect(after.blockedBySchema).toBeUndefined();
+ });
});
});