Skip to content

Commit 165b689

Browse files
committed
fix(link): allow catalog sync before signal restoration
1 parent 74d1b98 commit 165b689

5 files changed

Lines changed: 72 additions & 15 deletions

File tree

‎src/client/restore-ownership.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { withConfigMutationLockSync } from "../config";
2-
import { assertClientConnectionUnchanged, assertNoClientDisconnectPending, pendingClientConnectMayOwnToken, readClientConnectionState } from "./state";
2+
import { assertNoClientDisconnectPending, pendingClientConnectMayOwnToken, readClientConnectionState } from "./state";
33
import type { OcxClientConnectionConfig } from "../types";
44

55
export type RestoreBoundaryOwnership = "restore" | "hub-owned" | "unproven";
@@ -22,9 +22,16 @@ export function inspectStopRestoreOwnership(read = readClientConnectionState): R
2222
} catch { return "unproven"; }
2323
}
2424

25+
function restoreConnectionSnapshot(connection: OcxClientConnectionConfig) {
26+
// Normal sync changes these observations, not restoration ownership. All other
27+
// fields, including priorCatalog and future connection fields, remain guarded.
28+
const { catalogFingerprint: _fingerprint, catalogSyncedAt: _syncedAt, ...snapshot } = connection;
29+
return snapshot;
30+
}
31+
2532
/** C is reentrant inside N/C; this never acquires L or N. No lease crosses an await. */
2633
export function stopRestoreWriteGuard(expectedConnection?: OcxClientConnectionConfig) {
27-
const expected = expectedConnection && structuredClone(expectedConnection);
34+
const expected = expectedConnection && restoreConnectionSnapshot(structuredClone(expectedConnection));
2835
let boundary: RestoreBoundaryOwnership = "restore";
2936
return {
3037
boundary: () => boundary,
@@ -37,7 +44,10 @@ export function stopRestoreWriteGuard(expectedConnection?: OcxClientConnectionCo
3744
if (boundary === "restore" && expected) {
3845
try {
3946
if (expected.pendingOperation) throw new Error("client_rotation_pending");
40-
assertClientConnectionUnchanged(expected);
47+
const current = readClientConnectionState();
48+
if (current.kind !== "connected" || !Bun.deepEquals(restoreConnectionSnapshot(current.value), expected, true)) {
49+
throw new Error("client_connection_changed");
50+
}
4151
} catch { boundary = "unproven"; }
4252
}
4353
if (boundary !== "restore") throw new StopRestoreOwnershipError(boundary);

‎structure/remote-link.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Remote Link
22

3-
Orderly signals in an unsupervised Link Child call `src/client/stop-routing.ts` before releasing the listener. It reuses native Codex config/catalog/history restoration and managed Grok removal; the saved connection and credentials remain. `src/client/restore-ownership.ts` optionally binds each write under C to the immutable served connection, including selection and rotation state. A changed owner, pending transition or unverified journal refuses remaining writes. Service/desktop supervision, sibling ownership, accepted restart/recycle handoff and outstanding parent teardown receipts preserve integrations for their existing owners. Signal shutdown waits for an accepted restart to hand off or finish rolling back; a pending admission owns no routing. It refuses new or pending restart admission with `409 runtime_stopping`; normal bound restart remains unchanged. After an ordinary unsupervised stop, start and run `ocx sync --restart-codex`; start alone does not reapply routing. Coverage: `tests/clients/client-link-stop.test.ts`, `tests/clients/client-runtime-restart.test.ts`.
3+
Orderly signals in an unsupervised Link Child call `src/client/stop-routing.ts` before releasing the listener. It reuses native Codex config/catalog/history restoration and managed Grok removal; the saved connection and credentials remain. `src/client/restore-ownership.ts` optionally binds each write under C to the immutable served connection, including selection and rotation state. Only `catalogFingerprint` and `catalogSyncedAt`, updated by normal catalog sync, are excluded from this restore-specific comparison; `priorCatalog` remains guarded and the shared full-snapshot CAS for asynchronous connection work is unchanged. A changed owner, pending transition or unverified journal refuses remaining writes. Service/desktop supervision, sibling ownership, accepted restart/recycle handoff and outstanding parent teardown receipts preserve integrations for their existing owners. Signal shutdown waits for an accepted restart to hand off or finish rolling back; a pending admission owns no routing. It refuses new or pending restart admission with `409 runtime_stopping`; normal bound restart remains unchanged. After an ordinary unsupervised stop, start and run `ocx sync --restart-codex`; start alone does not reapply routing. Coverage: `tests/clients/client-link-stop.test.ts`, `tests/clients/client-runtime-restart.test.ts`.
44

55
`src/link/` owns the building blocks for linking OpenCodex machines over SSH. The pure modules start no process, open no socket and schedule no timer on import.
66

‎structure/runtime.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -175,9 +175,9 @@ described in [OpenAI quota ownership](providers/openai-tiers.md#public-provider-
175175

176176
`ocx start` refuses a duplicate PID, starts the proxy, writes `~/.opencodex/ocx.pid` and
177177
`runtime-port.json` through `src/config/process-state.ts`, syncs Codex config/catalog, then serves
178-
until shutdown. Standalone shutdown restores native Codex; connected hub clients preserve connection-owned Codex routing, catalog and Grok config across `ocx stop`/`ocx start`. An ordinary runtime rechecks persisted connection ownership in its exit cleanup: a connected Remote Link Child remains subject to the existing native Codex/Grok restoration decisions. Graceful signal shutdown runs that synchronous cleanup after draining and before releasing the listener. Sibling, recycling and service-managed exit exclusions remain intact; receipt-backed API stop may explicitly defer shared restoration to the stopping client. Only an accepted receipt deferral in `src/server/stop-teardown.ts` latches that process's exit deferral; CLI exit cleanup keeps native Codex and Grok restoration with the parent, while still stopping background owners and removing runtime records. Client start does not re-inject routing: use `ocx sync --restart-codex` to reapply it, or `ocx disconnect` to release connection ownership. A sibling instance beside a live proxy ([Codex home](codex-home.md#codex-home)) syncs and restores nothing, and `ocx stop` of a runtime whose record carries `siblingOfPort` skips the shared teardown. `src/cli/index.ts` resolves same-home ownership, then checks shared client hints through the cross-home owner helper, then reconciles the journal only when no sibling is marked. An indeterminate cross-home result refuses a new start before binding or publication, rather than persisting an unverified sibling topology; the next start performs fresh discovery. Service mode sets Native client signal cleanup follows the [served-connection and supervisor boundaries](remote-link.md); client update stops use full parent restoration because client start cannot discharge standalone handover receipts.
178+
until shutdown. Standalone shutdown restores native Codex; connected hub clients preserve connection-owned Codex routing, catalog and Grok config across `ocx stop`/`ocx start`. An ordinary runtime rechecks persisted connection ownership in its exit cleanup: a connected Remote Link Child remains subject to the existing native Codex/Grok restoration decisions. Graceful signal shutdown runs that synchronous cleanup after draining and before releasing the listener. Sibling, recycling and service-managed exit exclusions remain intact; receipt-backed API stop may explicitly defer shared restoration to the stopping client. Only an accepted receipt deferral in `src/server/stop-teardown.ts` latches that process's exit deferral; CLI exit cleanup keeps native Codex and Grok restoration with the parent, while still stopping background owners and removing runtime records. Client start does not re-inject routing: use `ocx sync --restart-codex` to reapply it, or `ocx disconnect` to release connection ownership. A sibling instance beside a live proxy ([Codex home](codex-home.md#codex-home)) syncs and restores nothing, and `ocx stop` of a runtime whose record carries `siblingOfPort` skips the shared teardown. `src/cli/index.ts` resolves same-home ownership, then checks shared client hints through the cross-home owner helper, then reconciles the journal only when no sibling is marked. An indeterminate cross-home result refuses a new start before binding or publication, rather than persisting an unverified sibling topology; the next start performs fresh discovery. Service mode sets
179179
`OCX_SERVICE=1`, so managed restarts do not repeatedly restore/reinject; scheduler failure diagnostics follow the [service command contract](ops/service-and-sidecars.md#background-service-command-selection). Explicit service stop and
180-
uninstall still restore. `src/service/cli.ts` removes the service token on uninstall only when persisted client state is disconnected and no pending connect marker owns the newly issued key. `src/client/connect.ts` publishes that fingerprint marker before the key, then clears it with the connection commit or rollback under the client lifecycle and config mutation locks. Connected, invalid, or mismatched client state retains an existing token. A valid pending marker retains only its matching fingerprint; an older marker does not own a replacement service key. An absent token is reported as absent; unsafe, malformed, or unreadable markers and lock, state-read, or deletion failures leave cleanup unverified.
180+
uninstall still restore. Native client signal cleanup follows the [served-connection and supervisor boundaries](remote-link.md); client update stops use full parent restoration because client start cannot discharge standalone handover receipts. `src/service/cli.ts` removes the service token on uninstall only when persisted client state is disconnected and no pending connect marker owns the newly issued key. `src/client/connect.ts` publishes that fingerprint marker before the key, then clears it with the connection commit or rollback under the client lifecycle and config mutation locks. Connected, invalid, or mismatched client state retains an existing token. A valid pending marker retains only its matching fingerprint; an older marker does not own a replacement service key. An absent token is reported as absent; unsafe, malformed, or unreadable markers and lock, state-read, or deletion failures leave cleanup unverified.
181181
`src/cli/tray-proxy.ts` coordinates `ocx restart` and tray restart. A second start requires proof the prior attempt never launched or its child exited, plus confirmed absence under a fresh bounded discovery window; a missing health response alone is insufficient. After an accepted restart, polling continues through uncertain observations until its deadline and requires a new runtime PID on the same port. If the old proxy then disappears, explicit recovery starts it regardless of the Codex autostart preference; a skipped recovery fails rather than reporting success. The Windows tray startup-health probe in `src/tray/windows-tray.ps1` requests termination at its 30-second deadline without waiting on the UI thread. It retains the process through later ticks until actual exit and both redirected readers settle; replacements cannot start while that reference is held. Launch setup failures follow the same cleanup. Tray shutdown alone waits at most 500 ms before disposal.
182182

183183
`ocx restart` also restarts a connected client runtime, which serves the same bound `POST /api/system/restart` from its client listener; the CLI sends that request only while the client's 90-second restart budget still fits before replacement observation ends (`CLIENT_RESTART_REQUEST_MIN_REMAINING_MS`), and reports a supervised client's `409 restart_supervised` as "not performed, runtime kept". See [Remote Link](remote-link.md) for the rollback.

‎tests/clients/client-link-stop.test.ts‎

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ async function runStop(options: Record<string, unknown>) {
3030
} else expect({ exit, stderr }, stdout).toEqual({ exit: 0, stderr: "" });
3131
const report = JSON.parse(readFileSync(join(home, "result.json"), "utf8"));
3232
const atExit = JSON.parse(readFileSync(join(home, "exit.json"), "utf8"));
33-
for (const field of ["after", "profileAfter", "journalRetained", "catalogAfter", "grokAfter", "protectedUnchanged"]) {
33+
for (const field of ["after", "profileAfter", "journalRetained", "journalHomeBound", "catalogAfter", "grokAfter", "protectedUnchanged"]) {
3434
expect(atExit[field], `no late restoration after listener release: ${field}`).toEqual(report[field]);
3535
}
3636
return report;
@@ -54,10 +54,26 @@ for (const signal of process.platform === "win32" ? ["SIGINT", "SIGTERM"] : ["SI
5454
}, 20_000);
5555
}
5656

57-
test.skipIf(process.platform === "win32")("a real POSIX SIGTERM restores before listener release", async () => {
58-
const report = await runStop({ mode: "runtime", osSignal: true });
57+
test.skipIf(process.platform === "win32")("a real POSIX SIGTERM restores after catalog sync before listener release", async () => {
58+
const report = await runStop({ mode: "runtime", osSignal: true, syncBeforeStop: true });
59+
expect(report.syncEvidence).toEqual({ changedFields: ["catalogFingerprint", "catalogSyncedAt"], fullCasRefused: true, catalogWritten: true, injected: true, journalHomeBound: true });
5960
expect(report.after).toBe('model = "native"\n');
60-
expect(report.journalRetained).toBe(false);
61+
expect(report.profileAfter).toBeNull();
62+
expect(report.journalHomeBound).toBe(false);
63+
expect(report.catalogAfter.models).toEqual([{ slug: "fixture-native", visibility: "list" }]);
64+
expect(report.grokAfter).toBe('theme = "fixture"\n');
65+
}, 20_000);
66+
67+
test("native Link signal restores after real catalog sync without weakening the full snapshot CAS", async () => {
68+
const report = await runStop({ mode: "runtime", syncBeforeStop: true });
69+
expect(report.syncEvidence).toEqual({ changedFields: ["catalogFingerprint", "catalogSyncedAt"], fullCasRefused: true, catalogWritten: true, injected: true, journalHomeBound: true });
70+
expect(report.after).toBe('model = "native"\n');
71+
expect(report.profileAfter).toBeNull();
72+
// Reinjection preserves the first hash: field-level restore retains its recovery
73+
// snapshot but releases the home binding, rather than deleting recovery evidence.
74+
expect(report.journalRetained).toBe(true);
75+
expect(report.journalHomeBound).toBe(false);
76+
expect(report.protectedUnchanged).toBe(true);
6177
expect(report.catalogAfter.models).toEqual([{ slug: "fixture-native", visibility: "list" }]);
6278
expect(report.grokAfter).toBe('theme = "fixture"\n');
6379
}, 20_000);
@@ -182,13 +198,18 @@ test("a scheduled recycle cannot skip restoration or spawn after signal shutdown
182198
expect(report.grokAfter).toBe('theme = "fixture"\n');
183199
}, 20_000);
184200

185-
for (const mutation of ["connection", "selection", "rotation"]) {
201+
for (const mutation of ["connection", "selection", "rotation", "hub", "prior-catalog", "api-key", "token", "management", "link-id"]) {
186202
test(`served-connection guard rechecks ${mutation} at each write and freezes its snapshot`, async () => {
187203
const report = await runStop({ mode: "guard", mutation });
188-
expect(report.result).toEqual({ writes: ["before-change"], refused: true, boundary: "unproven" });
204+
expect(report.result).toEqual({ writes: ["before-change"], refused: true, boundary: mutation === "hub" ? "hub-owned" : "unproven" });
189205
expect(report.after).toBe(report.before);
190206
expect(report.journalRetained).toBe(true);
191207
expect(report.catalogAfter).toEqual(JSON.parse(report.catalogBefore));
192208
expect(report.grokAfter).toBe(report.grokBefore);
193209
});
194210
}
211+
212+
test("served-connection guard permits catalog sync metadata at a later write", async () => {
213+
const report = await runStop({ mode: "guard", mutation: "catalog" });
214+
expect(report.result).toEqual({ writes: ["before-change", "after-change"], refused: false, boundary: "restore" });
215+
});

0 commit comments

Comments
 (0)