Skip to content

Commit f21179d

Browse files
committed
refactor(daemon): point every startup-marker consumer at the new owner
Importers attach to daemon-contracts/daemon-startup-phases directly; daemon-registration-owner keeps only the sweep call at acquisition. src/daemon.ts captures its host environment once and resolves the phases path from the same env and cwd startDaemonRuntime resolves its state dir from, so a relative AGENT_DEVICE_STATE_DIR cannot land the earliest markers beside a different directory than the registration (the module top-level second resolveDaemonPaths(process.env) is gone), and the modules-loaded marker stays the first thing recorded. Addresses review 6248815887 items 1 and 2 on #3791. Refs #3782, #3791
1 parent 054ed62 commit f21179d

7 files changed

Lines changed: 24 additions & 306 deletions

File tree

‎packages/daemon-contracts/src/daemon-registration-owner-startup-markers.test.ts‎

Lines changed: 0 additions & 153 deletions
This file was deleted.

‎packages/daemon-contracts/src/daemon-registration-owner.ts‎

Lines changed: 1 addition & 140 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import {
1010
type DaemonTerminationResult,
1111
} from './daemon-process.ts';
1212
import {
13-
isProcessAlive,
1413
readCurrentOwnerIdentity,
1514
readProcessStartTime,
1615
type OwnerIdentity,
@@ -45,148 +44,10 @@ import {
4544
resolveDaemonShutdownReportPath,
4645
type DaemonShutdownOutcome,
4746
} from './daemon-shutdown-report.ts';
47+
import { sweepDeadDaemonStartupPhasesFiles } from './daemon-startup-phases.ts';
4848

4949
export const DAEMON_STARTUP_EXIT_CODES = Object.freeze({ busy: 75, unproven: 78 });
5050

51-
/**
52-
* Startup phase markers: a per-launch record, named for the writing pid, of how far that startup
53-
* got, so a waiting client tells "slow but progressing" from "stuck" without a timestamp and with
54-
* no heartbeat. The writer removes it on completion, the launching client after a joined exit, and
55-
* each new registration owner sweeps the files of provably dead pids.
56-
*/
57-
const DAEMON_STARTUP_PHASES = Object.freeze([
58-
'modules-loaded',
59-
'composition-loaded',
60-
'lock-acquired',
61-
'recovery-finished',
62-
'listening',
63-
'registered',
64-
] as const);
65-
66-
export type DaemonStartupPhase = (typeof DAEMON_STARTUP_PHASES)[number];
67-
68-
const DAEMON_STARTUP_PHASE_SET: ReadonlySet<string> = new Set<string>(DAEMON_STARTUP_PHASES);
69-
70-
const DAEMON_STARTUP_PHASES_ENTRY = /^daemon-startup-phases-(\d*)\.jsonl$/;
71-
72-
/** The marker file the daemon process `pid` writes in `stateDir`; an absent file is no evidence. */
73-
export function resolveDaemonStartupPhasesPath(stateDir: string, pid: number): string {
74-
return path.join(stateDir, `daemon-startup-phases-${pid}.jsonl`);
75-
}
76-
77-
/** Appends one phase marker; a refused append goes to `reportFailure`, never fatal to a startup. */
78-
export function recordDaemonStartupMarker(
79-
startupPhasesPath: string,
80-
phase: DaemonStartupPhase,
81-
reportFailure?: (error: NormalizedError) => void,
82-
): void {
83-
try {
84-
const timestampMs = Date.now();
85-
fs.mkdirSync(path.dirname(startupPhasesPath), { recursive: true });
86-
// A crash mid-append can leave no trailing newline; glue two appends and both are lost.
87-
const separator = endsWithoutNewline(startupPhasesPath) ? '\n' : '';
88-
fs.appendFileSync(
89-
startupPhasesPath,
90-
`${separator}${JSON.stringify({ data: { startupPhase: phase, timestampMs } })}\n`,
91-
);
92-
} catch (error) {
93-
reportFailure?.(normalizeError(error));
94-
}
95-
}
96-
97-
function endsWithoutNewline(file: string): boolean {
98-
let fd: number | undefined;
99-
try {
100-
const stats = fs.statSync(file);
101-
if (stats.size === 0) return false;
102-
const buffer = Buffer.alloc(1);
103-
fd = fs.openSync(file, 'r');
104-
if (fs.readSync(fd, buffer, 0, 1, stats.size - 1) !== 1) return false;
105-
return buffer[0] !== 0x0a;
106-
} catch {
107-
return false;
108-
} finally {
109-
if (fd !== undefined) fs.closeSync(fd);
110-
}
111-
}
112-
113-
/**
114-
* Empties this launch's own record before its first marker: a per-pid name identifies a writer,
115-
* not a lifetime. No caller resets a file named for another pid; a refused reset never stops the
116-
* startup because the reset ran first when it could run.
117-
*/
118-
export function claimDaemonStartupPhasesFile(
119-
startupPhasesPath: string,
120-
reportFailure?: (error: NormalizedError) => void,
121-
): void {
122-
try {
123-
fs.rmSync(startupPhasesPath, { force: true });
124-
} catch (error) {
125-
reportFailure?.(normalizeError(error));
126-
}
127-
}
128-
129-
/** Removes a marker file whose writer is provably gone: a finished startup or a joined exit. */
130-
export function removeDaemonStartupPhasesFile(startupPhasesPath: string): void {
131-
try {
132-
fs.rmSync(startupPhasesPath, { force: true });
133-
} catch {}
134-
}
135-
136-
/** Sweeps marker files of provably dead (or unnameable) pids; a live pid's file is kept. */
137-
function sweepDeadDaemonStartupPhasesFiles(stateDir: string): void {
138-
let entries: string[];
139-
try {
140-
entries = fs.readdirSync(stateDir);
141-
} catch {
142-
return;
143-
}
144-
for (const entry of entries) {
145-
const match = DAEMON_STARTUP_PHASES_ENTRY.exec(entry);
146-
if (match === null) continue;
147-
const deadPid = Number(match[1]);
148-
if (deadPid === process.pid) continue;
149-
if (!Number.isSafeInteger(deadPid) || deadPid <= 0 || !isProcessAlive(deadPid)) {
150-
removeDaemonStartupPhasesFile(path.join(stateDir, entry));
151-
}
152-
}
153-
}
154-
155-
/**
156-
* The phases observed in a marker tail, keeping each phase's earliest occurrence. Unknown and
157-
* unparsable lines are ignored: a client never fails a startup over a line it does not know.
158-
*/
159-
export function readDaemonStartupPhaseMarkers(
160-
markerTail: string,
161-
): Partial<Record<DaemonStartupPhase, number>> {
162-
const phases: Partial<Record<DaemonStartupPhase, number>> = {};
163-
for (const line of markerTail.split('\n')) {
164-
if (!line.includes('"startupPhase"')) continue;
165-
let record: DaemonStartupMarkerRecord;
166-
try {
167-
record = JSON.parse(line) as DaemonStartupMarkerRecord;
168-
} catch {
169-
continue;
170-
}
171-
const phase = record.data?.startupPhase;
172-
const timestampMs = record.data?.timestampMs;
173-
if (
174-
typeof phase !== 'string' ||
175-
!DAEMON_STARTUP_PHASE_SET.has(phase) ||
176-
typeof timestampMs !== 'number' ||
177-
!Number.isFinite(timestampMs)
178-
) {
179-
continue;
180-
}
181-
const seen = phases[phase as DaemonStartupPhase];
182-
if (seen === undefined || timestampMs < seen) phases[phase as DaemonStartupPhase] = timestampMs;
183-
}
184-
return phases;
185-
}
186-
187-
type DaemonStartupMarkerRecord = {
188-
data?: { startupPhase?: unknown; timestampMs?: unknown };
189-
};
19051
export type DaemonRegistrationFields = Readonly<{
19152
socketPort?: number;
19253
httpPort?: number;

‎packages/daemon/src/server/http/daemon-runtime.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,10 +87,12 @@ import {
8787
import {
8888
tryAcquireDaemonRegistration,
8989
DAEMON_STARTUP_EXIT_CODES,
90+
} from '@agent-device/daemon-contracts/daemon-registration-owner';
91+
import {
9092
recordDaemonStartupMarker,
9193
removeDaemonStartupPhasesFile,
9294
resolveDaemonStartupPhasesPath,
93-
} from '@agent-device/daemon-contracts/daemon-registration-owner';
95+
} from '@agent-device/daemon-contracts/daemon-startup-phases';
9496
import { retainPngWorker } from '@agent-device/capture-kit/png-worker-client';
9597
import { openWebSessionNames } from '../../sessions/web-session-names.ts';
9698
import { createAppLogAdmissionLedger } from '../../resources/app-log-admission-ledger.ts';

‎src/__tests__/test-utils/registered-daemon-fixture.test.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,8 @@ import path from 'node:path';
44
import { test } from 'vitest';
55
import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution';
66
import { stopDaemonProcess } from '@agent-device/daemon-contracts/daemon-process';
7-
import {
8-
DAEMON_STARTUP_EXIT_CODES,
9-
resolveDaemonStartupPhasesPath,
10-
} from '@agent-device/daemon-contracts/daemon-registration-owner';
7+
import { DAEMON_STARTUP_EXIT_CODES } from '@agent-device/daemon-contracts/daemon-registration-owner';
8+
import { resolveDaemonStartupPhasesPath } from '@agent-device/daemon-contracts/daemon-startup-phases';
119
import { mkdtempForTestSync } from '@agent-device/test-kit';
1210
import {
1311
launchRegisteredDaemonFixtureArgs,

‎src/__tests__/test-utils/registered-daemon-fixture.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,16 @@ export function registeredDaemonFixtureArgs(
4343
'../../../packages/daemon-contracts/src/daemon-registration-owner.ts',
4444
import.meta.url,
4545
).href;
46+
const phasesUrl = new URL(
47+
'../../../packages/daemon-contracts/src/daemon-startup-phases.ts',
48+
import.meta.url,
49+
).href;
4650
fs.writeFileSync(
4751
entry,
4852
`import fs from 'node:fs';
4953
import path from 'node:path';
50-
import { DAEMON_STARTUP_EXIT_CODES, tryAcquireDaemonRegistration, claimDaemonStartupPhasesFile, recordDaemonStartupMarker, resolveDaemonStartupPhasesPath } from ${JSON.stringify(registrationUrl)};
54+
import { DAEMON_STARTUP_EXIT_CODES, tryAcquireDaemonRegistration } from ${JSON.stringify(registrationUrl)};
55+
import { claimDaemonStartupPhasesFile, recordDaemonStartupMarker, resolveDaemonStartupPhasesPath } from ${JSON.stringify(phasesUrl)};
5156
const paths = ${JSON.stringify(paths)};
5257
const barrier = ${JSON.stringify(acquisitionBarrier)};
5358
const emitBefore = ${fixtureOptions?.emitStartupMarkerBeforeAcquisition ? 'true' : 'false'};

‎src/daemon-client/daemon-client-startup.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,18 @@ import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
99
import { type ExecDetachedExit } from '@agent-device/host-kit/command';
1010
import {
1111
DAEMON_STARTUP_EXIT_CODES,
12-
readDaemonStartupPhaseMarkers,
1312
recoverAbandonedDaemonRegistration,
14-
removeDaemonStartupPhasesFile,
15-
resolveDaemonStartupPhasesPath,
1613
type DaemonRetirementResult,
17-
type DaemonStartupPhase,
1814
launchDaemonProcess,
1915
stopAndRetireDaemon,
2016
type DaemonStartupLaunch,
2117
} from '@agent-device/daemon-contracts/daemon-registration-owner';
18+
import {
19+
readDaemonStartupPhaseMarkers,
20+
removeDaemonStartupPhasesFile,
21+
resolveDaemonStartupPhasesPath,
22+
type DaemonStartupPhase,
23+
} from '@agent-device/daemon-contracts/daemon-startup-phases';
2224
import type {
2325
DaemonPaths,
2426
DaemonTransportPreference,

0 commit comments

Comments
 (0)