Skip to content

Commit 9b46232

Browse files
Maxwellimusclaude
andcommitted
fix(desktop): drop live traces on any exit from the channel surface
Blind-review round 7 (Opus medium) findings: - P2: a trace begun while the channel route was still resolving never mounted ChannelScreen, so no route-exit cleanup existed; leaving for Home and history-backing into the channel within 30s settled the stale trace with the time spent away. Any committed non-channel navigation and any history traversal now drop the active trace at the navigation layer (dropActiveChannelSwitchTrace), which covers traces no component ever owned. Same-channel navigations keep the live trace. - The delayed-chunk spec now asserts no CLEAN measure while the chunk is held (the tracer honestly emits a truncated one if its 5s deadline passes) and guards its own timing budget explicitly so a slow CI box fails with the real reason. - The rotation-degradation test blocks rotation with a non-empty directory instead of chmod, so it also holds when tests run as root (containers), and now runs on Windows too. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Max Lampert <[email protected]>
1 parent b9a23a0 commit 9b46232

7 files changed

Lines changed: 166 additions & 26 deletions

File tree

‎desktop/src-tauri/src/commands/perf_log.rs‎

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -326,10 +326,8 @@ mod tests {
326326
std::fs::remove_dir_all(&dir).ok();
327327
}
328328

329-
#[cfg(unix)]
330329
#[test]
331330
fn a_failed_rotation_degrades_to_an_unrotated_append() {
332-
use std::os::unix::fs::PermissionsExt;
333331
let dir = std::env::temp_dir().join(format!(
334332
"perf-log-degrade-{}-{:?}",
335333
std::process::id(),
@@ -339,25 +337,21 @@ mod tests {
339337
let path = dir.join("switch-perf.jsonl");
340338
let rotated = dir.join("switch-perf.jsonl.1");
341339
std::fs::write(&path, "oversized-live\n").expect("seed live");
342-
std::fs::write(&rotated, "old-generation\n").expect("seed rotated");
340+
// A non-empty DIRECTORY at the rotated path defeats remove_file and
341+
// rename on every platform — including for root, where permission
342+
// tricks no-op (containers often run tests as uid 0). It stands in
343+
// for a transient AV/EDR hold: the append must degrade to the
344+
// unrotated file, not drop records until the lock clears.
345+
std::fs::create_dir_all(rotated.join("hold")).expect("seed blocker");
343346

344-
// A read-only directory makes remove/rename fail, like a transient
345-
// AV/EDR hold would. The append must degrade to the unrotated file —
346-
// dropping every record until an external lock clears would violate
347-
// the sink's no-silent-loss contract.
348-
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555)).expect("lock dir");
349-
let result = append_line_rotating(&path, "must-survive", 8);
350-
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).expect("unlock dir");
351-
result.expect("append must survive a failed rotation");
347+
append_line_rotating(&path, "must-survive", 8)
348+
.expect("append must survive a failed rotation");
352349

353350
assert_eq!(
354351
std::fs::read_to_string(&path).expect("read live"),
355352
"oversized-live\nmust-survive\n"
356353
);
357-
assert_eq!(
358-
std::fs::read_to_string(&rotated).expect("read rotated"),
359-
"old-generation\n"
360-
);
354+
assert!(rotated.join("hold").exists(), "blocker untouched");
361355
std::fs::remove_dir_all(&dir).ok();
362356
}
363357

‎desktop/src/app/navigation/commitGuardedNavigation.test.mjs‎

Lines changed: 97 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,111 @@ import assert from "node:assert/strict";
22
import test from "node:test";
33

44
import { commitGuardedNavigation } from "./commitGuardedNavigation.ts";
5-
import { registerNavigationGuard } from "./navigationGuard.ts";
5+
import { registerNavigationGuard, traverseHistory } from "./navigationGuard.ts";
66
import {
77
CHANNEL_SWITCH_MEASURE,
8+
beginChannelSwitchTrace,
89
resetChannelSwitchTrace,
910
settleChannelSwitchTrace,
1011
} from "../../shared/lib/channelSwitchPerf.ts";
1112

1213
const route = (href) => ({ kind: "route", href });
1314

15+
// Frame/document stubs so settle's rAF chain can be driven synchronously.
16+
function withTraceHarness(run) {
17+
const frames = [];
18+
const originalWindow = globalThis.window;
19+
const originalDocument = globalThis.document;
20+
globalThis.window = {
21+
requestAnimationFrame: (cb) => frames.push(cb) && frames.length,
22+
cancelAnimationFrame: () => {},
23+
};
24+
globalThis.document = {
25+
addEventListener: () => {},
26+
querySelector: () => null,
27+
removeEventListener: () => {},
28+
visibilityState: "visible",
29+
};
30+
performance.clearMeasures?.(CHANNEL_SWITCH_MEASURE);
31+
const flush = () => {
32+
for (let i = 0; i < 20 && frames.length > 0; i += 1) {
33+
for (const cb of frames.splice(0, frames.length)) cb();
34+
}
35+
};
36+
const measures = () =>
37+
performance
38+
.getEntriesByName(CHANNEL_SWITCH_MEASURE)
39+
.map((entry) => entry.detail?.channelId);
40+
return (async () => {
41+
try {
42+
await run({ flush, measures });
43+
} finally {
44+
resetChannelSwitchTrace();
45+
performance.clearMeasures?.(CHANNEL_SWITCH_MEASURE);
46+
if (originalWindow === undefined) delete globalThis.window;
47+
else globalThis.window = originalWindow;
48+
if (originalDocument === undefined) delete globalThis.document;
49+
else globalThis.document = originalDocument;
50+
}
51+
})();
52+
}
53+
54+
test("a committed non-channel navigation drops the active trace", async () => {
55+
await withTraceHarness(async ({ flush, measures }) => {
56+
// A trace can be live with no channel screen mounted at all (the route
57+
// still resolving), so no route-exit cleanup exists to abandon it — the
58+
// navigation layer must drop it, or a history-back re-entry within the
59+
// 30s timeout would settle it with the time spent away.
60+
beginChannelSwitchTrace("bbbb");
61+
const committed = await commitGuardedNavigation({
62+
currentHref: "/channels/bbbb",
63+
nextHref: "/",
64+
guardedTarget: route("/"),
65+
leavesChannelSurface: true,
66+
navigate: async () => {},
67+
});
68+
assert.equal(committed, true);
69+
settleChannelSwitchTrace("bbbb");
70+
flush();
71+
assert.deepEqual(measures(), []);
72+
});
73+
});
74+
75+
test("a same-channel navigation never drops the channel's live trace", async () => {
76+
await withTraceHarness(async ({ flush, measures }) => {
77+
beginChannelSwitchTrace("bbbb");
78+
// Jump-to-message within the active channel: untraced, but must not
79+
// kill the in-flight trace either.
80+
await commitGuardedNavigation({
81+
currentHref: "/channels/bbbb",
82+
nextHref: "/channels/bbbb?messageId=m1",
83+
guardedTarget: route("/channels/bbbb?messageId=m1"),
84+
leavesChannelSurface: false,
85+
navigate: async () => {},
86+
});
87+
settleChannelSwitchTrace("bbbb");
88+
flush();
89+
assert.deepEqual(measures(), ["bbbb"]);
90+
});
91+
});
92+
93+
test("history traversal drops the active trace", async () => {
94+
await withTraceHarness(async ({ flush, measures }) => {
95+
beginChannelSwitchTrace("bbbb");
96+
const calls = [];
97+
// History navigation is deliberately untraced and its destination is
98+
// unknowable here — a live trace must not survive into it.
99+
traverseHistory(
100+
{ back: () => calls.push("back"), forward: () => {} },
101+
"back",
102+
);
103+
assert.deepEqual(calls, ["back"]);
104+
settleChannelSwitchTrace("bbbb");
105+
flush();
106+
assert.deepEqual(measures(), []);
107+
});
108+
});
109+
14110
test("a refused navigation opens no trace; a later history settle records nothing", async () => {
15111
// Frame-queue stub so the settle's rAF chain can be drained synchronously.
16112
const frames = [];

‎desktop/src/app/navigation/commitGuardedNavigation.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,39 +2,51 @@ import {
22
allowNavigation,
33
type GuardedNavigation,
44
} from "@/app/navigation/navigationGuard";
5-
import { beginChannelSwitchTrace } from "@/shared/lib/channelSwitchPerf";
5+
import {
6+
beginChannelSwitchTrace,
7+
dropActiveChannelSwitchTrace,
8+
} from "@/shared/lib/channelSwitchPerf";
69

710
/**
811
* commitGuardedNavigation runs the shared commit flow for app navigations:
912
* skip same-destination no-ops (unless forced), consult the navigation
1013
* guard, then navigate. When `traceChannelId` is set, the channel-switch
1114
* trace opens only after the guard accepts — a refused click must not leave
1215
* an orphan trace that a later history navigation (deliberately untraced)
13-
* would settle with the refused click's inflated wall time. Returns whether
14-
* the navigation was performed. `deps` exists for unit tests.
16+
* would settle with the refused click's inflated wall time. When
17+
* `leavesChannelSurface` is set, any active trace is dropped instead: the
18+
* trace may be live with no channel screen mounted (route still resolving),
19+
* so this is the only reliable exit hook. Returns whether the navigation was
20+
* performed. `deps` exists for unit tests.
1521
*/
1622
export async function commitGuardedNavigation(
1723
input: {
1824
currentHref: string;
1925
nextHref: string;
2026
force?: boolean;
2127
guardedTarget: GuardedNavigation;
28+
leavesChannelSurface?: boolean;
2229
traceChannelId?: string;
2330
navigate: () => Promise<unknown>;
2431
},
2532
deps: {
2633
allow?: typeof allowNavigation;
2734
beginTrace?: typeof beginChannelSwitchTrace;
35+
dropActiveTrace?: typeof dropActiveChannelSwitchTrace;
2836
} = {},
2937
): Promise<boolean> {
3038
const allow = deps.allow ?? allowNavigation;
3139
const beginTrace = deps.beginTrace ?? beginChannelSwitchTrace;
40+
const dropActiveTrace = deps.dropActiveTrace ?? dropActiveChannelSwitchTrace;
3241
if (input.currentHref === input.nextHref && !input.force) {
3342
return false;
3443
}
3544
if (!allow(input.guardedTarget)) {
3645
return false;
3746
}
47+
if (input.leavesChannelSurface) {
48+
dropActiveTrace();
49+
}
3850
if (input.traceChannelId !== undefined) {
3951
beginTrace(input.traceChannelId);
4052
}

‎desktop/src/app/navigation/navigationGuard.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { dropActiveChannelSwitchTrace } from "@/shared/lib/channelSwitchPerf";
2+
13
export type GuardedNavigation =
24
| {
35
kind: "history";
@@ -40,6 +42,11 @@ export function traverseHistory(
4042
return false;
4143
}
4244

45+
// History navigation is deliberately untraced and its destination is
46+
// unknowable here: a live switch trace must not survive into it, or an
47+
// untraced re-entry into the traced channel would settle it with the time
48+
// spent away.
49+
dropActiveChannelSwitchTrace();
4350
history[direction]();
4451
return true;
4552
}

‎desktop/src/app/navigation/useAppNavigation.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ export function useAppNavigation() {
4646
kind: "route",
4747
href: nextLocation.href,
4848
},
49+
// Leaving the channel surface must drop any active switch trace —
50+
// including one whose channel screen never mounted (route still
51+
// resolving), which no component cleanup can cover.
52+
leavesChannelSurface: !next.to.startsWith("/channels/"),
4953
navigate: () =>
5054
navigate({
5155
...next,

‎desktop/src/shared/lib/channelSwitchPerf.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,18 @@ export function abandonChannelSwitchTrace(channelId: string): void {
161161
}
162162
}
163163

164+
/**
165+
* dropActiveChannelSwitchTrace abandons whatever trace is active, regardless
166+
* of channel. Called when navigation leaves the channel surface (any
167+
* committed non-channel destination, any history traversal): a trace can be
168+
* live with no channel screen mounted at all — the route still resolving —
169+
* so no route-exit cleanup exists to abandon it, and a later untraced
170+
* re-entry within the timeout would settle it with the time spent away.
171+
*/
172+
export function dropActiveChannelSwitchTrace(): void {
173+
activeTrace = null;
174+
}
175+
164176
// Route-exit abandons currently deferred; see scheduleRouteExitAbandon.
165177
const pendingRouteExitAbandons = new Set<string>();
166178

‎desktop/tests/e2e/switch-settle-after-paint.spec.ts‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -88,15 +88,30 @@ test("settle waits for a delayed lazy channel-pane chunk", async ({ page }) => {
8888
.toBe(true);
8989

9090
// Give the tracer ample frames to (incorrectly) settle behind the held
91-
// chunk. This wait must stay well under the tracer's 5s settle deadline.
91+
// chunk. The tracer's 5s render-wait deadline runs from settle entry
92+
// (query readiness — immediate in mock mode), after which it honestly
93+
// emits a TRUNCATED measure even while suspended; the contract under test
94+
// is that no CLEAN measure appears. Guard the timing assumption
95+
// explicitly so a slow CI box fails with the real reason.
9296
await page.waitForTimeout(1_500);
93-
const early = await page.evaluate(
94-
(name) => performance.getEntriesByName(name).length,
95-
SWITCH_MEASURE,
96-
);
97+
const early = await page.evaluate((name) => {
98+
const start = performance.getEntriesByName("buzz:channel-switch:start")[0];
99+
return {
100+
cleanMeasures: performance
101+
.getEntriesByName(name)
102+
.filter(
103+
(entry) => !(entry as PerformanceMeasure).detail?.settleWaitTruncated,
104+
).length,
105+
elapsedSinceClick: start ? performance.now() - start.startTime : null,
106+
};
107+
}, SWITCH_MEASURE);
108+
expect(
109+
early.elapsedSinceClick,
110+
"harness overhead consumed the tracer's settle deadline — timing, not a tracer bug",
111+
).toBeLessThan(4_500);
97112
expect(
98-
early,
99-
"no settle may be recorded while the pane chunk is suspended",
113+
early.cleanMeasures,
114+
"no clean settle may be recorded while the pane chunk is suspended",
100115
).toBe(0);
101116

102117
releaseChunk();

0 commit comments

Comments
 (0)