Skip to content

Commit 0b2dfbf

Browse files
matt2eclaude
andauthored
fix(channels): let published leave and delete confirm through access loss (#2357)
## Problem Leaving a channel worked, but the app showed **"Leave channel failed — The request may have taken effect. Refresh channels before trying again."** The relay announces a departure live, before it acknowledges the 9022. It does this through a 39002 roster push, a 44101 member-removed hint (with its strong roster refresh), or a CLOSED `restricted:`. Discovery marks the channel denied, and the session's `revokeAccess` calls `lifecycle.cancel()`. That aborted the leave's own in-flight publish or confirmation read. Publication had already started, so `run()` wrapped the abort as `ChannelLifecycleUnconfirmed` and the dialog showed the failure toast. The same abort had other effects: - `completed()` never ran, so the app was left on "Select a channel to read it." instead of moving to the neighbouring channel. - `observeRemoval` listeners didn't fire, so queued follow-ups for the departed channel were kept. It is intermittent in production because the main trigger is a race between the 44101 hint's full-roster read and the leave's own exact confirmation read. CI missed it because the browser fixture's 9022 handler never pushes anything live. **Delete and archive are affected too.** Delete confirms through the same loop and also revokes the viewer's access. Archive can hit the race when another channel's access changes during its confirmation. The fix covers all three, because it applies to every published lifecycle command. ## Fix One production file, `src/features/relay/channel-lifecycle.ts` (+48/−34). - **Access loss no longer cancels a published command.** Lifecycle scopes now record publication, and `cancel(ids)` / `cancel()` skip published commands. Cancelling on access change is meant to stop permission checks. Once a command is published there's nothing left to authorise, and losing access is usually the command's own effect. - **Retired confirmation reads are read again.** If the shared reader retires a confirmation read as cancelled, the read is issued again under the same 20 s deadline, as `load()` already does. One `reread(signal, attempt)` helper now owns this rule for both paths. It yields a macrotask before each retry, so a reader that rejects without one can't starve the deadline timer and freeze the renderer. Unchanged: the strong exact read is still the only confirmation, and `PublishRejected` is still a real failure. ### What still stops a published command These still abort it and still end as `ChannelLifecycleUnconfirmed`, with nothing removed: - the caller's own signal - the 20 s deadline - session `clear()` - session `dispose()` ## Before / after Both builds are recorded side by side in WebKit (browser harness, fixture data only), with **Channel settings → Leave channel → confirm**. In both, the test relay pushes the updated roster live before it acknowledges the leave. - **Before**, at merge base `3fabf1be4`: the row vanishes and "Leave channel failed … Fetch is aborted" stays on screen. Nothing is selected. - **After**: "Channel left: Lifecycle channel", and Beta is selected. Each build sent exactly one 9022. https://github.com/user-attachments/assets/38201361-9781-417d-8d00-1387c673a5b4 ![Held final frame. Before: "Leave channel failed … Fetch is aborted" over an empty "Select a channel to read it." view, though Lifecycle channel is gone from the sidebar. After: "Channel left: Lifecycle channel", with Beta selected.](https://github.com/user-attachments/assets/9bcfd35b-f397-4716-acdc-7ed977ba0f12) The after arm was recorded at `335430a61`, before the branch was rebased onto `e2f29cccf`. `git range-diff` shows its 3 commits are identical to this PR's (`8b22b05ed`, `fdd7bc892`, `3cf2b8894`). The live push came from an uncommitted scratch fixture patch. The patch stands in for the production 44101 path, which the fixture relay can't route. ## Review Two rounds of agent review, run before this PR was opened: 1. **On `8b22b05ed`:** the fix was judged correct, with one fragile invariant. The reread loop was bounded only while each retired read gave the event loop a turn. A reader that rejected without a macrotask, which a closed reader does, would retry entirely in microtasks, so the 20 s timeout could never fire. The review also suggested hoisting one helper shared with `load()`'s identical loop, renaming the parameter that shadowed the module's `read()`, and testing the deadline directly. `fdd7bc892` addresses all three. 2. **On `fdd7bc892`:** all three earlier points are resolved, with no regression from the shared helper. An optional suggestion was to add join to the survivor matrix, since join is the one action whose surviving confirmation feeds `acceptDiscovery` after `revokeAccess`. `3cf2b8894` adds that case and also renames the "synchronously" deadline case to "without a macrotask", which is what it actually tests. Neither round raised a blocker. ## Tests - `membership-outbox`: the relay announces a leave live before acknowledging it, by roster push, by hint (whose refresh retires the held confirmation read) or by CLOSED. In each case the leave resolves, removes the channel and publishes once. - `channel-lifecycle`: a scoped cancel or a full cancel during a published leave, delete or join, in publication or in a retired confirmation read, still confirms. A surviving join accepts only the roster from the post-revocation read. `clear`, `dispose` and caller abort stay unconfirmed and remove nothing. If every confirmation read is retired, the command is still pending at 19,999 ms and ends `ChannelLifecycleUnconfirmed` at 20 s, on a controlled clock. - Fail-before: - All 11 leave/delete survivor cases fail without the fix. - Without the reread, the 4 confirmation-read cases and the hint case still fail. - Without the yield, the "without a macrotask" deadline case fails. - If the held read returns its pre-revocation roster instead of being retired, the scoped-cancel and cancel join cases fail. - No browser journeys were added or removed. Validated locally: vitest over `src/features/relay`, `src/features/channels`, `src/features/channel-navigation` and follow-up-queue (144 files, 2963 passed, 4 skipped); `tsc --noEmit`; `biome check --error-on-warnings`. ## Verification scope **This change has been verified only in unit tests and in the WebKit browser harness against a synthetic relay.** It has not been run in the desktop app or against a production relay, and no human has tested it yet. The main production trigger, the 44101 race, is covered only by the session-level unit test, because the browser fixture can't model it. The native app's failure-toast suffix (the abort reason after "trying again.") hasn't been checked. ## Test plan - [x] Session-level and lifecycle unit tests above (local) - [x] Before/after leave in the WebKit browser harness with a live roster push (video above) - [ ] Desktop app against a real relay (human), steps below Desktop app against a real relay: 1. Join a channel you can leave, open it, then choose **Channel actions → View channel details → Leave channel** and confirm. - **Expected:** a brief "Leaving channel…" toast, then **"Channel left: \<name\>"**. The channel leaves the sidebar, and the neighbouring channel is selected. - **Bug:** "Leave channel failed" appears, or the app stays on "Select a channel to read it." 2. Repeat step 1 several times. The production trigger is a race, so a single success isn't conclusive. 3. In a channel you own, run **Delete channel**. - **Expected:** "Channel deleted: \<name\>", with no "Delete channel failed" toast. 4. In a channel you own, run **Archive channel** and confirm. - **Expected:** "Channel archived: \<name\>", with no "Archive channel failed" toast. ## Deferred - **Double revocation.** When the race fires, `removed(id)` runs after access was already revoked, so `denyChannel` repeats a revocation pass for the same channel. That retires other in-flight shared reads once more. Review judged it harmless (extra work only), so it is left as a follow-up to keep this change small. - **Browser fixture live roster push.** Not added. The session-level test drives the real session's live callbacks deterministically, the dialog's error mapping is unchanged, and the fixture can't model the production 44101 path. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Matt Toohey <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 9f14241 commit 0b2dfbf

4 files changed

Lines changed: 266 additions & 94 deletions

File tree

‎docs/channels.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -559,11 +559,11 @@ the returned command, and confirms relay-owned state before removing a row. Arch
559559
confirmed Delete/Leave use the existing access-loss purge. Commands use narrow
560560
development-broker routes or the packaged native `relay_channel_sign` and
561561
`relay_channel_publish` commands, never the message outbox or automatic replay.
562-
A dispatched Leave keeps its bounded, fresh, strong viewer-roster confirmation
563-
when membership loss retires access-dependent work. Retired confirmation reads
562+
A published lifecycle command keeps its bounded, fresh, strong confirmation
563+
when access loss retires access-dependent work. Retired confirmation reads
564564
are reread; caller cancellation, session clear/disposal and the original deadline
565565
still abort its signal. A rejected publication or definitive confirmation-read
566-
failure still fails Leave; an aborted read alone never confirms it. These signals
566+
failure still fails the command; an aborted read alone never confirms it. These signals
567567
do not forcibly interrupt an in-flight native publication IPC.
568568
Both hosts admit only the exact two-tag `9002` shape with `archived=true` (Archive)
569569
or `archived=false` (Unarchive); other values, extra tags, cross-route commands and

‎src/features/relay/channel-lifecycle.test.ts‎

Lines changed: 171 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,24 @@ function harness(role = "owner", type = "stream", owners = 1) {
162162
},
163163
};
164164
}
165+
function preview(tags: string[][] = [["public"]]) {
166+
const h = harness("member");
167+
const metadata = h.record(39000, [
168+
["d", id],
169+
["t", "stream"],
170+
["name", "fixture"],
171+
...tags,
172+
]);
173+
const roster = (...members: string[]) =>
174+
h.record(39002, [["d", id], ...members.map((member) => ["p", member])]);
175+
h.setEvents([metadata, roster(other)]);
176+
// Nonmember previews never satisfy member-action access.
177+
h.deny();
178+
h.publish.mockImplementation(async (event: RelayEvent) => {
179+
if (event.kind === 9021) h.setEvents([metadata, roster(other, viewer)]);
180+
});
181+
return { ...h, metadata, roster };
182+
}
165183

166184
describe("bounded visibility recovery", () => {
167185
beforeEach(() => {
@@ -765,7 +783,7 @@ describe("Leave confirmation across access revocation", () => {
765783
["scoped", "global"].map((scope) => ({ action, scope })),
766784
),
767785
)(
768-
"$scope revocation still aborts published $action",
786+
"$scope revocation lets published $action confirm",
769787
async ({ action, scope }) => {
770788
const h = harness();
771789
const publish = h.publish.getMockImplementation();
@@ -775,13 +793,16 @@ describe("Leave confirmation across access revocation", () => {
775793
h.owner.cancel(scope === "scoped" ? [id] : undefined);
776794
});
777795
try {
778-
await expect(h.owner.capability.run(action, id)).rejects.toBeInstanceOf(
779-
ChannelLifecycleUnconfirmed,
780-
);
781-
expect(h.read).toHaveBeenCalledTimes(2);
796+
await h.owner.capability.run(action, id);
797+
expect(h.read).toHaveBeenCalledTimes(3);
782798
expect(h.publish).toHaveBeenCalledOnce();
783-
expect(h.acceptDiscovery).not.toHaveBeenCalled();
784-
expect(h.removed).not.toHaveBeenCalled();
799+
if (action === "archive") {
800+
expect(h.acceptDiscovery).toHaveBeenCalledOnce();
801+
expect(h.removed).not.toHaveBeenCalled();
802+
} else {
803+
expect(h.acceptDiscovery).not.toHaveBeenCalled();
804+
expect(h.removed).toHaveBeenCalledExactlyOnceWith(id);
805+
}
785806
} finally {
786807
h.owner.dispose();
787808
}
@@ -884,6 +905,10 @@ describe("Leave confirmation across access revocation", () => {
884905
const rejected = expect(
885906
h.owner.capability.run("leave", id),
886907
).rejects.toBeInstanceOf(ChannelLifecycleUnconfirmed);
908+
// The retired read is reread after a real macrotask the fake clock
909+
// does not drive; start the poll budget once that reread is issued.
910+
while (h.read.mock.calls.length < 4)
911+
await new Promise<void>((resolve) => setImmediate(resolve));
887912
await vi.advanceTimersByTimeAsync(2500);
888913
await rejected;
889914
expect(h.publish).toHaveBeenCalledOnce();
@@ -1090,6 +1115,145 @@ it("retiring a caller during publication keeps the outcome uncertain without rep
10901115
expect(h.removed).not.toHaveBeenCalled();
10911116
h.owner.dispose();
10921117
});
1118+
it.each(
1119+
(["scoped cancel", "cancel", "clear", "dispose", "caller"] as const).flatMap(
1120+
(stop) =>
1121+
(
1122+
[
1123+
["leave", "publication"],
1124+
["leave", "confirmation read"],
1125+
["delete", "publication"],
1126+
["delete", "confirmation read"],
1127+
["join", "confirmation read"],
1128+
["hide", "confirmation read"],
1129+
] as const
1130+
).map(([action, phase]) => [stop, action, phase] as const),
1131+
),
1132+
)("%s during a published %s's %s", async (stop, action, phase) => {
1133+
const join = action === "join" ? preview() : undefined;
1134+
const h = join ?? harness("owner", action === "hide" ? "dm" : "stream", 2);
1135+
const caller = new AbortController();
1136+
const started = deferred<void>();
1137+
const gate = deferred<void>();
1138+
if (phase === "publication") {
1139+
const apply = h.publish.getMockImplementation();
1140+
assert(apply);
1141+
// The relay applies the command before it acknowledges it.
1142+
h.publish.mockImplementationOnce(async (event) => {
1143+
await apply(event);
1144+
started.resolve();
1145+
await gate.promise;
1146+
});
1147+
} else {
1148+
const currentRead = h.read.getMockImplementation();
1149+
assert(currentRead);
1150+
let held = false;
1151+
h.read.mockImplementation(async (filters, options) => {
1152+
if (held || !filters.every((filter) => filter.consistency === "strong"))
1153+
return currentRead(filters, options);
1154+
held = true;
1155+
started.resolve();
1156+
await gate.promise;
1157+
// The session retires every shared read when access changes.
1158+
throw cancelled();
1159+
});
1160+
}
1161+
const run = h.owner.capability.run(action, id, caller.signal);
1162+
try {
1163+
await started.promise;
1164+
if (stop === "caller") caller.abort();
1165+
else if (stop === "scoped cancel") h.owner.cancel([id]);
1166+
else h.owner[stop]();
1167+
let roster: RelayEvent | undefined;
1168+
if (join) {
1169+
// Revocation purges discovery, so a join may accept only a roster
1170+
// read after it.
1171+
roster = join.roster(other, viewer);
1172+
join.setEvents([join.metadata, roster]);
1173+
}
1174+
gate.resolve();
1175+
if (stop === "scoped cancel" || stop === "cancel") {
1176+
// A published command outlives revocation, usually its own effect, and
1177+
// still confirms.
1178+
await run;
1179+
if (roster)
1180+
expect(h.acceptDiscovery).toHaveBeenCalledExactlyOnceWith([roster]);
1181+
else if (action === "hide")
1182+
expect(h.owner.capability.snapshot().hidden).toEqual([id]);
1183+
else expect(h.removed).toHaveBeenCalledExactlyOnceWith(id);
1184+
} else {
1185+
await expect(run).rejects.toBeInstanceOf(ChannelLifecycleUnconfirmed);
1186+
expect(h.removed).not.toHaveBeenCalled();
1187+
expect(h.acceptDiscovery).not.toHaveBeenCalled();
1188+
expect(h.owner.capability.snapshot().hidden).toEqual([]);
1189+
}
1190+
expect(h.publish).toHaveBeenCalledOnce();
1191+
} finally {
1192+
h.owner.dispose();
1193+
}
1194+
});
1195+
it.each(["after a macrotask", "without a macrotask"] as const)(
1196+
"a published leave whose confirmation reads are all retired %s is unconfirmed at the deadline",
1197+
async (timing) => {
1198+
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
1199+
// Node's native AbortSignal timer is not driven by Vitest's clock.
1200+
const timeout = vi
1201+
.spyOn(AbortSignal, "timeout")
1202+
.mockImplementation((milliseconds) => {
1203+
const controller = new AbortController();
1204+
setTimeout(() => controller.abort(), milliseconds);
1205+
return controller.signal;
1206+
});
1207+
const h = harness("owner", "stream", 2);
1208+
const currentRead = h.read.getMockImplementation();
1209+
assert(currentRead);
1210+
const turn = () => new Promise<void>((resolve) => setImmediate(resolve));
1211+
let retired = 0;
1212+
let unyielded = 0;
1213+
h.read.mockImplementation(async (filters, options) => {
1214+
if (!filters.every((filter) => filter.consistency === "strong"))
1215+
return currentRead(filters, options);
1216+
retired++;
1217+
// A reread that never yields starves the clock; fail it rather than
1218+
// freeze the worker.
1219+
if (++unyielded > 100) throw new Error("Reread without yielding");
1220+
void turn().then(() => {
1221+
unyielded = 0;
1222+
});
1223+
if (timing === "after a macrotask") await turn();
1224+
throw cancelled();
1225+
});
1226+
let settled = false;
1227+
const outcome = h.owner.capability
1228+
.run("leave", id)
1229+
.then(
1230+
() => undefined,
1231+
(error: unknown) => error,
1232+
)
1233+
.finally(() => {
1234+
settled = true;
1235+
});
1236+
// Retired reads are still being reread, so the leave is still pending.
1237+
const rereading = async () => {
1238+
const seen = retired;
1239+
while (retired < seen + 2 && !settled) await turn();
1240+
expect(settled).toBe(false);
1241+
};
1242+
try {
1243+
await rereading();
1244+
await vi.advanceTimersByTimeAsync(19_999);
1245+
await rereading();
1246+
await vi.advanceTimersByTimeAsync(1);
1247+
expect(await outcome).toBeInstanceOf(ChannelLifecycleUnconfirmed);
1248+
expect(h.removed).not.toHaveBeenCalled();
1249+
expect(h.publish).toHaveBeenCalledOnce();
1250+
} finally {
1251+
h.owner.dispose();
1252+
timeout.mockRestore();
1253+
vi.useRealTimers();
1254+
}
1255+
},
1256+
);
10931257
it("reads exact relay-owned coordinates fresh both before sign and before publish", async () => {
10941258
const h = harness();
10951259
await h.owner.capability.run("delete", id);
@@ -1934,25 +2098,6 @@ describe("caller publication guard", () => {
19342098
});
19352099

19362100
describe("join from a public preview", () => {
1937-
function preview(tags: string[][] = [["public"]]) {
1938-
const h = harness("member");
1939-
const metadata = h.record(39000, [
1940-
["d", id],
1941-
["t", "stream"],
1942-
["name", "fixture"],
1943-
...tags,
1944-
]);
1945-
const roster = (...members: string[]) =>
1946-
h.record(39002, [["d", id], ...members.map((member) => ["p", member])]);
1947-
h.setEvents([metadata, roster(other)]);
1948-
// Nonmember previews never satisfy member-action access.
1949-
h.deny();
1950-
h.publish.mockImplementation(async (event: RelayEvent) => {
1951-
if (event.kind === 9021) h.setEvents([metadata, roster(other, viewer)]);
1952-
});
1953-
return { ...h, metadata, roster };
1954-
}
1955-
19562101
it("applies an existing membership without signing", async () => {
19572102
const h = preview();
19582103
h.setEvents([h.metadata, h.roster(viewer)]);

0 commit comments

Comments
 (0)