Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/command-registry/src/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,15 @@ const COMMAND_DESCRIPTOR_BY_NAME: ReadonlyMap<
CommandDescriptor & { standaloneCommandProjection: StandaloneCommandProjection | undefined }
> = new Map(commandDescriptors.map((descriptor) => [descriptor.name, descriptor]));

/**
* Whether the daemon admits this command's request against the lease it names (ADR 0007). A name
* outside the registry, or a command exempt from lease admission, never meets lease admission.
*/
export function commandMeetsLeaseAdmission(command: string): boolean {
const daemon = COMMAND_DESCRIPTOR_BY_NAME.get(command)?.daemon;
return daemon !== undefined && daemon.leaseAdmissionExempt !== true;
}

export function resolveCommandCompositeResourceTrait(
command: string,
): CompositeResourceTrait | undefined {
Expand Down
22 changes: 22 additions & 0 deletions packages/contracts/src/lease-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,15 @@ export function parseLeaseDeviceKey(
return { platform: platform!, target: target!, id: id! };
}

/** A lease id as the registry stores it: trimmed lower-case hex. `undefined` for any other value. */
export function normalizeLeaseId(raw: string | undefined): string | undefined {
if (!raw) return undefined;
const value = raw.trim();
if (!value) return undefined;
if (!/^[a-f0-9]{16,128}$/i.test(value)) return undefined;
return value.toLowerCase();
}

export function isProxyLeaseScope(scope: LeaseScope): boolean {
return scope.leaseProvider === PROXY_LEASE_PROVIDER;
}
Expand Down Expand Up @@ -544,6 +553,19 @@ export function isInactiveLeaseError(error: unknown): boolean {
);
}

/**
* Whether `error` is the daemon's lease-admission refusal: the lease is gone, and the request never
* reached a handler. A client that let admission check a reused lease (the `lease-admission`
* capability) reallocates and resends on this refusal alone.
*/
export function isUndispatchedInactiveLeaseRefusal(error: unknown): boolean {
return (
isInactiveLeaseError(error) &&
(error as Readonly<{ details?: Readonly<{ dispatched?: unknown }> }>).details?.dispatched ===
'no'
);
}

/** Whether `error` says the provider's device instance ended, which ends its lease. */
export function isProviderInstanceEndedError(error: unknown): boolean {
return (
Expand Down
135 changes: 135 additions & 0 deletions packages/daemon-client/src/__tests__/index-lease-admission.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import http from 'node:http';
import path from 'node:path';
import { expect, test } from 'vitest';
import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit';
import { DAEMON_HTTP_INSTANCE_MISMATCH_HEADER } from '@agent-device/contracts/daemon-http';
import { sendToDaemon } from '../index.ts';

// A request whose reused lease no heartbeat checked reads `lease-admission` from the `/health` gate
// it already passes, so it costs `/health` and `/rpc` and nothing more. Without the capability it is
// refused before the send, so the caller can fall back to its heartbeat.

const LEASE_ADMISSION = ['script-artifacts', 'lease-admission'];

async function sendAdmissionChecked(
health: () => Record<string, unknown>,
onRpc?: (res: http.ServerResponse) => boolean,
flags: Record<string, unknown> = {},
) {
const routes: string[] = [];
const server = http.createServer((req, res) => {
routes.push(req.url ?? '');
res.setHeader('content-type', 'application/json');
if (req.url === '/health') {
res.end(JSON.stringify({ ok: true, ...health() }));
return;
}
if (onRpc?.(res)) return;
res.end(JSON.stringify({ jsonrpc: '2.0', id: 'test', result: { ok: true, data: {} } }));
});
const root = mkdtempForTestSync('lease-admission-');
try {
const result = await sendToDaemon(
{
command: 'snapshot',
session: 'remote',
positionals: [],
flags: {
daemonBaseUrl: `http://127.0.0.1:${await listenOnLoopback(server)}`,
stateDir: path.join(root, 'state'),
...flags,
},
meta: { tenantId: 'proxy', runId: 'run', leaseId: 'a'.repeat(32) },
},
{ authToken: 'test', leaseCheckedByAdmission: true },
).catch((error: unknown) => error);
return { result, routes };
} finally {
await closeLoopbackServer(server);
}
}

test.each([
{ name: 'daemon', health: { instanceId: 'daemon', capabilities: LEASE_ADMISSION } },
{
name: 'proxy in front of the daemon',
health: {
instanceId: 'proxy',
upstream: { instanceId: 'daemon', capabilities: LEASE_ADMISSION },
},
},
])('a lease-admission $name answers in /health and /rpc', async ({ health }) => {
const { result, routes } = await sendAdmissionChecked(() => health);

expect(result).toMatchObject({ ok: true });
expect(routes).toEqual(['/health', '/rpc']);
});

test.each([
{ name: 'legacy daemon', health: { instanceId: 'daemon', capabilities: ['script-artifacts'] } },
{
name: 'upgraded proxy in front of a legacy daemon',
health: { instanceId: 'proxy', capabilities: LEASE_ADMISSION, upstream: { instanceId: 'd' } },
},
// Without every instance ID, nothing holds the next request to the daemon that answered.
{ name: 'daemon that names no instance', health: { capabilities: LEASE_ADMISSION } },
{
name: 'proxy whose daemon names no instance',
health: { instanceId: 'proxy', upstream: { capabilities: LEASE_ADMISSION } },
},
{
name: 'proxy that names no instance',
health: { upstream: { instanceId: 'daemon', capabilities: LEASE_ADMISSION } },
},
{
name: 'proxy that reports no upstream',
health: { service: 'agent-device-proxy', instanceId: 'proxy', capabilities: LEASE_ADMISSION },
},
])('a $name is refused before the send', async ({ health }) => {
const { result, routes } = await sendAdmissionChecked(() => health);

expect(result).toMatchObject({
code: 'UNSUPPORTED_OPERATION',
details: { reason: 'lease_admission_unsupported', daemonRequestSent: false, dispatched: 'no' },
});
expect(routes).toEqual(['/health']);
});

test.each([
{
name: 'without lease admission',
replacement: { instanceId: 'legacy', capabilities: ['script-artifacts'] },
},
{ name: 'that names no instance', replacement: { capabilities: LEASE_ADMISSION } },
])('a replacement daemon $name is refused before the resend', async ({ replacement }) => {
let replaced = false;
const { result, routes } = await sendAdmissionChecked(
() => (replaced ? replacement : { instanceId: 'capable', capabilities: LEASE_ADMISSION }),
(res) => {
replaced = true;
res.statusCode = 409;
res.setHeader(DAEMON_HTTP_INSTANCE_MISMATCH_HEADER, 'true');
res.end(
JSON.stringify({ jsonrpc: '2.0', id: 'test', error: { code: -32000, message: 'x' } }),
);
return true;
},
);

expect(result).toMatchObject({
details: { reason: 'lease_admission_unsupported', daemonRequestSent: false, dispatched: 'no' },
});
expect(routes).toEqual(['/health', '/rpc', '/health']);
});

// The checked route reads no `/health`, which is where `lease-admission` is reported.
test('an admission-checked request on a checked connection goes health-first', async () => {
const { result, routes } = await sendAdmissionChecked(
() => ({ instanceId: 'daemon', capabilities: [...LEASE_ADMISSION, 'checked-rpc'] }),
undefined,
{ daemonRpc: 'checked' },
);

expect(result).toMatchObject({ ok: true });
expect(routes).toEqual(['/health', '/rpc']);
});
11 changes: 8 additions & 3 deletions packages/daemon-client/src/daemon-client-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
resolveDaemonServerMode,
resolveDaemonTransportPreference,
DAEMON_RETIREMENT_REASONS,
remoteDaemonCapabilities,
type DaemonPaths,
type DaemonServerMode,
type DaemonTransportPreference,
Expand Down Expand Up @@ -68,7 +69,8 @@ export type DaemonClientSettings = {
remoteAuthToken?: string;
/**
* The request goes on the checked RPC route without a `/health` probe: its connection sets
* `daemonRpc: checked`, and the request has no remote side effect before its command RPC.
* `daemonRpc: checked`, the request has no remote side effect before its command RPC, and nothing
* about it has to be read from `/health`.
*/
remoteCheckedRpc?: true;
/** See {@link DaemonBinding}. Present on a client that is pinned to one daemon instance. */
Expand Down Expand Up @@ -105,6 +107,7 @@ export function resolveClientSettings(
host: HostEnvironment,
daemonLifecycle: DaemonLifecycle = 'managed',
daemonBinding: DaemonBinding | undefined = undefined,
leaseCheckedByAdmission?: true,
): DaemonClientSettings {
const explicitStateDir = resolveExplicitStateDir(req, host.env);
const remote = resolveRemoteClientSettings(req, suppliedAuthToken, host.env);
Expand Down Expand Up @@ -146,7 +149,9 @@ export function resolveClientSettings(
...(remote.remoteBaseUrl &&
remote.daemonRpc === 'checked' &&
approvesCheckedRpcTarget(req.flags?.daemonRpcTarget, remote.remoteBaseUrl) &&
isStandaloneRemoteRequest(req)
isStandaloneRemoteRequest(req) &&
// An unchecked lease needs `lease-admission`, which only `/health` reports.
!leaseCheckedByAdmission
? { remoteCheckedRpc: true as const }
: {}),
...(daemonBinding ? { daemonBinding } : {}),
Expand Down Expand Up @@ -372,7 +377,7 @@ async function ensureRemoteDaemon(
probe: async (probeMs, signal) => await cachedRemoteDaemonHealth(remoteInfo, probeMs, signal),
});
}
remoteInfo.capabilities = (health.upstream ?? health).capabilities;
remoteInfo.capabilities = remoteDaemonCapabilities(health);
remoteInfo.remoteInstanceId = health.instanceId;
remoteInfo.remoteUpstreamInstanceId = health.upstream?.instanceId;
return { info: remoteInfo, startedByClient: false };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ import type { DaemonInfo } from './daemon-client-metadata.ts';
export type RemoteResendHealth = {
reachable: boolean;
timedOut?: true;
service?: string;
instanceId?: string;
capabilities?: readonly DaemonCapability[];
upstream?: { instanceId?: string; capabilities?: readonly DaemonCapability[] };
upstream?: { service?: string; instanceId?: string; capabilities?: readonly DaemonCapability[] };
};

/** The transport's side of one failed send: how to probe, resend and refuse for that request. */
Expand All @@ -20,6 +21,8 @@ export type RemoteResendPort = {
timeoutMs: number | undefined;
deadline: number | undefined;
signal: AbortSignal | undefined;
/** The request relies on admission to check its lease; a replacement must report `lease-admission`. */
leaseCheckedByAdmission?: true;
/** Sends the request once more, with `timeoutMs` as its budget. */
resend(timeoutMs: number | undefined): Promise<DaemonResponse>;
/** A live `/health` read that refuses a skewed protocol. */
Expand Down
10 changes: 8 additions & 2 deletions packages/daemon-client/src/daemon-client-remote-resend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@
// checked route triggers a resend. Loaded only on those failures; the transport hands in what it
// owns as a `RemoteResendPort`, declared below both in `daemon-client-remote-resend-port.ts`.
import type { DaemonResponse } from '@agent-device/kernel/contracts';
import { assertScriptArtifactsCapability } from '@agent-device/daemon-contracts/daemon-resolution';
import {
assertLeaseAdmissionCapability,
assertScriptArtifactsCapability,
remoteDaemonCapabilities,
} from '@agent-device/daemon-contracts/daemon-resolution';
import {
CheckedRpcConnectFailure,
undispatchedWithoutEndpoint,
Expand Down Expand Up @@ -77,10 +81,12 @@ export async function retryAfterRemoteInstanceMismatch(
}
info.remoteInstanceId = health.instanceId;
info.remoteUpstreamInstanceId = health.upstream?.instanceId;
info.capabilities = (health.upstream ?? health).capabilities;
info.capabilities = remoteDaemonCapabilities(health);
cacheRemoteDaemonHealth(info, health);
// A replacement daemon must still deliver the script that a remote recording asks for.
if (scriptPublicationId) assertScriptArtifactsCapability(info.capabilities);
// A replacement that cannot check the lease at admission gets the heartbeat path instead.
if (port.leaseCheckedByAdmission) assertLeaseAdmissionCapability(info.capabilities);
try {
return await port.resend(remainingMs);
} catch (error) {
Expand Down
6 changes: 6 additions & 0 deletions packages/daemon-client/src/daemon-client-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ export type DaemonRequest = DaemonWireRequest;
export type DaemonResponse = SharedDaemonResponse;
export type DaemonTransportOptions = AgentDeviceDaemonTransportContext & {
onProgress?: RequestProgressSink;
/**
* The request names a reused lease that no heartbeat checked, so the daemon must check it at
* admission. A daemon whose `/health` lacks `lease-admission` is refused before the send, so the
* request never takes the checked RPC route, which reads no `/health`.
*/
leaseCheckedByAdmission?: true;
};

/** What a client sends one daemon request through. */
Expand Down
2 changes: 2 additions & 0 deletions packages/daemon-client/src/daemon-client-transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ type ResolvedDaemonTransport = LoopbackTransport;
type SendRequestOptions = {
/** The host whose working directory and environment this request's client-side work reads. */
host: HostEnvironment;
leaseCheckedByAdmission?: true;
onProgress?: RequestProgressSink;
/**
* The caller's per-request cancellation (#3178). Aborted at or before a send attempt, nothing
Expand Down Expand Up @@ -536,6 +537,7 @@ function remoteResendPort(
timeoutMs,
deadline,
signal: options.signal,
leaseCheckedByAdmission: options.leaseCheckedByAdmission,
resend: async (budgetMs) =>
await sendRequestWithTransport(info, req, statePaths, budgetMs, transport, options),
readHealth: async (probeMs) => await readRemoteDaemonHealth(info, probeMs, options.signal),
Expand Down
9 changes: 8 additions & 1 deletion packages/daemon-client/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import type { DaemonConnection, EnsureDaemonOptions } from '@agent-device/contracts/client';
import type { DaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution';
import {
assertLeaseAdmissionCapability,
type DaemonPaths,
} from '@agent-device/daemon-contracts/daemon-resolution';
import type { DaemonStopIdentity } from '@agent-device/daemon-contracts/daemon-registration';
import type { DaemonStopResult } from '@agent-device/daemon-contracts/daemon-stop';
import { AppError } from '@agent-device/kernel/errors';
Expand Down Expand Up @@ -96,6 +99,7 @@ async function sendToDaemonOnHost(
host,
options.daemonLifecycle,
options.daemonBinding,
options.leaseCheckedByAdmission,
);
const requestTimeoutMs = resolveCommandRequestTimeoutMs(
resolveCommandTimeoutPolicy(requestWithoutAuthFlag.command),
Expand Down Expand Up @@ -124,6 +128,8 @@ async function sendToDaemonOnHost(
);
});
const info = daemon.info;
// Read from the `/health` gate this request already passed, so the check adds no round trip.
if (options.leaseCheckedByAdmission) assertLeaseAdmissionCapability(info.capabilities);
const preparedRemoteRequest = await cancellation.guard(
async () =>
await protectArtifactUploadWithLeaseBeats(
Expand Down Expand Up @@ -174,6 +180,7 @@ async function sendToDaemonOnHost(
onProgress: options.onProgress,
signal: options.signal,
timeoutRecovery: resolveTimeoutRecovery(settings),
...(options.leaseCheckedByAdmission ? { leaseCheckedByAdmission: true } : {}),
},
);
if (!info.baseUrl || !request.meta?.clientArtifactPaths?.savedScript)
Expand Down
Loading
Loading