Repository navigation
Expand file tree
/
Copy pathprofile.ts
More file actions
228 lines (215 loc) · 8.4 KB
/
Copy pathprofile.ts
File metadata and controls
228 lines (215 loc) · 8.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import { median } from './stats.ts';
import type {
MeasurementProfile,
Sample,
SampleProfile,
SettleFacts,
SnapshotFacts,
Timing,
} from './types.ts';
type DiagnosticEvent = {
ts?: string;
level?: string;
phase?: string;
durationMs?: number;
data?: Record<string, unknown>;
};
const RUNNER_COMMAND_PHASE = 'ios_runner_command_send';
const SPAWN_PHASE = 'exec_command';
const SNAPSHOT_SOURCE_PHASE = 'ios.snapshot-source.acquire';
const SNAPSHOT_RECOVERY_PHASE = 'ios_snapshot_source_recovery';
const STABILIZATION_PHASE = /settle|stabiliz/i;
const FALLBACK_TEXT_LIMIT = 140;
const CLIENT_DIAG_PREFIX = '[agent-device][diag] ';
function addTiming(map: Record<string, Timing>, key: string, durationMs: number | undefined): void {
const entry = (map[key] ??= { count: 0, totalMs: 0 });
entry.count += 1;
entry.totalMs += durationMs ?? 0;
}
function text(value: unknown): string | undefined {
return typeof value === 'string' && value.length > 0
? value.slice(0, FALLBACK_TEXT_LIMIT)
: undefined;
}
function eventDuration(event: DiagnosticEvent): number | undefined {
if (typeof event.durationMs === 'number') return event.durationMs;
const nested = event.data?.durationMs;
return typeof nested === 'number' ? nested : undefined;
}
/**
* Reads one daemon request log (`--debug` ndjson). Process spawns count once, at their `settled`
* event. Fallbacks name every degraded path the request took: snapshot-source errors, truncated
* recovery, and warn- or error-level phases.
*/
export function profileRequestLog(ndjson: string): SampleProfile {
const profile: SampleProfile = {
phases: {},
runnerCommands: {},
spawns: {},
snapshotSources: {},
retries: 0,
stabilization: { count: 0, totalMs: 0 },
fallbacks: [],
};
const fallbacks = new Set<string>();
let firstTs: number | undefined;
let lastTs: number | undefined;
for (const line of ndjson.split('\n')) {
if (!line.trim()) continue;
let event: DiagnosticEvent;
try {
event = JSON.parse(line) as DiagnosticEvent;
} catch {
continue;
}
const phase = event.phase;
if (!phase) continue;
const ts = typeof event.ts === 'string' ? Date.parse(event.ts) : Number.NaN;
if (Number.isFinite(ts)) {
firstTs ??= ts;
lastTs = ts;
}
const data = event.data ?? {};
const duration = eventDuration(event);
if (phase === SPAWN_PHASE) {
if (data.event !== 'settled') continue;
addTiming(profile.spawns, text(data.command) ?? 'unknown', duration);
} else if (phase === RUNNER_COMMAND_PHASE) {
addTiming(profile.runnerCommands, text(data.command) ?? 'unknown', duration);
} else if (phase === SNAPSHOT_SOURCE_PHASE) {
const producer = text(data.producer) ?? 'unknown';
const entry = (profile.snapshotSources[producer] ??= { count: 0, totalMs: 0, failures: 0 });
entry.count += 1;
entry.totalMs += duration ?? 0;
const error = text(data.error);
if (error || event.level === 'error') {
entry.failures += 1;
fallbacks.add(`${producer}: ${error ?? 'failed'}`);
}
} else if (phase === SNAPSHOT_RECOVERY_PHASE && data.truncated === true) {
fallbacks.add(
`${text(data.producer) ?? 'unknown'}: truncated at ${String(data.acceptedLevels)} levels`,
);
} else if (phase === 'retry' && data.event === 'attempt_failed') {
profile.retries += 1;
} else if (event.level === 'warn' || event.level === 'error') {
fallbacks.add(`${phase}${text(data.reason) ? `: ${text(data.reason)}` : ''}`);
}
if (STABILIZATION_PHASE.test(phase)) {
profile.stabilization.count += 1;
profile.stabilization.totalMs += duration ?? 0;
}
addTiming(profile.phases, phase, duration);
}
profile.fallbacks = [...fallbacks].sort();
if (firstTs !== undefined && lastTs !== undefined) profile.requestSpanMs = lastTs - firstTs;
return profile;
}
/** Reads the client's `daemon_request` timer and request id from `--debug` stderr. */
export function readClientDiagnostics(stderr: string): { daemonMs?: number; requestId?: string } {
for (const line of stderr.split('\n')) {
const start = line.indexOf(CLIENT_DIAG_PREFIX);
if (start < 0) continue;
try {
const event = JSON.parse(line.slice(start + CLIENT_DIAG_PREFIX.length)) as {
phase?: string;
durationMs?: number;
requestId?: string;
};
if (event.phase === 'daemon_request') {
return { daemonMs: event.durationMs, requestId: event.requestId };
}
} catch {
// A truncated diagnostic line carries no timer.
}
}
return {};
}
/** Reads the settle outcome of a `--settle` response. */
export function readSettleFacts(json: unknown): SettleFacts | undefined {
const settle = (json as { data?: { settle?: Record<string, unknown> } } | undefined)?.data
?.settle;
if (!settle || typeof settle.waitedMs !== 'number') return undefined;
return {
waitedMs: settle.waitedMs,
captures: typeof settle.captures === 'number' ? settle.captures : undefined,
settled: typeof settle.settled === 'boolean' ? settle.settled : undefined,
};
}
/** Reads snapshot quality facts from a `--json` snapshot response. */
export function readSnapshotFacts(json: unknown): SnapshotFacts | undefined {
const data = (json as { data?: Record<string, unknown> } | undefined)?.data;
if (!data || !Array.isArray(data.nodes)) return undefined;
const nodes = data.nodes as { depth?: unknown }[];
const quality = (data.snapshotQuality ?? {}) as Record<string, unknown>;
const depths = nodes.map((node) => (typeof node.depth === 'number' ? node.depth : 0));
return {
backend: text(quality.backend),
state: text(quality.state),
reasonCode: text(quality.reasonCode),
nodeCount: nodes.length,
maxDepth: depths.length > 0 ? Math.max(...depths) : undefined,
truncated: typeof data.truncated === 'boolean' ? data.truncated : undefined,
};
}
function medianOrNull(values: number[]): number | null {
return values.length === 0 ? null : median(values);
}
function sumTimings(map: Record<string, Timing>): Timing {
return Object.values(map).reduce(
(sum, t) => ({ count: sum.count + t.count, totalMs: sum.totalMs + t.totalMs }),
{ count: 0, totalMs: 0 },
);
}
function tally(counts: Record<string, number>, keys: Iterable<string>): void {
for (const key of new Set(keys)) counts[key] = (counts[key] ?? 0) + 1;
}
/**
* Summarizes the successful samples' profiles. Medians describe a typical request; producers,
* backends, and fallbacks count how many samples took each path.
*/
export function aggregateProfiles(samples: Sample[]): MeasurementProfile | null {
const profiled = samples.filter((s) => s.ok && s.profile);
if (profiled.length === 0) return null;
const profiles = profiled.map((s) => s.profile!);
const producers: Record<string, number> = {};
const backends: Record<string, number> = {};
const fallbacks: Record<string, number> = {};
for (const sample of profiled) {
const profile = sample.profile!;
tally(
producers,
Object.entries(profile.snapshotSources)
.filter(([, source]) => source.count > source.failures)
.map(([producer]) => producer),
);
if (profile.runnerCommands.snapshot) tally(producers, ['apple-runner']);
if (sample.snapshot?.backend) {
const { backend, state, reasonCode } = sample.snapshot;
tally(backends, [[backend, state, reasonCode].filter(Boolean).join('/')]);
}
tally(fallbacks, profile.fallbacks);
}
const phaseNames = new Set(profiles.flatMap((p) => Object.keys(p.phases)));
const topPhases = [...phaseNames]
.map((phase) => ({
phase,
medianMs: median(profiles.map((p) => p.phases[phase]?.totalMs ?? 0)),
}))
.filter((entry) => entry.medianMs > 0)
.sort((a, b) => b.medianMs - a.medianMs)
.slice(0, 5);
return {
runnerMs: medianOrNull(profiles.map((p) => sumTimings(p.runnerCommands).totalMs)),
spawnCount: medianOrNull(profiles.map((p) => sumTimings(p.spawns).count)),
spawnMs: medianOrNull(profiles.map((p) => sumTimings(p.spawns).totalMs)),
snapshotSourceMs: medianOrNull(profiles.map((p) => sumTimings(p.snapshotSources).totalMs)),
stabilizationMs: medianOrNull(profiles.map((p) => p.stabilization.totalMs)),
settleWaitMs: medianOrNull(profiled.flatMap((s) => (s.settle ? [s.settle.waitedMs] : []))),
retries: profiles.reduce((sum, p) => sum + p.retries, 0),
producers,
backends,
fallbacks,
topPhases,
};
}