Skip to content

Commit 3d26b78

Browse files
roodboiclaude
andcommitted
fix(native): re-observe a sandbox-less bridge endpoint instead of refusing adopted Compose (HACK-1421)
Docker lists an endpoint that is not joined to a sandbox as `ep-<endpoint>` in a bridge's `.Containers`, for a moment on every container start and exit. The bridge read takes no container lock, so the retained-resource binding proof could see that key while a job or service changed state. The member check accepted only 64-hex container IDs, so it refused the binding identity immediately. Inside an adopted start, that refusal surfaces as a closed E_CONFIG_INVALID with no ordered-refusal detail, which matches the flaky native-compose-adoption-job-worktrees failure at alpha-start-7. A placeholder member is now never attributed, admitted or saved. It marks that bridge read as transient, and the existing snapshot loop discards the observation and re-reads under the same aggregate deadline and output allowance. A placeholder that persists until the deadline still refuses, and any other non-ID key still refuses identity at once. The completed-job scenario's cli-result line also names a fixed refusal message by closed token (refusal=legacy-state, legacy-changed, input-access, ...), so a recurrence says which owner refused without any value. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 0ca0e45 commit 3d26b78

5 files changed

Lines changed: 259 additions & 28 deletions

‎docs/reference/native-compose-adoption.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,10 @@ Container observations bracket the active-member read. If an original changes
354354
running state while all immutable facts remain verified, the mixed observation
355355
is discarded within the same aggregate deadline and output allowance. Foreign
356356
members, replaced identities and stable membership mismatches refuse immediately.
357+
Docker keys an endpoint that is not joined to a sandbox as `ep-<endpoint>`. This
358+
happens for a moment while any container starts or exits. Such a member is never
359+
attributed, admitted or saved: the observation is discarded and re-read within
360+
the same deadline, and a placeholder that persists until the deadline refuses.
357361
This is not an atomic daemon snapshot: delayed endpoint removal can still refuse,
358362
and fresh successful job completion remains the scheduler's separate decision.
359363
The Docker routing environment is captured for later comparison. Queries never

‎src/lib/native-compose-adoption-binding.ts‎

Lines changed: 54 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,13 @@ import {
6868
import type { LegacyComposeSourceBindIntent } from "./native-config-import-storage.ts";
6969

7070
const ID = /^[a-f0-9]{64}$/;
71+
/**
72+
* Docker lists an endpoint that is not joined to a sandbox as `ep-<endpoint>`
73+
* in a bridge's `.Containers`. That happens for a moment on every container
74+
* start (endpoint created, sandbox not yet joined) and exit (sandbox left,
75+
* endpoint not yet deleted), and the bridge read takes no container lock.
76+
*/
77+
const ENDPOINT_PLACEHOLDER = /^ep-[a-f0-9]{64}$/;
7178
const NAME = /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,254}$/;
7279
const ENGINE_ID = /^[a-zA-Z0-9:._-]{1,128}$/;
7380
const TIME = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/;
@@ -708,6 +715,28 @@ function containerRows(
708715
})
709716
.sort((a, b) => a.service.localeCompare(b.service));
710717
}
718+
/**
719+
* Split a bridge's `.Containers` keys into container IDs and a transient flag.
720+
* A placeholder is never attributed, admitted or retained: it only marks this
721+
* bridge read as mid-transition so the caller re-observes under its original
722+
* deadline. Any other non-ID key, or a duplicate, refuses as before.
723+
*/
724+
function bridgeMembers(value: unknown): {
725+
readonly ids: readonly string[];
726+
readonly transient: boolean;
727+
} {
728+
requireValue(
729+
Array.isArray(value) &&
730+
value.every(
731+
(key) =>
732+
typeof key === "string" &&
733+
(ID.test(key) || ENDPOINT_PLACEHOLDER.test(key))
734+
) &&
735+
new Set(value).size === value.length
736+
);
737+
const ids = value.filter((key: string) => ID.test(key));
738+
return { ids, transient: ids.length !== value.length };
739+
}
711740
function networkRow(
712741
rows: readonly Record<string, unknown>[],
713742
intent: LegacyComposeStorageIntent
@@ -736,11 +765,9 @@ function networkRow(
736765
timestamp(row.createdAt) &&
737766
row.driver === "bridge" &&
738767
row.scope === "local" &&
739-
row.internal === (intent.ownedNetwork?.internal ?? false) &&
740-
Array.isArray(row.containers) &&
741-
row.containers.every((id) => typeof id === "string" && ID.test(id)) &&
742-
new Set(row.containers).size === row.containers.length
768+
row.internal === (intent.ownedNetwork?.internal ?? false)
743769
);
770+
const members = bridgeMembers(row.containers);
744771
return {
745772
network: {
746773
id: row.id,
@@ -753,7 +780,8 @@ function networkRow(
753780
}
754781
: {}),
755782
},
756-
containerIds: row.containers,
783+
containerIds: members.ids,
784+
transient: members.transient,
757785
};
758786
}
759787
function pluralNetworkRows(
@@ -762,7 +790,9 @@ function pluralNetworkRows(
762790
): {
763791
readonly networks: readonly LegacyComposeVerifiedNetwork[];
764792
readonly members: ReadonlyMap<string, readonly string[]>;
793+
readonly transient: boolean;
765794
} {
795+
let transient = false;
766796
const declared = intent.ownedNetworks?.networks;
767797
requireValue(declared && declared.length === 2 && rows.length === 2);
768798
requireValue(
@@ -794,7 +824,8 @@ function pluralNetworkRows(
794824
]);
795825
const expected = declared.find((network) => network.name === row.name);
796826
const id = row.id;
797-
const rowMembers = row.containers;
827+
const rowMembers = bridgeMembers(row.containers);
828+
transient ||= rowMembers.transient;
798829
requireValue(
799830
expected &&
800831
typeof id === "string" &&
@@ -805,16 +836,11 @@ function pluralNetworkRows(
805836
row.internal === expected.internal &&
806837
row.driver === "bridge" &&
807838
row.scope === "local" &&
808-
timestamp(row.createdAt) &&
809-
Array.isArray(rowMembers) &&
810-
rowMembers.every(
811-
(member) => typeof member === "string" && ID.test(member)
812-
) &&
813-
new Set(rowMembers).size === rowMembers.length
839+
timestamp(row.createdAt)
814840
);
815841
ids.add(id);
816842
names.add(expected.name);
817-
members.set(expected.logical, [...rowMembers].sort());
843+
members.set(expected.logical, [...rowMembers.ids].sort());
818844
return {
819845
id,
820846
name: expected.name,
@@ -824,7 +850,7 @@ function pluralNetworkRows(
824850
};
825851
})
826852
.sort((a, b) => a.logical.localeCompare(b.logical));
827-
return { networks, members };
853+
return { networks, members, transient };
828854
}
829855
async function engine(probe: Probe) {
830856
const rows = lines(
@@ -981,8 +1007,14 @@ async function inspectResources(
9811007
)
9821008
);
9831009
}
984-
return { plural, single };
1010+
return {
1011+
plural,
1012+
single,
1013+
transient: plural?.transient === true || single?.transient === true,
1014+
};
9851015
};
1016+
// The first bridge read only fixes identity and refuses foreign members; the
1017+
// loop below always re-reads, so a placeholder here needs no extra scan.
9861018
let { plural, single } = await readNetwork();
9871019
const networkIdentity = JSON.stringify(plural?.networks ?? single?.network);
9881020
let ingress: NativeComposeIngressBinding | undefined;
@@ -1019,18 +1051,21 @@ async function inspectResources(
10191051
let containerFacts: readonly Record<string, unknown>[];
10201052
let containers: LegacyComposeVerifiedContainer[];
10211053
for (;;) {
1022-
({ plural, single } = await readNetwork());
1054+
let transient: boolean;
1055+
({ plural, single, transient } = await readNetwork());
10231056
requireValue(
10241057
JSON.stringify(plural?.networks ?? single?.network) === networkIdentity
10251058
);
10261059
const after = await readContainers();
10271060
// Both scans validate all labels, mounts and configured attachments against
1028-
// the same originals. Only running state is transient; stopped aliases may
1029-
// be absent under the existing contract. No completion authority is granted.
1061+
// the same originals. Only running state and a sandbox-less endpoint
1062+
// placeholder are transient; stopped aliases may be absent under the
1063+
// existing contract. No completion authority is granted.
10301064
requireValue(JSON.stringify(after.containers) === containerIdentity);
10311065
if (
1066+
transient ||
10321067
JSON.stringify(before.facts.map((row) => [row.id, row.running])) !==
1033-
JSON.stringify(after.facts.map((row) => [row.id, row.running]))
1068+
JSON.stringify(after.facts.map((row) => [row.id, row.running]))
10341069
) {
10351070
// Reuse this aggregate probe's original deadline and output allowance.
10361071
// Never accept mixed membership, reset a timer, or retry an identity error.

‎tests/e2e/scenarios/native-compose-adoption-job-diagnostics.ts‎

Lines changed: 51 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { isRecord } from "../../../src/lib/guards.ts";
22
import type { LegacyComposeOrderedRefusal } from "../../../src/lib/native-compose-adoption-diagnostics.ts";
3+
import { LegacyComposeAdoptedGenerationError } from "../../../src/lib/native-compose-adoption-generation.ts";
4+
import { LEGACY_ADOPTION_SELECTION_MESSAGES } from "../../../src/lib/native-compose-adoption-marker.ts";
5+
import { ProjectInputAccessError } from "../../../src/lib/project-input-selection.ts";
36
import type { CliResult } from "../harness.ts";
47

58
const STAGES = [
@@ -15,6 +18,7 @@ const STAGES = [
1518
type Stage = (typeof STAGES)[number];
1619
const CODES = [
1720
"E_CONFIG_INVALID",
21+
"E_PERMISSION",
1822
"E_LIFECYCLE_FAILED",
1923
"E_STATE",
2024
"E_NATIVE_COMPOSE_ADOPTION",
@@ -58,6 +62,46 @@ const SCHEDULER_REASONS: readonly SchedulerReason[] = [
5862
"completion-authority",
5963
];
6064
const MAX_REPLY_BYTES = 64 * 1024;
65+
/**
66+
* Closed refusal tokens for the fixed, value-free messages an adopted start can
67+
* end with (HACK-1421). Only exact matches map to a token; the message itself
68+
* is never emitted, and any other text is `other`.
69+
*/
70+
const REFUSALS: readonly (readonly [string, string])[] = [
71+
...(
72+
[
73+
["legacy-state", "E_LEGACY_ADOPTION_STATE"],
74+
["legacy-busy", "E_LEGACY_ADOPTION_BUSY"],
75+
["legacy-changed", "E_LEGACY_ADOPTION_CHANGED"],
76+
["legacy-unsupported", "E_LEGACY_ADOPTION_UNSUPPORTED"],
77+
["legacy-cancelled", "E_LEGACY_ADOPTION_CANCELLED"],
78+
["legacy-deadline", "E_LEGACY_ADOPTION_DEADLINE"],
79+
["legacy-literal-env", "E_LEGACY_ADOPTION_LITERAL_ENV"],
80+
] as const
81+
).map(
82+
([token, code]) =>
83+
[token, new LegacyComposeAdoptedGenerationError(code).message] as const
84+
),
85+
[
86+
"adopted-refused",
87+
"Adopted Compose ownership or execution refused; original data is retained. Values omitted.",
88+
],
89+
[
90+
"adopted-cancelled",
91+
"Adopted Compose operation cancelled; pending ownership is retained. Values omitted.",
92+
],
93+
["marker-adoption", LEGACY_ADOPTION_SELECTION_MESSAGES.adoption],
94+
["marker-permission", LEGACY_ADOPTION_SELECTION_MESSAGES.permission],
95+
// The marker's input-access message is the shared project-input guard's.
96+
["input-access", new ProjectInputAccessError("unreadable").message],
97+
];
98+
99+
function refusalToken(message: unknown): string {
100+
if (typeof message !== "string") {
101+
return "unavailable";
102+
}
103+
return REFUSALS.find(([, text]) => text === message)?.[0] ?? "other";
104+
}
61105

62106
function isStage(value: unknown): value is Stage {
63107
return STAGES.some((stage) => stage === value);
@@ -98,6 +142,7 @@ function cliFacts(stdout: string) {
98142
code: "unavailable",
99143
orderedStage: "unavailable",
100144
orderedReason: "unavailable",
145+
refusal: "unavailable",
101146
} as const;
102147
if (Buffer.byteLength(stdout) > MAX_REPLY_BYTES) {
103148
return unavailable;
@@ -108,7 +153,7 @@ function cliFacts(stdout: string) {
108153
return unavailable;
109154
}
110155
if (value.ok === true) {
111-
return { ...unavailable, code: "none" };
156+
return { ...unavailable, code: "none", refusal: "none" };
112157
}
113158
if (value.ok === false && isRecord(value.error)) {
114159
const error = value.error;
@@ -119,6 +164,7 @@ function cliFacts(stdout: string) {
119164
code,
120165
orderedStage: ordered?.stage ?? "unavailable",
121166
orderedReason: ordered?.reason ?? "unavailable",
167+
refusal: refusalToken(error.message),
122168
};
123169
}
124170
} catch {
@@ -128,8 +174,8 @@ function cliFacts(stdout: string) {
128174
}
129175

130176
/**
131-
* Record only closed start/restart substages, CLI codes and exact ordered-refusal
132-
* detail. No reply values, paths, argv, identifiers, arbitrary errors or
177+
* Record only closed start/restart substages, CLI codes, exact ordered-refusal
178+
* detail and a closed token for a fixed refusal message. No reply values, paths, argv, identifiers, arbitrary errors or
133179
* elapsed-budget claims are emitted. Logging failure never replaces the result.
134180
*/
135181
export function createCompletedJobFixtureStartDiagnostics(opts: {
@@ -180,11 +226,11 @@ export function createCompletedJobFixtureStartDiagnostics(opts: {
180226
const timeout = result.timedOut ? "yes" : "no";
181227
const facts = cliFacts(result.stdout);
182228
emit(
183-
`stage=cli-result exit=${exit} timed-out=${timeout} code=${facts.code} ordered-stage=${facts.orderedStage} ordered-reason=${facts.orderedReason}`
229+
`stage=cli-result exit=${exit} timed-out=${timeout} code=${facts.code} ordered-stage=${facts.orderedStage} ordered-reason=${facts.orderedReason} refusal=${facts.refusal}`
184230
);
185231
} catch {
186232
emit(
187-
"stage=cli-result exit=unavailable timed-out=unavailable code=unavailable ordered-stage=unavailable ordered-reason=unavailable"
233+
"stage=cli-result exit=unavailable timed-out=unavailable code=unavailable ordered-stage=unavailable ordered-reason=unavailable refusal=unavailable"
188234
);
189235
}
190236
},

‎tests/native-compose-adoption-binding.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,12 @@ if (fixture.mode?.startsWith('source-bind-c2-') && kind === 'container' && actio
156156
writeFileSync(root+'/fixture.json',JSON.stringify(fixture));
157157
}
158158
}
159+
if (fixture.mode?.startsWith("snapshot-placeholder-") && kind === "network" && action === "inspect") {
160+
// Docker keys an endpoint that has no sandbox (mid start/stop) as ep-<endpoint>; this read only.
161+
const at = fixture.mode.slice("snapshot-placeholder-".length);
162+
const key = at.endsWith("-malformed") ? "ep-not-an-endpoint" : "ep-" + "d".repeat(64);
163+
if (at.startsWith("always") || at === String(networkOrdinal)) for (const bridge of fixture.network) bridge.containers = [...bridge.containers, key];
164+
}
159165
if (kind === "info") {console.log(JSON.stringify({id: fixture.engine, os: "linux"}));}
160166
else if (action === "ls") {for (const row of fixture[kind]) console.log(JSON.stringify({id: row.id, name: kind === 'container' ? row.name.slice(1) : row.name, project: row.project ?? ""}));}
161167
else {
@@ -646,6 +652,75 @@ test("moving snapshot guard exhausts the original shared deadline", async () =>
646652
expect(await Bun.file(join(root, "mutation")).exists()).toBe(false);
647653
}, 10_000);
648654

655+
function networkInspections(observed: readonly string[][]): number {
656+
return observed.filter(
657+
([kind, action]) => kind === "network" && action === "inspect"
658+
).length;
659+
}
660+
661+
test.each([
662+
// The identity-only first read is always followed by a fresh loop read.
663+
["1", 0],
664+
// A placeholder in the accepted loop read costs exactly one more scan.
665+
["2", 1],
666+
] as const)(
667+
"a sandbox-less endpoint placeholder on bridge read %s is re-observed, never admitted or refused (HACK-1421)",
668+
async (ordinal, extra) => {
669+
const clean = await acquireLegacyComposeAdoptionBinding({ projectRoot });
670+
const original = await clean.resolveBinding({ projectRoot });
671+
const baseline = networkInspections(await commands());
672+
await rm(join(root, "commands"));
673+
fixture.mode = `snapshot-placeholder-${ordinal}`;
674+
await writeFile(join(root, "snapshot-network-ordinal"), "0");
675+
await save();
676+
const acquired = await acquireLegacyComposeAdoptionBinding({ projectRoot });
677+
expect(await acquired.resolveBinding({ projectRoot })).toEqual(original);
678+
expect(networkInspections(await commands())).toBe(baseline + extra);
679+
expect(JSON.stringify(original)).not.toContain("ep-");
680+
expect(await Bun.file(join(root, "mutation")).exists()).toBe(false);
681+
},
682+
60_000
683+
);
684+
685+
test("a placeholder on one of two owned bridges is re-observed with both bridges (HACK-1421)", async () => {
686+
await twoBridges();
687+
const clean = await acquireLegacyComposeAdoptionBinding({ projectRoot });
688+
const original = await clean.resolveBinding({ projectRoot });
689+
const baseline = networkInspections(await commands());
690+
await rm(join(root, "commands"));
691+
// Reads 1-2 fix identity; read 3 is the first bridge of the accepted loop scan.
692+
fixture.mode = "snapshot-placeholder-3";
693+
await writeFile(join(root, "snapshot-network-ordinal"), "0");
694+
await save();
695+
const acquired = await acquireLegacyComposeAdoptionBinding({ projectRoot });
696+
expect(await acquired.resolveBinding({ projectRoot })).toEqual(original);
697+
expect(networkInspections(await commands())).toBe(baseline + 2);
698+
expect(await Bun.file(join(root, "mutation")).exists()).toBe(false);
699+
}, 60_000);
700+
701+
test("a persistent endpoint placeholder exhausts the original shared deadline", async () => {
702+
fixture.mode = "snapshot-placeholder-always";
703+
await save();
704+
const started = Date.now();
705+
await refusal(
706+
acquireLegacyComposeAdoptionBinding({ projectRoot, timeoutMs: 6000 }),
707+
"E_LEGACY_COMPOSE_BINDING_PROBE"
708+
);
709+
expect(Date.now() - started).toBeLessThan(9000);
710+
// Identity read plus at least two discarded loop reads before the deadline.
711+
expect(networkInspections(await commands())).toBeGreaterThan(2);
712+
}, 20_000);
713+
714+
test("a malformed placeholder-shaped bridge member still refuses identity without retry", async () => {
715+
fixture.mode = "snapshot-placeholder-always-malformed";
716+
await save();
717+
await refusal(
718+
acquireLegacyComposeAdoptionBinding({ projectRoot }),
719+
"E_LEGACY_COMPOSE_BINDING_IDENTITY"
720+
);
721+
expect(networkInspections(await commands())).toBe(1);
722+
}, 10_000);
723+
649724
test("moving snapshot guard rejects a selected ID on its undeclared bridge before retry", async () => {
650725
await twoBridges();
651726
fixture.mode = "snapshot-wrong-bridge";

0 commit comments

Comments
 (0)