Skip to content

Commit c697ace

Browse files
ryan-williamsclaude
andcommitted
Session log: don't count failures nobody saw as errors
A network failure (`s: 0`, not a cancellation) is now an `offlineFailure`, counted as a request rather than an error, when the client reported `online: false` or `visibility: 'hidden'`, or when its batch reached the server more than `OFFLINE_LAG_MS` (60 s) after the request. The logger flushes every 10 s, so normal batches arrive within ~16 s; disky saw `Failed to fetch` batches arrive 164-1151 s late with `online: true` from a laptop closed mid-refresh. `isFailedApi` / `isErrorEvent` take an optional `receivedMs`. The D1 ingest (`n_errors`), the activity bridge (which passes it on to a custom `event` mapper) and the session viewer all apply it. The viewer gets it as `_received_ms` on each stored event, a name no client field can take. The rule matches disky's `offlineFailure` (cw `42fb2748`). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DyJyzSYpRxJuL6x6NyjpG3
1 parent e5013f6 commit c697ace

9 files changed

Lines changed: 116 additions & 24 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ slog('movie.queued', { query, format })
234234

235235
The identity on every batch is the request's (`identify`), never the client's. App events must be declared on the server: the client drops undeclared ones and undeclared fields, and the server refuses them, so an app event can't carry an arbitrary object. `filterEvents`, `onStored` (run through `waitUntil`) and `onPurge` hook in an app's own muting, activity feed and derived tables.
236236

237-
Fetch cancellations remain visible as `cancelled` without inflating error counts. Explicit `AbortError` is classified immediately; other network failures wait up to five seconds so an intervening `pagehide` can classify them as navigation cancellations. That is a client heuristic, not proof that backend work stopped. Failures on a surviving page remain errors. Benign ResizeObserver scheduling reports are dropped by the client. Anonymous config reads never trigger retention writes, including opted-in public viewers.
237+
Fetch cancellations remain visible as `cancelled` without inflating error counts. Explicit `AbortError` is classified immediately; other network failures wait up to five seconds so an intervening `pagehide` can classify them as navigation cancellations. That is a client heuristic, not proof that backend work stopped. Failures on a surviving page remain errors, unless nobody could have seen them fail (`offlineFailure`): the browser reported itself offline, the tab was hidden, or the batch reached the server over a minute (`OFFLINE_LAG_MS`) after the request, as when a laptop is closed mid-request. Those count as requests, not errors, in the session list, the viewer and the activity bridge. Each failed request also records `online`, `visibility` and, after a tab resume, `visible_ms`. Benign ResizeObserver scheduling reports are dropped by the client. Anonymous config reads never trigger retention writes, including opted-in public viewers.
238238

239239
The migrations are a track of their own (`migrations/session-log/`), so apps that don't use the session log carry no tables for it. Apply the track in order through your migration system (or copy into your app's sequence). `0002_actor.sql` adds nullable `grant_id`/`subject_name`: apply it once after `0001_session_log.sql` before deploying this version, including existing disky-shaped databases. Do not blindly re-run the ALTER statements. `fromGate` attaches trusted recipient identity, and the viewer's filter matches email, recipient name and grant ID; the private grant memo is never used. Old rows are not retrospectively attributed. The summary row tracks the tab's latest identity, not immutable per-event identity evidence.
240240

‎src/activity/bridges.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,17 @@ export interface SessionActivityOptions {
1919
/** Required: core SessionLogWho has no stable identity for an unbound grant. Never trust batch fields for it. */
2020
actor: (input: StoredSession) => ActivityActor | null | Promise<ActivityActor | null>
2121
now?: () => number
22-
/** Optional app-specific conversion. Null drops an event; no arbitrary client fields are copied by default. */
23-
event?: (event: SlogEvent) => Pick<ActivityEvent, 'kind' | 'line' | 'path'> | null
22+
/**
23+
* Optional app-specific conversion. Null drops an event; no arbitrary client fields are copied by default.
24+
* `receivedMs` is when the server received the batch, for `isErrorEvent`'s offline-failure rule.
25+
*/
26+
event?: (event: SlogEvent, receivedMs: number) => Pick<ActivityEvent, 'kind' | 'line' | 'path'> | null
2427
}
2528

26-
function sessionEvent(event: SlogEvent): Pick<ActivityEvent, 'kind' | 'line' | 'path'> | null {
29+
function sessionEvent(event: SlogEvent, receivedMs: number): Pick<ActivityEvent, 'kind' | 'line' | 'path'> | null {
2730
const { k } = event
2831
if (k === 'dropped') return null
29-
if (isErrorEvent(event)) return { kind: 'error', line: String(event.msg ?? `${k} ${event.s ?? ''}`).slice(0, 2000) }
32+
if (isErrorEvent(event, receivedMs)) return { kind: 'error', line: String(event.msg ?? `${k} ${event.s ?? ''}`).slice(0, 2000) }
3033
if (k === 'start' || k === 'nav') {
3134
const path = typeof event.u === 'string' ? activityPath(event.u) : undefined
3235
return { kind: k === 'start' ? 'view' : 'nav', line: path, path }
@@ -46,7 +49,7 @@ export function sessionLogActivity(feed: ActivityFeed, options: SessionActivityO
4649
const receipt = now()
4750
// Stable per-event keys allow safe retry after partially bridging a stored batch.
4851
for (const [index, event] of batch.events.entries()) {
49-
const mapped = (options.event ?? sessionEvent)(event)
52+
const mapped = (options.event ?? sessionEvent)(event, receipt * 1000)
5053
if (!mapped) continue
5154
await feed.record({
5255
...mapped,

‎src/adapters/d1-session-log.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ export function d1SessionLogStore(db: D1Database, opts: D1SessionLogOptions = {}
105105
const ts = b.events.map(e => e.t)
106106
const first = Math.min(...ts)
107107
const last = Math.max(...ts)
108-
const errors = b.events.filter(isErrorEvent).length
108+
const errors = b.events.filter(e => isErrorEvent(e, nowS * 1000)).length
109109
// One transaction: the batch row, then the session's counters only if
110110
// that row was new (`changes()`), so a retried beacon counts nothing and
111111
// a failure leaves neither half behind.
@@ -237,11 +237,11 @@ export function d1SessionLogStore(db: D1Database, opts: D1SessionLogOptions = {}
237237
const session = stored ? sessionRow(stored) : null
238238
if (!session) return null
239239
const rows = await db
240-
.prepare('SELECT pid, seq, events FROM session_log_batches WHERE sid = ? ORDER BY first_ms, pid, seq')
240+
.prepare('SELECT pid, seq, received_ts, events FROM session_log_batches WHERE sid = ? ORDER BY first_ms, pid, seq')
241241
.bind(sid)
242-
.all<{ pid: string; seq: number; events: string }>()
242+
.all<{ pid: string; seq: number; received_ts: number; events: string }>()
243243
const tagged = rows.results.flatMap(r =>
244-
(JSON.parse(r.events) as SlogEvent[]).map((e, i) => ({ e: { ...e, pid: r.pid, seq: r.seq } as StoredEvent, i })),
244+
(JSON.parse(r.events) as SlogEvent[]).map((e, i) => ({ e: { ...e, pid: r.pid, seq: r.seq, _received_ms: r.received_ts * 1000 } as StoredEvent, i })),
245245
)
246246
tagged.sort(
247247
(a, b) => a.e.t - b.e.t || (a.e.pid < b.e.pid ? -1 : a.e.pid > b.e.pid ? 1 : 0) || a.e.seq - b.e.seq || a.i - b.i,

‎src/core/session-log-shape.ts‎

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -99,12 +99,38 @@ export const benignError = (msg: unknown): boolean => typeof msg === 'string' &&
9999

100100
/** A client-classified cancellation, not proof that server-side work was cancelled. */
101101
export const isCancelled = (e: { k?: unknown; s?: unknown; err?: unknown }): boolean => e.k === 'api' && e.s === 0 && e.err === 'abort'
102-
export const isFailedApi = (e: { k?: unknown; s?: unknown; err?: unknown }): boolean =>
103-
e.k === 'api' && typeof e.s === 'number' && (e.s >= 500 || (e.s === 0 && !isCancelled(e)))
104102

105-
/** Kinds and API statuses that count as errors; intentional cancellations do not. */
106-
export const isErrorEvent = (e: { k: Kind; s?: unknown; err?: unknown }): boolean =>
107-
e.k === 'error' || e.k === 'reject' || e.k === 'console' || isFailedApi(e)
103+
/** Batches normally arrive within ~16 s (the logger flushes every 10 s); a failure received later than this was reported by a device that went to sleep or offline. */
104+
export const OFFLINE_LAG_MS = 60_000
105+
106+
type ApiFields = { k?: unknown; t?: unknown; s?: unknown; err?: unknown; online?: unknown; visibility?: unknown }
107+
108+
/**
109+
* A network failure nobody saw fail: the browser was offline, the tab hidden,
110+
* or its batch arrived over `OFFLINE_LAG_MS` after the request (a laptop closed
111+
* mid-request reports `online: true` on wake). It counts as a request, not an
112+
* error. Without `receivedMs` (epoch ms the server received the batch), only
113+
* the client's own context decides.
114+
*/
115+
export const offlineFailure = (e: ApiFields, receivedMs?: number): boolean =>
116+
e.k === 'api' &&
117+
e.s === 0 &&
118+
e.err !== 'abort' &&
119+
(e.online === false ||
120+
e.visibility === 'hidden' ||
121+
(receivedMs !== undefined && typeof e.t === 'number' && receivedMs - e.t > OFFLINE_LAG_MS))
122+
123+
/** A request that failed: a 5xx, or no response other than a cancellation or an `offlineFailure`. */
124+
export const isFailedApi = (e: ApiFields, receivedMs?: number): boolean =>
125+
e.k === 'api' && typeof e.s === 'number' && (e.s >= 500 || (e.s === 0 && !isCancelled(e) && !offlineFailure(e, receivedMs)))
126+
127+
/**
128+
* Kinds and API statuses that count as errors; cancellations and offline
129+
* failures do not. Pass `receivedMs` explicitly: not as a bare `filter` / `map`
130+
* callback, whose index would land there.
131+
*/
132+
export const isErrorEvent = (e: ApiFields & { k: Kind }, receivedMs?: number): boolean =>
133+
e.k === 'error' || e.k === 'reject' || e.k === 'console' || isFailedApi(e, receivedMs)
108134

109135
const ID = /^[A-Za-z0-9_-]{6,40}$/
110136

@@ -283,7 +309,8 @@ export interface SessionPage {
283309
}
284310

285311
/** A stored event with where it came from (the page load and batch), as the session view gets it. */
286-
export type StoredEvent = SlogEvent & { pid: string; seq: number }
312+
/** An event as the viewer gets it: tagged with its page load, batch, and when the server received that batch (`_`: no client field can take the name). */
313+
export type StoredEvent = SlogEvent & { pid: string; seq: number; _received_ms?: number }
287314

288315
/** `GET <base>/sessions/:sid`. */
289316
export interface SessionDetail {

‎src/react/session-log/model.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ const BUILTIN = new Set<string>(KINDS)
6868
export const LANES = ['nav', 'input', 'app', 'api', 'error', 'page'] as const
6969
export type Lane = typeof LANES[number]
7070
export const laneOf = (e: StoredEvent): Lane =>
71-
isErrorEvent(e) ? 'error'
71+
isErrorEvent(e, e._received_ms) ? 'error'
7272
: e.k === 'start' || e.k === 'nav' ? 'nav'
7373
: e.k === 'click' || e.k === 'filter' || e.k === 'pick' || e.k === 'prefetch' ? 'input'
7474
: e.k === 'api' ? 'api'
@@ -95,7 +95,7 @@ export function timeline(events: readonly StoredEvent[]): Line[] {
9595
const urlBy = new Map<string, string>()
9696
return events.map((e, i) => {
9797
if ((e.k === 'start' || e.k === 'nav') && typeof e.u === 'string') urlBy.set(e.pid, e.u)
98-
return { i, t: e.t, off: e.t - t0, k: e.k, text: summarize(e), error: isErrorEvent(e), lane: laneOf(e), url: urlBy.get(e.pid) ?? null, pid: e.pid }
98+
return { i, t: e.t, off: e.t - t0, k: e.k, text: summarize(e), error: isErrorEvent(e, e._received_ms), lane: laneOf(e), url: urlBy.get(e.pid) ?? null, pid: e.pid }
9999
})
100100
}
101101

‎test/activity-bridges.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,18 @@ describe('activity bridges', () => {
3939
})
4040
})
4141

42+
it('bridges a failure the user saw as an error, and one reported a minute late as nothing', async () => {
43+
const { store, feed } = setup()
44+
const hooks = sessionLogActivity(feed, { actor: () => actor, now: () => 1000 })
45+
const fail = (t: number) => ({ t, k: 'api', u: '/api/x', s: 0, ms: 0, err: 'TypeError: Failed to fetch', online: true, visibility: 'visible' })
46+
await hooks.onStored({
47+
who: { email: null, via: 'grant' }, req: new Request('https://app.example/api/log'),
48+
batch: { sid: 'tab-123', pid: 'page-123', seq: 0, build: 'test', events: [fail(999_000), fail(939_000)] },
49+
})
50+
const [burst] = await store.list()
51+
expect({ counts: burst?.counts, lines: burst?.lines.map(e => [e.kind, e.line]) }).toEqual({ counts: { error: 1 }, lines: [['error', 'api 0']] })
52+
})
53+
4254
it('bridges persisted access rows idempotently, including non-browser views', async () => {
4355
const { store, feed } = setup()
4456
const bridge = accessLogActivity(feed, { origin: 'https://app.example', actor: () => actor })

‎test/react/session-log-model.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,17 @@ describe('session view model', () => {
2727
['error', true, 'GET /api/network → failed · 4ms · TypeError: Failed to fetch'],
2828
])
2929
})
30+
it('keeps a failure nobody saw (offline, or received over a minute late) out of the error lane', () => {
31+
const fail = { u: '/api/x', s: 0, ms: 4, err: 'TypeError: Failed to fetch', online: true, visibility: 'visible' }
32+
const lines = timeline([
33+
e(0, 'api', { ...fail, _received_ms: T + 10_000 }),
34+
e(1, 'api', { ...fail, online: false, _received_ms: T + 10_000 }),
35+
e(2, 'api', { ...fail, _received_ms: T + 164_000 }),
36+
e(3, 'api', fail),
37+
])
38+
expect(lines.map(l => [l.lane, l.error])).toEqual([['error', true], ['api', false], ['api', false], ['error', true]])
39+
})
40+
3041
it('renders each kind as a line, with the URL in effect per page load and errors flagged', () => {
3142
const events = [
3243
e(0, 'start', { u: '/?d=2026-10-10', ref: 'https://discord.com/channels' }),

‎test/session-log-identity.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ describe('trusted share-link identity', () => {
9999
const detail = await handle(new Request(`${HOST}/api/session-log/sessions/sid-identity`, { headers: admin }))
100100
expect([list?.status, await list?.json(), detail?.status, await detail?.json(), stored]).toEqual([
101101
200, { sessions: [expected], total: 1, offset: 0, prev: null, next: null },
102-
200, { session: expected, events: [{ t: NOW, k: 'start', u: '/report', pid: 'pid-identity', seq: 0 }] },
102+
200, { session: expected, events: [{ t: NOW, k: 'start', u: '/report', pid: 'pid-identity', seq: 0, _received_ms: NOW }] },
103103
[{ email: null, via: 'grant', grantId: grant.id, subjectName: 'Ada Recipient' }],
104104
])
105105
})
@@ -114,7 +114,7 @@ describe('D1 session actor storage', () => {
114114
expect(await store.ingest(next, null, batch(), NOW / 1000 + 1)).toBe('duplicate')
115115
expect(await store.sessionDetail('sid-identity')).toEqual({
116116
session: summary({ grant_id: 'grant-first', subject_name: 'First Recipient' }),
117-
events: [{ t: NOW, k: 'start', u: '/report', pid: 'pid-identity', seq: 0 }],
117+
events: [{ t: NOW, k: 'start', u: '/report', pid: 'pid-identity', seq: 0, _received_ms: NOW }],
118118
})
119119
expect(await store.ingest(next, null, batch({ seq: 1 }), NOW / 1000 + 1)).toBe('stored')
120120
expect(await store.listSessions({ email: 'NEXT RECIPIENT' })).toEqual({

‎test/session-log.test.ts‎

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ import {
1313
fmtCursor,
1414
isForever,
1515
isErrorEvent,
16+
offlineFailure,
17+
OFFLINE_LAG_MS,
1618
LIMITS,
1719
parseCursor,
1820
parseUntil,
@@ -176,7 +178,31 @@ describe('session log error classification', () => {
176178
{ k: 'api', s: 200 },
177179
{ k: 'error', msg: 'real exception' },
178180
] as const
179-
expect(events.map(isErrorEvent)).toEqual([false, true, true, false, true])
181+
expect(events.map(e => isErrorEvent(e))).toEqual([false, true, true, false, true])
182+
})
183+
184+
it('does not count a network failure nobody saw: offline, hidden tab, or reported over a minute late', () => {
185+
const fail = (dt: number, f: Record<string, unknown> = {}) => ({ k: 'api', t: NOW - dt, s: 0, err: 'TypeError: Failed to fetch', ...f })
186+
const cases = [
187+
[fail(1000), NOW],
188+
[fail(1000, { online: false }), NOW],
189+
[fail(1000, { online: true, visibility: 'hidden' }), NOW],
190+
[fail(OFFLINE_LAG_MS, { online: true, visibility: 'visible' }), NOW],
191+
[fail(OFFLINE_LAG_MS + 1, { online: true, visibility: 'visible' }), NOW],
192+
[fail(OFFLINE_LAG_MS + 1), undefined],
193+
[fail(1000, { online: false, err: 'abort' }), NOW],
194+
[{ k: 'api', t: NOW - 600_000, s: 503, online: false }, NOW],
195+
] as const
196+
expect(cases.map(([e, rcv]) => [offlineFailure(e, rcv), isErrorEvent(e, rcv)])).toEqual([
197+
[false, true],
198+
[true, false],
199+
[true, false],
200+
[false, true],
201+
[true, false],
202+
[false, true],
203+
[false, false],
204+
[false, true],
205+
])
180206
})
181207
})
182208

@@ -471,6 +497,19 @@ describe('POST <base>', () => {
471497
])
472498
})
473499

500+
it('counts a failed request as an error only if someone could have seen it fail', async () => {
501+
const { call, viewer, raw } = await setup()
502+
const fail = (t: number, f: Record<string, unknown> = {}) => ev(t, 'api', { u: '/api/x', s: 0, ms: 0, err: 'TypeError: Failed to fetch', ...f })
503+
const events = [
504+
fail(NOW - 1000, { online: true, visibility: 'visible' }),
505+
fail(NOW - 1000, { online: false, visibility: 'visible' }),
506+
fail(NOW - 1000, { online: true, visibility: 'hidden' }),
507+
fail(NOW - 164_000, { online: true, visibility: 'visible' }),
508+
]
509+
expect(await call('POST', '', { token: viewer, body: batch({ events }) })).toEqual([204, null])
510+
expect(raw.prepare('SELECT n_events, n_errors FROM session_log').all()).toEqual([{ n_events: 4, n_errors: 1 }])
511+
})
512+
474513
it('a repeated (sid, pid, seq) — a retried beacon — is ignored and counts nothing', async () => {
475514
const { call, viewer, raw } = await setup()
476515
await call('POST', '', { token: viewer, body: batch() })
@@ -741,9 +780,9 @@ describe('admin reads', () => {
741780
received_ts: NOW / 1000,
742781
},
743782
events: [
744-
{ t: NOW - 5000, k: 'start', u: '/', pid: 'pid-111111', seq: 0 },
745-
{ t: NOW - 3000, k: 'error', msg: 'x', pid: 'pid-222222', seq: 0 },
746-
{ t: NOW - 1000, k: 'nav', u: '/a', pid: 'pid-111111', seq: 0 },
783+
{ t: NOW - 5000, k: 'start', u: '/', pid: 'pid-111111', seq: 0, _received_ms: NOW },
784+
{ t: NOW - 3000, k: 'error', msg: 'x', pid: 'pid-222222', seq: 0, _received_ms: NOW },
785+
{ t: NOW - 1000, k: 'nav', u: '/a', pid: 'pid-111111', seq: 0, _received_ms: NOW },
747786
],
748787
},
749788
])

0 commit comments

Comments
 (0)