fix(desktop): gate roster attribution on abort; warn on dead sink; drop starved frames

Blind-review round 9 (Opus high) findings:

- P2: the members queryFn attributed unconditionally, so a roster fetch
  superseded by a live join/leave invalidation could claim the trace's
  one-shot membersFetch slot with a stale count and duration. It now
  checks signal.throwIfAborted() before attributing — same rule as the
  window fetch's reconcile abort gate.
- P2: a permanently dead sink (unwritable log dir, stale directory at
  the log path) was indistinguishable from no traced switches: console
  lines kept flowing while every append failed into .catch(() => {}).
  The first persistence failure now warns once.
- P3: during a suspension that fires no visibilitychange, the deferred
  render-pending marker stays latched, so the settle wait recorded a
  truncated measure inflated by the whole stall (bounded only by the
  35s age guard). A single inter-frame gap beyond 3s — beyond any real
  main-thread stall — now drops the sample.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Max Lampert <maxwell@squareup.com>
This commit is contained in:
Max Lampert
2026-08-24 23:31:23 -07:00
parent 087d9b7b90
commit 116b73bd5e
3 changed files with 63 additions and 7 deletions

View File

@@ -560,13 +560,18 @@ export function useChannelMembersQuery(
return useQuery({
enabled: enabled && channelId !== null,
queryKey: ["channels", channelId ?? "none", "members"],
queryFn: async () => {
queryFn: async ({ signal }) => {
if (!channelId) {
throw new Error("No channel selected.");
}
const fetchStartedAt = performance.now();
const members = await getChannelMembers(channelId);
// Attribute only accepted fetches: a live join/leave invalidation
// cancels and replaces an in-flight roster refetch, and the superseded
// fetch must not claim the trace's one-shot membersFetch slot with a
// stale count — same rule as the window fetch's reconcile abort gate.
signal.throwIfAborted();
traceChannelMembersFetch(
channelId,
members.length,

View File

@@ -146,6 +146,23 @@ test("a not-pending frame landing past the wait deadline is starvation, not a se
});
});
test("a starved frame gap drops even while the render-pending marker is latched", () => {
// During a suspension React can't flush the deferred commit, so the
// pending marker stays latched — its truth is NOT evidence the render was
// slow. A single inter-frame gap beyond any plausible main-thread stall
// means the process was suspended; recording a truncated 22s "switch"
// would fabricate the very regression the tracer hunts.
assert.equal(resolveSettleWait(22_300, 5_300, true, 0, 22_000), "drop");
// Heavy-but-real frames (multi-hundred-ms long tasks) still record.
assert.deepEqual(resolveSettleWait(5_400, 5_300, true, 0, 900), {
settleWaitTruncated: true,
});
// The first frame has no predecessor: no gap to judge.
assert.deepEqual(resolveSettleWait(1_000, 5_300, false, 0, null), {
settleWaitTruncated: false,
});
});
test("a truncated settle is flagged in the summary and the log record", () => {
const summary = summarizeChannelSwitchTrace(trace(), 1_412, true);
assert.ok(summary.endsWith(" settle=truncated"), summary);

View File

@@ -111,8 +111,15 @@ export function buildSwitchPerfLogRecord(
}
let hasAnnouncedLogPath = false;
let hasWarnedSinkFailure = false;
/** Fire-and-forget JSONL append; diagnostics must never surface failures. */
/**
* Fire-and-forget JSONL append; diagnostics must never throw into the app.
* A permanently dead sink must not be SILENT though — the console keeps
* printing per-switch lines that read as "tracing works", so warn once when
* persistence fails or an operator's before/after run yields an empty file
* with no way to tell why.
*/
function appendSwitchPerfLogRecord(record: Record<string, unknown>): void {
if (!isTauri()) return;
void invoke<string>("append_switch_perf_log", {
@@ -124,7 +131,15 @@ function appendSwitchPerfLogRecord(record: Record<string, unknown>): void {
console.info(`[switch-perf] logging to ${path}`);
}
})
.catch(() => {});
.catch((error) => {
if (!hasWarnedSinkFailure) {
hasWarnedSinkFailure = true;
console.warn(
"[switch-perf] failed to persist record; offline log may be incomplete:",
error,
);
}
});
}
/**
@@ -309,6 +324,14 @@ export function resetChannelSwitchTrace(): void {
/** Bound on waiting for the deferred timeline commit before recording. */
const SETTLE_RENDER_WAIT_MS = 5_000;
/**
* Largest inter-frame gap attributable to real main-thread work (heavy
* long tasks run a few hundred ms; 4x-throttled harness frames stay well
* under this). Anything larger is rAF starvation — suspension without a
* visibilitychange — and the sample drops.
*/
const MAX_SETTLE_FRAME_GAP_MS = 3_000;
/**
* Per-frame decision for the bounded settle wait: keep waiting only while
* the deferred render is still pending AND the deadline hasn't passed. When
@@ -321,19 +344,25 @@ const SETTLE_RENDER_WAIT_MS = 5_000;
* suspension (system suspend, App Nap — cases that fire no
* visibilitychange), not render time. A trace older than the settle-entry
* timeout plus the render wait is dropped on the same grounds regardless of
* pending state. The rare honest render that catches up within one frame of
* the deadline is sacrificed by the first rule — better no measurement than
* a fabricated one. Pure for unit testing.
* pending state, as is a single inter-frame gap beyond any plausible
* main-thread stall — a suspension latches the pending marker, so its truth
* is not evidence the render was slow. The rare honest render that catches
* up within one frame of the deadline is sacrificed by these rules — better
* no measurement than a fabricated one. Pure for unit testing.
*/
export function resolveSettleWait(
now: number,
waitDeadline: number,
renderPending: boolean,
startedAt: number,
frameGapMs: number | null = null,
): "wait" | "drop" | { settleWaitTruncated: boolean } {
if (now - startedAt > SWITCH_TRACE_TIMEOUT_MS + SETTLE_RENDER_WAIT_MS) {
return "drop";
}
if (frameGapMs !== null && frameGapMs > MAX_SETTLE_FRAME_GAP_MS) {
return "drop";
}
if (!renderPending && now > waitDeadline) return "drop";
if (renderPending && now < waitDeadline) return "wait";
return { settleWaitTruncated: renderPending };
@@ -411,6 +440,7 @@ export function settleChannelSwitchTrace(channelId: string): void {
const dropTrace = () => {
if (activeTrace === trace) activeTrace = null;
};
let lastFrameAt: number | null = null;
const awaitDeferredCommit = () => {
if (activeTrace !== trace) {
// A newer switch replaced this trace, or a community reset dropped it.
@@ -424,11 +454,15 @@ export function settleChannelSwitchTrace(channelId: string): void {
dropTrace();
return;
}
const now = performance.now();
const frameGapMs = lastFrameAt === null ? null : now - lastFrameAt;
lastFrameAt = now;
const decision = resolveSettleWait(
performance.now(),
now,
waitDeadline,
document.querySelector('[data-render-pending="true"]') !== null,
trace.startedAt,
frameGapMs,
);
if (decision === "wait") {
window.requestAnimationFrame(awaitDeferredCommit);