GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — perf(server): track Claude descendants with the macOS resource monito… · patroza/t3code@3ed650f

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • .github/workflows
    • release-desktop.yml
  • apps/server/src
    • orchestration-v2/Adapters
      • ClaudeAdapterV2.ts
      • ClaudeAgentSdkQueryRunner.test.ts
    • resourceTelemetry
      • NativeTelemetryClient.test.ts
      • NativeTelemetryClient.ts
    • server.ts
  • native/resource-monitor
    • Cargo.lock
    • Cargo.toml
    • build.rs
    • src
      • main.rs
      • process_identities.c
  • packages/contracts/src
    • resourceTelemetry.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎.github/workflows/release-desktop.yml‎

Copy file name to clipboardExpand all lines: .github/workflows/release-desktop.yml
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ jobs:
212212
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
213213
with:
214214
path: native/resource-monitor/target/${{ inputs.rust_target }}/release/t3-resource-monitor${{ inputs.platform == 'win' && '.exe' || '' }}
215-
key: resource-monitor-${{ inputs.rust_target }}-${{ hashFiles('.cargo/config.toml', 'native/resource-monitor/Cargo.lock', 'native/resource-monitor/Cargo.toml', 'native/resource-monitor/src/**') }}
215+
key: resource-monitor-${{ inputs.rust_target }}-${{ hashFiles('.cargo/config.toml', 'native/resource-monitor/Cargo.lock', 'native/resource-monitor/Cargo.toml', 'native/resource-monitor/build.rs', 'native/resource-monitor/src/**') }}
216216

217217
- name: Cache Linux capture helpers
218218
if: inputs.platform == 'linux'
Collapse file

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+88-36Lines changed: 88 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,7 @@ import {
194194
type CompiledClaudeModelSelection,
195195
} from "../../claudeModelOptions.ts";
196196
import * as ServerConfig from "../../config.ts";
197+
import { NativeTelemetryClient } from "../../resourceTelemetry/NativeTelemetryClient.ts";
197198
import * as PortScanner from "../../preview/PortScanner.ts";
198199
import * as ProcessRunner from "../../processRunner.ts";
199200
import * as ServerSettings from "../../serverSettings.ts";
@@ -489,25 +490,32 @@ interface ClaudeProcessRow {
489490
readonly pid: number;
490491
readonly ppid: number;
491492
readonly pgid: number;
492-
readonly started: string;
493+
readonly startTimeSeconds: number;
494+
readonly startTimeMicros?: number;
493495
}
494496

495-
/** Parses `ps -A -o pid=,ppid=,pgid=,lstart=`; pid plus start time tells a process from a reused pid. */
497+
const isClaudeProcessRow = Schema.is(
498+
Schema.Struct({
499+
pid: Schema.Int,
500+
ppid: Schema.Int,
501+
pgid: Schema.Int,
502+
startTimeSeconds: Schema.Int,
503+
}),
504+
);
505+
506+
/** Parses the C-locale, UTC output of `ps -A -o pid=,ppid=,pgid=,lstart=`. */
496507
function parseClaudeProcessTable(table: string): ReadonlyArray<ClaudeProcessRow> {
497508
return table.split("\n").flatMap((line) => {
498509
const [pid, ppid, pgid, ...started] = line.trim().split(/\s+/);
510+
const start = DateTime.make(started.join(" ") + " GMT");
511+
if (Option.isNone(start)) return [];
499512
const row = {
500513
pid: Number(pid),
501514
ppid: Number(ppid),
502515
pgid: Number(pgid),
503-
started: started.join(" "),
516+
startTimeSeconds: DateTime.toEpochSeconds(start.value),
504517
};
505-
return Number.isSafeInteger(row.pid) &&
506-
Number.isSafeInteger(row.ppid) &&
507-
Number.isSafeInteger(row.pgid) &&
508-
row.started
509-
? [row]
510-
: [];
518+
return isClaudeProcessRow(row) ? [row] : [];
511519
});
512520
}
513521

@@ -519,11 +527,19 @@ function killClaudeDescendant(row: ClaudeProcessRow) {
519527
} catch {}
520528
}
521529

530+
function indexClaudeProcessTable(rows: ReadonlyArray<ClaudeProcessRow>) {
531+
return {
532+
byPid: new Map(rows.map((row) => [row.pid, row] as const)),
533+
children: Map.groupBy(rows, (row) => row.ppid),
534+
};
535+
}
536+
537+
type ClaudeProcessTable = ReturnType<typeof indexClaudeProcessTable>;
538+
522539
function claudeDescendants(
523-
rows: ReadonlyArray<ClaudeProcessRow>,
540+
{ children }: ClaudeProcessTable,
524541
rootPids: ReadonlyArray<number>,
525542
): ReadonlyArray<ClaudeProcessRow> {
526-
const children = Map.groupBy(rows, (row) => row.ppid);
527543
const found: Array<ClaudeProcessRow> = [];
528544
const seen = new Set<number>(rootPids);
529545
const pending = [...rootPids];
@@ -538,25 +554,34 @@ function claudeDescendants(
538554
return found;
539555
}
540556

541-
const processIdentity = (row: ClaudeProcessRow) => `${row.pid} ${row.started}`;
542-
543-
/** What one CLI started, by pid and start time, recorded from each process table read while it runs. */
557+
/** What one CLI started, validated by pid and start time on every successful read. */
544558
function makeClaudeDescendantTracker(cliPid: number) {
545-
const tracked = new Map<string, ClaudeProcessRow>();
546-
// After exit the CLI's pid may belong to an unrelated process, so only tracked jobs are roots.
547-
const record = (rows: ReadonlyArray<ClaudeProcessRow>, cliRunning: boolean) => {
548-
const running = new Set(rows.map(processIdentity));
549-
// `ps -A` lists itself, so no rows is a failed read.
550-
if (rows.length === 0) return running;
559+
const tracked = new Map<number, ClaudeProcessRow>();
560+
const record = (table: ClaudeProcessTable, cliRunning: boolean) => {
561+
// An empty table means the read failed. Keep the previous observations for a later read.
562+
if (table.byPid.size === 0) return;
551563
const roots = cliRunning ? [cliPid] : [];
552-
for (const [key, row] of tracked) {
553-
if (running.has(key)) roots.push(row.pid);
554-
else tracked.delete(key);
564+
for (const [pid, row] of tracked) {
565+
const current = table.byPid.get(pid);
566+
if (
567+
current?.startTimeSeconds === row.startTimeSeconds &&
568+
(current.startTimeMicros === undefined ||
569+
row.startTimeMicros === undefined ||
570+
current.startTimeMicros === row.startTimeMicros)
571+
) {
572+
roots.push(pid);
573+
// Preserve the finer identity across an intervening ps fallback.
574+
tracked.set(
575+
pid,
576+
current.startTimeMicros === undefined && row.startTimeMicros !== undefined
577+
? { ...current, startTimeMicros: row.startTimeMicros }
578+
: current,
579+
);
580+
} else tracked.delete(pid);
555581
}
556-
for (const row of claudeDescendants(rows, roots)) tracked.set(processIdentity(row), row);
557-
return running;
582+
for (const row of claudeDescendants(table, roots)) tracked.set(row.pid, row);
558583
};
559-
return { tracked: tracked as ReadonlyMap<string, ClaudeProcessRow>, record };
584+
return { tracked: tracked as ReadonlyMap<number, ClaudeProcessRow>, record };
560585
}
561586

562587
/**
@@ -571,8 +596,9 @@ export function makeClaudeDescendantPoll(
571596
// Polls, session closes and exits read one at a time, so each table is newer than all recorded,
572597
// and a pid and start time it no longer lists never run again.
573598
const reading = Semaphore.makeUnsafe(1);
574-
const read = <A>(apply: (rows: ReadonlyArray<ClaudeProcessRow>) => A) =>
575-
reading.withPermits(1)(readProcessTable.pipe(Effect.map(apply)));
599+
const indexedTable = readProcessTable.pipe(Effect.map(indexClaudeProcessTable));
600+
const read = <A>(apply: (table: ClaudeProcessTable) => A) =>
601+
reading.withPermits(1)(indexedTable.pipe(Effect.map(apply)));
576602
return {
577603
// A table read before a CLI started may list an older process under its pid, so a poll records
578604
// only into the CLIs working when its read began.
@@ -583,7 +609,7 @@ export function makeClaudeDescendantPoll(
583609
.withPermits(1)(
584610
Effect.suspend(() => {
585611
const working = [...live];
586-
return readProcessTable.pipe(
612+
return indexedTable.pipe(
587613
Effect.map((rows) => {
588614
for (const tracker of working)
589615
if (live.has(tracker)) tracker.record(rows, true);
@@ -596,7 +622,7 @@ export function makeClaudeDescendantPoll(
596622
track: (cliPid: number) => {
597623
const tracker = makeClaudeDescendantTracker(cliPid);
598624
let exited = false;
599-
const refresh = read((rows) => void tracker.record(rows, true));
625+
const refresh = read((rows) => void tracker.record(rows, !exited));
600626
return {
601627
tracked: tracker.tracked,
602628
refresh,
@@ -615,10 +641,8 @@ export function makeClaudeDescendantPoll(
615641
}).pipe(
616642
Effect.andThen(
617643
read((rows) => {
618-
const running = tracker.record(rows, false);
619-
return [...tracker.tracked.values()].filter((row) =>
620-
running.has(processIdentity(row)),
621-
);
644+
tracker.record(rows, false);
645+
return rows.byPid.size === 0 ? [] : [...tracker.tracked.values()];
622646
}),
623647
),
624648
),
@@ -1644,12 +1668,40 @@ export const layerQueryRunner: Layer.Layer<
16441668
const hostEnvironment = yield* HostProcess.Environment;
16451669
const portDiscovery = yield* PortScanner.PortDiscovery;
16461670
const processRunner = yield* ProcessRunner.make();
1647-
const readProcessTable = processRunner
1648-
.run({ command: "ps", args: ["-A", "-o", "pid=,ppid=,pgid=,lstart="], timeout: "5 seconds" })
1671+
const psProcessTable = processRunner
1672+
.run({
1673+
command: "ps",
1674+
args: ["-A", "-o", "pid=,ppid=,pgid=,lstart="],
1675+
env: { LC_ALL: "C", TZ: "UTC0" },
1676+
timeout: "5 seconds",
1677+
})
16491678
.pipe(
16501679
Effect.map((result) => (result.code === 0 ? parseClaudeProcessTable(result.stdout) : [])),
16511680
Effect.orElseSucceed(() => []),
16521681
);
1682+
const monitor = Option.getOrUndefined(yield* Effect.serviceOption(NativeTelemetryClient));
1683+
const nativeTable = platform === "darwin" ? monitor?.processIdentities : undefined;
1684+
// Both readers use epoch seconds so a sidecar restart preserves tracked orphans.
1685+
const readProcessTable =
1686+
nativeTable === undefined
1687+
? psProcessTable
1688+
: nativeTable.pipe(
1689+
Effect.flatMap((rows) => {
1690+
const table: ClaudeProcessRow[] = [];
1691+
for (const { pid, ppid, pgid, startTimeMicros } of rows) {
1692+
if (pgid === undefined || startTimeMicros === undefined) return psProcessTable;
1693+
table.push({
1694+
pid,
1695+
ppid,
1696+
pgid,
1697+
startTimeSeconds: Math.floor(startTimeMicros / 1_000_000),
1698+
startTimeMicros,
1699+
});
1700+
}
1701+
return table.length === 0 ? psProcessTable : Effect.succeed(table);
1702+
}),
1703+
Effect.catch(() => psProcessTable),
1704+
);
16531705
// Without an agent scope, a job that left the CLI's group escapes the group kill and is
16541706
// re-parented once the CLI exits. So the CLI's tree is recorded while it runs, and what is
16551707
// still the same process (pid and start time) is stopped after it exits.
Collapse file

‎apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
+20-1Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -763,7 +763,7 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
763763
pid,
764764
ppid,
765765
pgid: pid,
766-
started: `Sun Nov 15 10:00:0${startedSecond} 2026`,
766+
startTimeSeconds: startedSecond,
767767
});
768768
const byNumber = (left: number, right: number) => left - right;
769769

@@ -828,6 +828,25 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
828828
},
829829
);
830830

831+
it.effect("rejects a same-second pid reuse after an intervening lower precision snapshot", () => {
832+
const cli = processRow(1000, 10, 0);
833+
const child = processRow(1100, 1000, 1);
834+
const orphan = { ...child, ppid: 1 };
835+
const tables = [
836+
[cli, { ...child, startTimeMicros: 1000001 }],
837+
[cli, orphan],
838+
[{ ...orphan, startTimeMicros: 1000002 }, processRow(1101, orphan.pid, 2)],
839+
];
840+
const tracker = makeClaudeDescendantPoll(Effect.sync(() => tables.shift() ?? [])).track(
841+
cli.pid,
842+
);
843+
return Effect.gen(function* () {
844+
yield* tracker.refresh;
845+
yield* tracker.refresh;
846+
assert.deepStrictEqual(yield* tracker.leftovers, []);
847+
});
848+
});
849+
831850
// The poll and a session close read the table independently. The older table still lists a
832851
// re-parented job and the child it just started; the newer one lists a job started since.
833852
it.effect(
Collapse file

‎apps/server/src/resourceTelemetry/NativeTelemetryClient.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/resourceTelemetry/NativeTelemetryClient.test.ts
+19Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,15 @@ import type { HostPowerSnapshot } from "@t3tools/contracts";
22
import { describe, expect, it } from "@effect/vitest";
33
import * as DateTime from "effect/DateTime";
44
import * as Deferred from "effect/Deferred";
5+
import * as Duration from "effect/Duration";
6+
import * as TestClock from "effect/testing/TestClock";
57
import * as Effect from "effect/Effect";
68
import * as Fiber from "effect/Fiber";
79
import * as Ref from "effect/Ref";
810
import * as Semaphore from "effect/Semaphore";
911

1012
import {
13+
requestProcessTable,
1114
commitCollectionControlUpdate,
1215
synchronizeCollectionControlOnStart,
1316
} from "./NativeTelemetryClient.ts";
@@ -138,3 +141,19 @@ describe("commitCollectionControlUpdate", () => {
138141
}),
139142
);
140143
});
144+
145+
it.effect("bounds a process-table write that outlasts the deadline", () =>
146+
Effect.gen(function* () {
147+
const response = yield* Deferred.make<void>();
148+
const writing = yield* Deferred.make<void>();
149+
const fiber = yield* requestProcessTable(
150+
Deferred.succeed(writing, undefined).pipe(Effect.andThen(Effect.sleep(300))),
151+
response,
152+
Duration.millis(250),
153+
).pipe(Effect.flip, Effect.forkChild);
154+
yield* Deferred.await(writing);
155+
yield* TestClock.adjust(250);
156+
expect(fiber.pollUnsafe()?._tag).toBe("Success");
157+
expect((yield* Fiber.join(fiber)).timeoutMs).toBe(250);
158+
}),
159+
);
Collapse file

‎apps/server/src/resourceTelemetry/NativeTelemetryClient.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/resourceTelemetry/NativeTelemetryClient.ts
+39-21Lines changed: 39 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,10 @@ export class NativeTelemetryClient extends Context.Service<
195195
snapshot: HostPowerSnapshot,
196196
) => Effect.Effect<void, NativeTelemetryClientError>;
197197
readonly sampleNow: Effect.Effect<NativeTelemetrySnapshot, NativeTelemetryClientError>;
198+
readonly processIdentities?: Effect.Effect<
199+
ReadonlyArray<ResourceMonitorProcessTableEntry>,
200+
NativeTelemetryClientError
201+
>;
198202
readonly processTable: Effect.Effect<
199203
ReadonlyArray<ResourceMonitorProcessTableEntry>,
200204
NativeTelemetryClientError
@@ -361,6 +365,26 @@ function canCommandNativeTelemetrySidecar(
361365
return hasHandle && (status === "healthy" || status === "degraded");
362366
}
363367

368+
export function requestProcessTable<A, E>(
369+
write: Effect.Effect<void, E>,
370+
response: Deferred.Deferred<A, E>,
371+
timeout: Duration.Duration,
372+
) {
373+
return write.pipe(
374+
Effect.andThen(Deferred.await(response)),
375+
Effect.timeoutOrElse({
376+
duration: timeout,
377+
orElse: () =>
378+
Effect.fail(
379+
new NativeTelemetryRequestTimedOut({
380+
operation: "processTable",
381+
timeoutMs: Duration.toMillis(timeout),
382+
}),
383+
),
384+
}),
385+
);
386+
}
387+
364388
/** @public */
365389
export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(function* () {
366390
const binary = yield* ResourceMonitorBinary.ResourceMonitorBinary;
@@ -441,6 +465,8 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
441465
cause,
442466
}),
443467
),
468+
// One complete NDJSON frame per Writable.write. Interrupting a drain wait
469+
// leaves the accepted buffer in Node's ordered queue (stdin has endOnDone: false).
444470
Effect.flatMap((encoded) =>
445471
Stream.run(Stream.encodeText(Stream.make(encoded)), handle.stdin),
446472
),
@@ -970,14 +996,20 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
970996
);
971997
});
972998

973-
const processTable: NativeTelemetryClient["Service"]["processTable"] = Effect.gen(function* () {
999+
const processTable = Effect.fnUntraced(function* (identities: boolean) {
9741000
const current = yield* Ref.get(state);
9751001
if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) {
9761002
return yield* new NativeTelemetryUnavailable({
9771003
reason: Option.getOrElse(current.lastError, () => "sidecar is not running"),
9781004
});
9791005
}
9801006

1007+
if (identities && !Option.getOrUndefined(current.hello)?.capabilities.processIdentities) {
1008+
return yield* new NativeTelemetryUnavailable({ reason: "process identities unavailable" });
1009+
}
1010+
1011+
// A busy monitor must leave time for the cleanup tracker's ps fallback.
1012+
const timeout = identities ? Duration.millis(250) : PROCESS_TABLE_REQUEST_TIMEOUT;
9811013
const requestId = yield* random
9821014
.uuidV4()
9831015
.pipe(
@@ -994,28 +1026,13 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
9941026
next.set(requestId, deferred);
9951027
return next;
9961028
});
997-
return yield* writeCommand(Option.getOrThrow(current.handle), {
1029+
const write = writeCommand(Option.getOrThrow(current.handle), {
9981030
version: RESOURCE_MONITOR_PROTOCOL_VERSION,
9991031
type: "processTable",
1032+
...(identities ? { identities } : {}),
10001033
requestId,
1001-
}).pipe(
1002-
Effect.andThen(
1003-
Deferred.await(deferred).pipe(
1004-
Effect.timeoutOption(PROCESS_TABLE_REQUEST_TIMEOUT),
1005-
Effect.flatMap(
1006-
Option.match({
1007-
onNone: () =>
1008-
Effect.fail(
1009-
new NativeTelemetryRequestTimedOut({
1010-
operation: "processTable",
1011-
timeoutMs: Duration.toMillis(PROCESS_TABLE_REQUEST_TIMEOUT),
1012-
}),
1013-
),
1014-
onSome: Effect.succeed,
1015-
}),
1016-
),
1017-
),
1018-
),
1034+
});
1035+
return yield* requestProcessTable(write, deferred, timeout).pipe(
10191036
Effect.ensuring(
10201037
Ref.update(pendingProcessTables, (pending) => {
10211038
const next = new Map(pending);
@@ -1047,7 +1064,8 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu
10471064
setExternalProcesses,
10481065
setHostPowerState,
10491066
sampleNow,
1050-
processTable,
1067+
processTable: processTable(false),
1068+
processIdentities: processTable(true),
10511069
retry: Ref.get(state).pipe(
10521070
Effect.flatMap((current) =>
10531071
!canRequestNativeTelemetryRetry(current.status, Option.isSome(current.handle))

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.