Skip to content

Commit a938217

Browse files
authored
fix(cli): end a remote lease allocated by a materialization that never persisted (#4135)
* refactor(move): split connection-runtime by ownership seam connection-runtime.ts crossed the 1,000-line architecture-debt line. Split it along the seams the file already had, with no behavior change: - connection-lease-policy.ts: which lease a provider's connection allocates, its TTL, and the id it names a new lease with - connection-lease-transaction.ts: the acquisition transaction — resolve the device, allocate or renew the lease, bind it to the record, and release it - connection-metro-runtime.ts: the deferred Metro runtime preparation the record carries, and the tunnel teardown - connection-previous-lease.ts: releasing the lease a reconnect replaces, with the previous endpoint's own credential - connection-runtime.ts: the materialization that sequences those three and persists the record Importers now name the module that owns each declaration. * fix(cli): end a remote lease allocated by a materialization that never persisted `materializeRemoteConnectionForCommand` allocated a lease and then could fail before `persistMaterializedConnection` wrote the record that would name it — a rejected `prepareConnectedMetro` was the live path. The only release path ran when the state-file write itself failed, so the new lease was neither saved nor ended: no record named it, so `disconnect` could not reach it, and it held the device until its TTL lapsed. The call now owns a lease it allocated until persistence transfers ownership, and every earlier exit ends it. A lease the call renewed was already named by the stored record, so this path never releases it — disconnect still does. The failure that ended the command stays the thrown error. A release that failed too is recorded beside it as typed secondary evidence under `details.leaseRollback` (ADR 0010 as amended by ADR 0019), never in its place. * chore(gates): drop the legacy line cap for connection-runtime.ts The split left every module under the 1,000-line limit, so the 1,019-line legacy cap for connection-runtime.ts has no subject. * fix(cli): end only a lease this command created, from allocation to the durable record The independent review found three ownership gaps in the lease rollback. - The daemon now answers each lease_allocate with whether its request created the lease (reused on the wire, Lease.created on the client). A run's repeat allocation gets the run's existing lease back, and that lease belongs to whoever holds it: this path ends only a lease the daemon says it created. - A lease enters the new ledger the moment allocation returns, before any later validation or binding can fail, so a platform conflict after a successful allocation can no longer leak it. Binding cleanup consumes the same ownership, so a lease is never released twice. - Ownership transfers at the durable session record, not at the whole write: the commit-point callback runs between the record and the active-session pointer, so a pointer failure leaves a named lease to disconnect. A release that did not end the lease keeps it owned, and the failure path reports it beside the command's own failure as typed details.leaseRollback. * fix(cli): stop the keyless-lease fallback when its first lease survives, and document created correctly The round-2 review found two gaps. - The keyless-lease fallback released the daemon-granted lease and ignored whether that release ended it. A throwing or refused release left the first lease owned by no durable record while the fallback allocated a replacement that became the connection. The fallback now requires a confirmed retirement; otherwise the command fails with PROXY_LEASE_RETIREMENT_FAILED, the ledger keeps the lease, and the failure path retries the release and reports it as details.leaseRollback beside the refusal. - The published JSDoc on Lease.created stated the mapping backwards; it now reads true = created by this allocation, false = an existing lease, absent = the daemon did not answer. website/docs/docs/client-api.md describes the field and the release guard: release only when created is true, and a missing answer is not permission to release. * fix: preserve older daemon allocation binding and simplify lease rollback * test: assert fallback lease binds the selected device * fix: report spec lease rollback failures in one typed shape * fix: release discarded allocations without creation evidence * docs: limit lease release retry to discarded allocations * fix: scope allocation evidence and protect the lease ledger
1 parent a42bc35 commit a938217

29 files changed

Lines changed: 2050 additions & 914 deletions

‎oxlint.config.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,6 @@ const LEGACY_FILE_LINE_CAPS = {
6363
'test/integration/provider-scenarios/android-lifecycle.test.ts': 1227,
6464
'packages/host-kit/src/internal/exec.ts': 1032,
6565
'packages/react-native/src/metro/client-metro.ts': 1123,
66-
'src/cli/commands/connection-runtime.ts': 1019,
6766
};
6867

6968
export default defineConfig({

‎packages/client/src/__tests__/lease-client.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,40 @@ test('allocate sends the lease id named on the call, never the configured one',
129129
assert.equal(lease.leaseId, 'abcdef0123456789');
130130
});
131131

132+
test.each([
133+
{ operation: 'allocate', reused: false, created: true },
134+
{ operation: 'allocate', reused: true, created: false },
135+
{ operation: 'heartbeat', reused: false, created: undefined },
136+
{ operation: 'heartbeat', reused: true, created: undefined },
137+
] as const)(
138+
'$operation reads creation evidence only from an allocate response (reused=$reused)',
139+
async ({ operation, reused, created }) => {
140+
const client = createAgentDeviceClient(
141+
{},
142+
{
143+
transport: async () => ({
144+
ok: true,
145+
data: {
146+
reused,
147+
lease: {
148+
leaseId: 'lease-a',
149+
tenantId: 'tenant-a',
150+
runId: 'run-a',
151+
backend: 'ios-instance',
152+
},
153+
},
154+
}),
155+
},
156+
);
157+
const lease = await client.leases[operation]({
158+
tenant: 'tenant-a',
159+
runId: 'run-a',
160+
leaseId: 'lease-a',
161+
});
162+
assert.equal(lease.created, created);
163+
},
164+
);
165+
132166
for (const operation of ['allocate', 'heartbeat'] as const) {
133167
const validLease = {
134168
leaseId: 'lease-a',

‎packages/client/src/lease-client.ts‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,16 @@ export function createLeaseClient(
1717
const control = async (positionals: string[], options?: InternalRequestOptions) =>
1818
await execute(INTERNAL_COMMANDS.humanControl, positionals, options);
1919
return {
20-
allocate: async (options) =>
21-
normalizeLease(
22-
await execute(INTERNAL_COMMANDS.leaseAllocate, [], {
23-
...options,
24-
leaseId: options.leaseId,
25-
}),
26-
),
20+
allocate: async (options) => {
21+
const data = await execute(INTERNAL_COMMANDS.leaseAllocate, [], {
22+
...options,
23+
leaseId: options.leaseId,
24+
});
25+
return {
26+
...normalizeLease(data),
27+
...(typeof data.reused === 'boolean' ? { created: !data.reused } : {}),
28+
};
29+
},
2730
heartbeat: async (options) =>
2831
normalizeLease(await execute(INTERNAL_COMMANDS.leaseHeartbeat, [], options)),
2932
release: async (options) => {

‎packages/contracts/src/client-lease.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,13 @@ export type Lease = {
1414
leaseProvider?: string;
1515
deviceKey?: string;
1616
clientId?: string;
17+
/**
18+
* What an allocate answered: `true` when this request created the lease, `false` on reuse.
19+
* Only allocate answers this; heartbeats and older daemons omit creation evidence.
20+
* A discarded allocate response can be released unless `created` is false.
21+
* Rollback after binding requires `created` to be true.
22+
*/
23+
created?: boolean;
1724
/**
1825
* The device granted for a request that named a device spec, written by the backend that
1926
* honoured the spec. A daemon refuses a spec instead, so only such a backend sets it.

‎packages/daemon/src/sessions/handlers/__tests__/lease.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,39 @@ test('lease_allocate answers with the lease id the request named', async () => {
8080
assert.equal(registry.listActiveLeases()[0]?.leaseId, leaseId);
8181
});
8282

83+
test('lease_allocate answers whether its request created the lease or got back an existing one', async () => {
84+
const registry = new LeaseRegistry();
85+
const leaseId = 'abcdef0123456789abcdef0123456789';
86+
const allocate = (requestedLeaseId?: string) =>
87+
handleLeaseCommands({
88+
host: createTestHostEnvironment(),
89+
req: {
90+
token: 'test-token',
91+
session: 'default',
92+
command: 'lease_allocate',
93+
positionals: [],
94+
meta: {
95+
tenantId: 'tenant-a',
96+
runId: 'run-1',
97+
...(requestedLeaseId ? { leaseId: requestedLeaseId } : {}),
98+
},
99+
},
100+
sessionName: 'default',
101+
sessionStore: makeSessionStore('agent-device-allocate-reused-'),
102+
leaseRegistry: registry,
103+
});
104+
105+
const created = await allocate(leaseId);
106+
assert.ok(created?.ok);
107+
assert.equal(created.data?.reused, false);
108+
// A repeat for the same run binding gets that lease back, and the answer says this request did
109+
// not create it — a client that might end the lease must end only the one its request created.
110+
const repeated = await allocate();
111+
assert.ok(repeated?.ok);
112+
assert.equal((repeated.data?.lease as DeviceLease | undefined)?.leaseId, leaseId);
113+
assert.equal(repeated.data?.reused, true);
114+
});
115+
83116
test('lease_release still releases a retainOnClose lease through the provider', async () => {
84117
const registry = new LeaseRegistry();
85118
const lease = registry.allocateLease({

‎packages/daemon/src/sessions/handlers/lease.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,13 @@ export async function handleLeaseCommands(args: LeaseHandlerArgs): Promise<Daemo
141141
const allocated = leaseRegistry.getLease(leaseReleaseRequestFor(lease)) ?? lease;
142142
return {
143143
ok: true,
144-
data: { lease: allocated, ...(providerData ? { provider: providerData } : {}) },
144+
data: {
145+
lease: allocated,
146+
// Whether this request was handed a lease that already existed. A caller that may end
147+
// the lease needs this: the returned lease alone does not say who created it.
148+
reused,
149+
...(providerData ? { provider: providerData } : {}),
150+
},
145151
};
146152
});
147153
}

‎packages/remote/src/remote-connection-state.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,13 +245,20 @@ export function readRemoteConnectionState(options: {
245245
export function writeRemoteConnectionState(options: {
246246
stateDir: string;
247247
state: RemoteConnectionState;
248+
/**
249+
* Runs once the session record has landed, before the active-session pointer is updated. A caller
250+
* that was holding the lease this record names until it was durable acts here: from this point the
251+
* record owns it, and a later pointer failure must not be read as a record that never came to be.
252+
*/
253+
onSessionRecordCommitted?: () => void;
248254
}): void {
249255
const statePath = remoteConnectionStatePath({
250256
stateDir: options.stateDir,
251257
session: options.state.session,
252258
});
253259
fs.mkdirSync(path.dirname(statePath), { recursive: true });
254260
writeJsonFile(statePath, options.state);
261+
options.onSessionRecordCommitted?.();
255262
writeJsonFile(activeConnectionStatePath(options.stateDir), { session: options.state.session });
256263
}
257264

‎src/__tests__/daemon-client-lease-device-spec.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,23 @@ test('a daemon refuses a lease allocate naming a device spec and records no leas
6767
});
6868
assert.equal(lease.leaseId, LEASE_ID);
6969
assert.equal(lease.device, undefined);
70+
// The answer that crosses the wire says this request created the lease, so a client that may
71+
// end a lease can tell its own from one the daemon had already issued.
72+
assert.equal(lease.created, true);
73+
const repeated = await client.leases.allocate({
74+
tenant: 'proxy',
75+
runId: 'run-spec',
76+
leaseBackend: 'ios-instance',
77+
platform: 'ios',
78+
});
79+
assert.equal(repeated.leaseId, LEASE_ID);
80+
assert.equal(repeated.created, false);
81+
await client.leases.release({
82+
tenant: 'proxy',
83+
runId: 'run-spec',
84+
leaseId: LEASE_ID,
85+
leaseBackend: 'ios-instance',
86+
});
7087
} finally {
7188
await daemon.close();
7289
}

‎src/__tests__/remote-connection-harmonyos.test.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,8 @@ import {
77
forceConnectFlags,
88
seedConnectionState,
99
} from './remote-connection.fixtures.ts';
10-
import {
11-
materializeRemoteConnectionForCommand,
12-
resolveRequestedLeaseBackend,
13-
} from '../cli/commands/connection-runtime.ts';
10+
import { materializeRemoteConnectionForCommand } from '../cli/commands/connection-runtime.ts';
11+
import { resolveRequestedLeaseBackend } from '../cli/commands/connection-lease-transaction.ts';
1412
import { disconnectCommand } from '../cli/commands/connection.ts';
1513
import { readRemoteConnectionState } from '@agent-device/remote/remote-connection-state';
1614

0 commit comments

Comments
 (0)