GeezerVison is showing github.com — perf(server): track Claude descendants with the macOS resource monito… · patroza/t3code@3ed650f
File treeExpand file treeCollapse file tree Open diff view settings orchestration-v2/Adapters
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: .github/workflows/release-desktop.yml +1-1Lines changed: 1 addition & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -212,7 +212,7 @@ jobs: | 212 | 212 | uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 | 213 | 213 | with: | 214 | 214 | 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/**') }} | 216 | 216 |
| 217 | 217 | - name: Cache Linux capture helpers | 218 | 218 | if: inputs.platform == 'linux' | |
Collapse file 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 number | Diff line number | Diff line change |
|---|
@@ -194,6 +194,7 @@ import { | 194 | 194 | type CompiledClaudeModelSelection, | 195 | 195 | } from "../../claudeModelOptions.ts"; | 196 | 196 | import * as ServerConfig from "../../config.ts"; | | 197 | +import { NativeTelemetryClient } from "../../resourceTelemetry/NativeTelemetryClient.ts"; | 197 | 198 | import * as PortScanner from "../../preview/PortScanner.ts"; | 198 | 199 | import * as ProcessRunner from "../../processRunner.ts"; | 199 | 200 | import * as ServerSettings from "../../serverSettings.ts"; | @@ -489,25 +490,32 @@ interface ClaudeProcessRow { | 489 | 490 | readonly pid: number; | 490 | 491 | readonly ppid: number; | 491 | 492 | readonly pgid: number; | 492 | | - readonly started: string; | | 493 | + readonly startTimeSeconds: number; | | 494 | + readonly startTimeMicros?: number; | 493 | 495 | } | 494 | 496 |
| 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=`. */ | 496 | 507 | function parseClaudeProcessTable(table: string): ReadonlyArray<ClaudeProcessRow> { | 497 | 508 | return table.split("\n").flatMap((line) => { | 498 | 509 | const [pid, ppid, pgid, ...started] = line.trim().split(/\s+/); | | 510 | + const start = DateTime.make(started.join(" ") + " GMT"); | | 511 | + if (Option.isNone(start)) return []; | 499 | 512 | const row = { | 500 | 513 | pid: Number(pid), | 501 | 514 | ppid: Number(ppid), | 502 | 515 | pgid: Number(pgid), | 503 | | - started: started.join(" "), | | 516 | + startTimeSeconds: DateTime.toEpochSeconds(start.value), | 504 | 517 | }; | 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] : []; | 511 | 519 | }); | 512 | 520 | } | 513 | 521 |
| @@ -519,11 +527,19 @@ function killClaudeDescendant(row: ClaudeProcessRow) { | 519 | 527 | } catch {} | 520 | 528 | } | 521 | 529 |
| | 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 | + | 522 | 539 | function claudeDescendants( | 523 | | - rows: ReadonlyArray<ClaudeProcessRow>, | | 540 | + { children }: ClaudeProcessTable, | 524 | 541 | rootPids: ReadonlyArray<number>, | 525 | 542 | ): ReadonlyArray<ClaudeProcessRow> { | 526 | | - const children = Map.groupBy(rows, (row) => row.ppid); | 527 | 543 | const found: Array<ClaudeProcessRow> = []; | 528 | 544 | const seen = new Set<number>(rootPids); | 529 | 545 | const pending = [...rootPids]; | @@ -538,25 +554,34 @@ function claudeDescendants( | 538 | 554 | return found; | 539 | 555 | } | 540 | 556 |
| 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. */ | 544 | 558 | 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; | 551 | 563 | 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); | 555 | 581 | } | 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); | 558 | 583 | }; | 559 | | - return { tracked: tracked as ReadonlyMap<string, ClaudeProcessRow>, record }; | | 584 | + return { tracked: tracked as ReadonlyMap<number, ClaudeProcessRow>, record }; | 560 | 585 | } | 561 | 586 |
| 562 | 587 | /** | @@ -571,8 +596,9 @@ export function makeClaudeDescendantPoll( | 571 | 596 | // Polls, session closes and exits read one at a time, so each table is newer than all recorded, | 572 | 597 | // and a pid and start time it no longer lists never run again. | 573 | 598 | 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))); | 576 | 602 | return { | 577 | 603 | // A table read before a CLI started may list an older process under its pid, so a poll records | 578 | 604 | // only into the CLIs working when its read began. | @@ -583,7 +609,7 @@ export function makeClaudeDescendantPoll( | 583 | 609 | .withPermits(1)( | 584 | 610 | Effect.suspend(() => { | 585 | 611 | const working = [...live]; | 586 | | - return readProcessTable.pipe( | | 612 | + return indexedTable.pipe( | 587 | 613 | Effect.map((rows) => { | 588 | 614 | for (const tracker of working) | 589 | 615 | if (live.has(tracker)) tracker.record(rows, true); | @@ -596,7 +622,7 @@ export function makeClaudeDescendantPoll( | 596 | 622 | track: (cliPid: number) => { | 597 | 623 | const tracker = makeClaudeDescendantTracker(cliPid); | 598 | 624 | let exited = false; | 599 | | - const refresh = read((rows) => void tracker.record(rows, true)); | | 625 | + const refresh = read((rows) => void tracker.record(rows, !exited)); | 600 | 626 | return { | 601 | 627 | tracked: tracker.tracked, | 602 | 628 | refresh, | @@ -615,10 +641,8 @@ export function makeClaudeDescendantPoll( | 615 | 641 | }).pipe( | 616 | 642 | Effect.andThen( | 617 | 643 | 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()]; | 622 | 646 | }), | 623 | 647 | ), | 624 | 648 | ), | @@ -1644,12 +1668,40 @@ export const layerQueryRunner: Layer.Layer< | 1644 | 1668 | const hostEnvironment = yield* HostProcess.Environment; | 1645 | 1669 | const portDiscovery = yield* PortScanner.PortDiscovery; | 1646 | 1670 | 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 | + }) | 1649 | 1678 | .pipe( | 1650 | 1679 | Effect.map((result) => (result.code === 0 ? parseClaudeProcessTable(result.stdout) : [])), | 1651 | 1680 | Effect.orElseSucceed(() => []), | 1652 | 1681 | ); | | 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 | + ); | 1653 | 1705 | // Without an agent scope, a job that left the CLI's group escapes the group kill and is | 1654 | 1706 | // re-parented once the CLI exits. So the CLI's tree is recorded while it runs, and what is | 1655 | 1707 | // still the same process (pid and start time) is stopped after it exits. | |
Collapse file 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 number | Diff line number | Diff line change |
|---|
@@ -763,7 +763,7 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro | 763 | 763 | pid, | 764 | 764 | ppid, | 765 | 765 | pgid: pid, | 766 | | - started: `Sun Nov 15 10:00:0${startedSecond} 2026`, | | 766 | + startTimeSeconds: startedSecond, | 767 | 767 | }); | 768 | 768 | const byNumber = (left: number, right: number) => left - right; | 769 | 769 |
| @@ -828,6 +828,25 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro | 828 | 828 | }, | 829 | 829 | ); | 830 | 830 |
| | 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 | + | 831 | 850 | // The poll and a session close read the table independently. The older table still lists a | 832 | 851 | // re-parented job and the child it just started; the newer one lists a job started since. | 833 | 852 | it.effect( | |
Collapse file Copy file name to clipboardExpand all lines: apps/server/src/resourceTelemetry/NativeTelemetryClient.test.ts +19Lines changed: 19 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -2,12 +2,15 @@ import type { HostPowerSnapshot } from "@t3tools/contracts"; | 2 | 2 | import { describe, expect, it } from "@effect/vitest"; | 3 | 3 | import * as DateTime from "effect/DateTime"; | 4 | 4 | import * as Deferred from "effect/Deferred"; | | 5 | +import * as Duration from "effect/Duration"; | | 6 | +import * as TestClock from "effect/testing/TestClock"; | 5 | 7 | import * as Effect from "effect/Effect"; | 6 | 8 | import * as Fiber from "effect/Fiber"; | 7 | 9 | import * as Ref from "effect/Ref"; | 8 | 10 | import * as Semaphore from "effect/Semaphore"; | 9 | 11 |
| 10 | 12 | import { | | 13 | + requestProcessTable, | 11 | 14 | commitCollectionControlUpdate, | 12 | 15 | synchronizeCollectionControlOnStart, | 13 | 16 | } from "./NativeTelemetryClient.ts"; | @@ -138,3 +141,19 @@ describe("commitCollectionControlUpdate", () => { | 138 | 141 | }), | 139 | 142 | ); | 140 | 143 | }); | | 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 Copy file name to clipboardExpand all lines: apps/server/src/resourceTelemetry/NativeTelemetryClient.ts +39-21Lines changed: 39 additions & 21 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -195,6 +195,10 @@ export class NativeTelemetryClient extends Context.Service< | 195 | 195 | snapshot: HostPowerSnapshot, | 196 | 196 | ) => Effect.Effect<void, NativeTelemetryClientError>; | 197 | 197 | readonly sampleNow: Effect.Effect<NativeTelemetrySnapshot, NativeTelemetryClientError>; | | 198 | + readonly processIdentities?: Effect.Effect< | | 199 | + ReadonlyArray<ResourceMonitorProcessTableEntry>, | | 200 | + NativeTelemetryClientError | | 201 | + >; | 198 | 202 | readonly processTable: Effect.Effect< | 199 | 203 | ReadonlyArray<ResourceMonitorProcessTableEntry>, | 200 | 204 | NativeTelemetryClientError | @@ -361,6 +365,26 @@ function canCommandNativeTelemetrySidecar( | 361 | 365 | return hasHandle && (status === "healthy" || status === "degraded"); | 362 | 366 | } | 363 | 367 |
| | 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 | + | 364 | 388 | /** @public */ | 365 | 389 | export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(function* () { | 366 | 390 | const binary = yield* ResourceMonitorBinary.ResourceMonitorBinary; | @@ -441,6 +465,8 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu | 441 | 465 | cause, | 442 | 466 | }), | 443 | 467 | ), | | 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). | 444 | 470 | Effect.flatMap((encoded) => | 445 | 471 | Stream.run(Stream.encodeText(Stream.make(encoded)), handle.stdin), | 446 | 472 | ), | @@ -970,14 +996,20 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu | 970 | 996 | ); | 971 | 997 | }); | 972 | 998 |
| 973 | | - const processTable: NativeTelemetryClient["Service"]["processTable"] = Effect.gen(function* () { | | 999 | + const processTable = Effect.fnUntraced(function* (identities: boolean) { | 974 | 1000 | const current = yield* Ref.get(state); | 975 | 1001 | if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) { | 976 | 1002 | return yield* new NativeTelemetryUnavailable({ | 977 | 1003 | reason: Option.getOrElse(current.lastError, () => "sidecar is not running"), | 978 | 1004 | }); | 979 | 1005 | } | 980 | 1006 |
| | 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; | 981 | 1013 | const requestId = yield* random | 982 | 1014 | .uuidV4() | 983 | 1015 | .pipe( | @@ -994,28 +1026,13 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu | 994 | 1026 | next.set(requestId, deferred); | 995 | 1027 | return next; | 996 | 1028 | }); | 997 | | - return yield* writeCommand(Option.getOrThrow(current.handle), { | | 1029 | + const write = writeCommand(Option.getOrThrow(current.handle), { | 998 | 1030 | version: RESOURCE_MONITOR_PROTOCOL_VERSION, | 999 | 1031 | type: "processTable", | | 1032 | + ...(identities ? { identities } : {}), | 1000 | 1033 | 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( | 1019 | 1036 | Effect.ensuring( | 1020 | 1037 | Ref.update(pendingProcessTables, (pending) => { | 1021 | 1038 | const next = new Map(pending); | @@ -1047,7 +1064,8 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu | 1047 | 1064 | setExternalProcesses, | 1048 | 1065 | setHostPowerState, | 1049 | 1066 | sampleNow, | 1050 | | - processTable, | | 1067 | + processTable: processTable(false), | | 1068 | + processIdentities: processTable(true), | 1051 | 1069 | retry: Ref.get(state).pipe( | 1052 | 1070 | Effect.flatMap((current) => | 1053 | 1071 | !canRequestNativeTelemetryRetry(current.status, Option.isSome(current.handle)) | |
|