Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(computer): finish a Run whose acceptance was cut off by a disconnect

shoudi zheng730f87e84fe0
diff --git a/apps/computer/local-daemon/internal/daemon/operation_start.go b/apps/computer/local-daemon/internal/daemon/operation_start.go
index 0b86325c..d8137e04 100644
--- a/apps/computer/local-daemon/internal/daemon/operation_start.go
+++ b/apps/computer/local-daemon/internal/daemon/operation_start.go
@@ -127,15 +127,10 @@ func (d *Daemon) handleOperationStart(ctx context.Context, stream transport.Stre
"accepted_append_ms", acceptedAppendMs, "accepted_send_ms", acceptedSendMs,
"prepared", preparedAdopted,
"total_ms", time.Since(admissionStartedAt).Milliseconds())
- if acceptanceSendErr != nil {
- cancel()
- d.discardPreparedOperationAsync(prepared, "acceptance_delivery")
- terminalErr := d.finishFailure(
- context.WithoutCancel(ctx), stream, command, operationCodeExecutionFailed,
- "Operation acceptance delivery became indeterminate before Provider start",
- )
- return errors.Join(acceptanceSendErr, terminalErr)
- }
+ // A failed acceptance send leaves the accepted event in the ledger, like
+ // any later event whose delivery fails. The Operation stays admitted and
+ // starts; the returned error reconnects, the next hello reports it active,
+ // and the Gateway's re-sent start replays the accepted event.
if prepared != nil {
prepared.suppressReceipt()
}
diff --git a/apps/computer/local-daemon/internal/daemon/operation_start_accepted_test.go b/apps/computer/local-daemon/internal/daemon/operation_start_accepted_test.go
index cc91d537..a25aa18e 100644
--- a/apps/computer/local-daemon/internal/daemon/operation_start_accepted_test.go
+++ b/apps/computer/local-daemon/internal/daemon/operation_start_accepted_test.go
@@ -367,3 +367,61 @@ func TestAcceptedStartResolvesAgainOnlyAfterAuthorityChange(t *testing.T) {
d.WaitForOperations()
}
}
+
+// acceptedSendFailingStream fails only the operation.accepted send, standing in
+// for a connection that drops between admission and acceptance delivery.
+type acceptedSendFailingStream struct {
+ *fakeStream
+ failures atomic.Int32
+}
+
+func (s *acceptedSendFailingStream) Send(ctx context.Context, event protocol.Event) error {
+ if event.Type == protocol.EventOperationAccepted {
+ s.failures.Add(1)
+ return errors.New("connection closed")
+ }
+ return s.fakeStream.Send(ctx, event)
+}
+
+// A failed acceptance send keeps the admitted Operation running, so the
+// reconnect reports it active and the re-sent start replays its acceptance.
+func TestOperationStartAcceptanceSendFailureKeepsOperationAdmitted(t *testing.T) {
+ providerRelease := make(chan struct{})
+ started := make(chan struct{}, 8)
+ d, stream := acceptedStartDaemon(t, newBlockingBinder("unused", nil), started, providerRelease)
+ dead := &acceptedSendFailingStream{fakeStream: &fakeStream{}}
+ start := daemonOperationStart("operation-accept-lost", "agent-1")
+
+ if err := d.handleOperationStart(context.Background(), dead, start); err == nil {
+ t.Fatal("acceptance send failure was not returned to the connection")
+ }
+ if got := dead.failures.Load(); got != 1 {
+ t.Fatalf("accepted send failures=%d, want 1", got)
+ }
+ awaitProviderStarts(t, started, 1)
+ active, err := d.ledger.Active(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(active), start.OperationID) {
+ t.Fatalf("ledger Active=%s does not report %s", active, start.OperationID)
+ }
+ begin, err := d.ledger.Begin(context.Background(), operationIdentity(start))
+ if err != nil || begin.Disposition != BeginRunning {
+ t.Fatalf("Begin=%+v err=%v, want running", begin, err)
+ }
+
+ if err := d.handleOperationStart(context.Background(), stream, start); err != nil {
+ t.Fatal(err)
+ }
+ awaitAcceptedOperationEvent(t, stream, start.OperationID, protocol.EventOperationAccepted)
+ close(providerRelease)
+ d.WaitForOperations()
+ awaitAcceptedOperationEvent(t, stream, start.OperationID, protocol.EventOperationCompleted)
+ assertNoProviderStart(t, started)
+ for _, event := range append(stream.snapshotEvents(), dead.snapshotEvents()...) {
+ if event.OperationID == start.OperationID && event.Type == protocol.EventOperationFailed {
+ t.Fatalf("admitted Operation recorded a failure: %s", event.Payload)
+ }
+ }
+}
diff --git a/apps/node-services/src/agent/runner-gateway/runner-operation.ts b/apps/node-services/src/agent/runner-gateway/runner-operation.ts
index 1f79ec53..8f9bec92 100644
--- a/apps/node-services/src/agent/runner-gateway/runner-operation.ts
+++ b/apps/node-services/src/agent/runner-gateway/runner-operation.ts
@@ -198,6 +198,11 @@ export class RunnerOperationInputError extends RunnerGatewayError {
type CommandSender = (command: AgentToDaemonEnvelope) => Promise<void>;
const MAX_OPERATION_PREPARE_MCP_RELAYS = 64;
+// An unaccepted start re-sent this many times across reconnects without an
+// acceptance or terminal is ended instead of re-sent again: its outcome on the
+// Computer cannot be learned, and re-sending it forever keeps the Run running.
+const MAX_UNACCEPTED_START_RESENDS = 3;
+export const OPERATION_OUTCOME_UNKNOWN = "OPERATION_OUTCOME_UNKNOWN";
export type OperationEnvelope = Extract<
DaemonToAgentEnvelope,
@@ -248,6 +253,11 @@ export class RunnerOperationState {
readonly #createdAt: number;
#lastStartSentAt: number | undefined;
#startSentCount = 0;
+ #unacceptedStartResends = 0;
+ // Every connection epoch the start was sent with. A Daemon may report an
+ // Operation it recorded on an earlier connection, before the start was
+ // rebased, under that connection's epoch.
+ readonly #sentEpochs = new Set<number>();
#inputReceiptTimer: ReturnType<typeof setTimeout> | undefined;
#inputReceipts: Deferred<void> | undefined;
#turnId: string | undefined;
@@ -328,6 +338,7 @@ export class RunnerOperationState {
// Callers update Session checkpoints in place. Retain the original wire
// command independently so reconnect never changes an admitted request.
this.start = structuredClone({ ...start, ...operationIdentity(start) });
+ this.#sentEpochs.add(this.start.connection_epoch);
this.#currentContextViewRef = this.start.context_view_ref;
}
@@ -502,13 +513,31 @@ export class RunnerOperationState {
readonly retainedByDaemon: boolean;
}): readonly AgentToDaemonEnvelope[] {
if (this.#terminal) return [];
- if (
- options &&
- !this.#accepted &&
- !options.retainedByDaemon &&
- this.start.connection_epoch !== options.connectionEpoch
- ) {
- this.#rebaseConnectionEpoch(options.connectionEpoch);
+ // A Daemon that reports the Operation active still holds it and replays
+ // its acceptance, so only a start it does not report counts as a re-send.
+ if (options && !this.#accepted && !options.retainedByDaemon) {
+ if (this.#unacceptedStartResends >= MAX_UNACCEPTED_START_RESENDS) {
+ logAgentEvent("error", "runner.operation.outcome_unknown", {
+ operationId: this.start.operation_id,
+ computerId: this.start.runner_id,
+ agentId: this.start.agent_id,
+ resendCount: this.#unacceptedStartResends,
+ });
+ this.#complete(() =>
+ this.#outcome.reject(
+ new RunnerOperationError(
+ OPERATION_OUTCOME_UNKNOWN,
+ "The Computer never confirmed the Operation start; its outcome is unknown",
+ false,
+ ),
+ ),
+ );
+ return [];
+ }
+ this.#unacceptedStartResends++;
+ if (this.start.connection_epoch !== options.connectionEpoch) {
+ this.#rebaseConnectionEpoch(options.connectionEpoch);
+ }
}
const commands: AgentToDaemonEnvelope[] = [
this.start,
@@ -533,6 +562,7 @@ export class RunnerOperationState {
);
}
this.start = start;
+ this.#sentEpochs.add(connectionEpoch);
for (const [commandId, pending] of this.#pendingInputs) {
const command = parseAgentToDaemonEnvelope({
...pending.command,
@@ -608,7 +638,15 @@ export class RunnerOperationState {
assertIdentity(
value: ActiveOperation | OperationEnvelope | OperationInputClosed,
): void {
- assertOperationIdentity(this.start, value);
+ assertOperationIdentity(this.#identityAt(value.connection_epoch), value);
+ }
+
+ // The start's identity under an epoch it was sent with; any other epoch
+ // keeps the current one and so fails the identity check.
+ #identityAt(connectionEpoch: number): OperationStart {
+ return this.#sentEpochs.has(connectionEpoch)
+ ? { ...this.start, connection_epoch: connectionEpoch }
+ : this.start;
}
async receive(
@@ -626,7 +664,7 @@ export class RunnerOperationState {
async receiveClosedInput(envelope: OperationInputClosed): Promise<void> {
return this.#serialize(async () => {
- assertOperationIdentity(this.start, envelope);
+ this.assertIdentity(envelope);
const pending = this.#pendingInputs.get(envelope.command_id);
// The Daemon answers each input once from its ledger, and it never
// commits a terminal while it holds an unanswered input, so a receipt
@@ -665,7 +703,9 @@ export class RunnerOperationState {
envelope: OperationEnvelope,
apply = true,
): Promise<OperationAck> {
- assertOperationIdentity(this.start, envelope);
+ this.assertIdentity(envelope);
+ const ack = (throughSequence: number) =>
+ this.#ack(throughSequence, envelope.connection_epoch);
// A restarted Daemon keeps no Operation: it numbers the terminal it
// reports for one it lost from 1. This Operation has seen no terminal, so
// the frame is not a replay; it ends the Operation.
@@ -676,7 +716,7 @@ export class RunnerOperationState {
// A Computer that reconnects replays every event it has not seen
// acknowledged; the ones already applied only need the acknowledgement.
if (envelope.seq <= this.#lastSequence && !restartedTerminal)
- return this.#ack(this.#lastSequence);
+ return ack(this.#lastSequence);
if (this.#terminal) {
// A Gateway-local terminal (cancel timeout, abandoned placement) does
// not stop the Daemon from finishing the Operation it was asked to
@@ -685,7 +725,7 @@ export class RunnerOperationState {
// every reconnect.
if (!this.#outcomeEnvelope && envelope.seq === this.#lastSequence + 1) {
this.#lastSequence = envelope.seq;
- return this.#ack(this.#lastSequence);
+ return ack(this.#lastSequence);
}
throw new RunnerGatewayProtocolError(
"Runner emitted after terminal state",
@@ -738,7 +778,7 @@ export class RunnerOperationState {
// After a restarted Daemon's terminal the sequence is that Daemon's, so
// its replays of the terminal are acknowledged at the same sequence.
this.#lastSequence = envelope.seq;
- return this.#ack(this.#lastSequence);
+ return ack(this.#lastSequence);
}
#acceptEnvelope(envelope: OperationEnvelope): void {
@@ -1008,8 +1048,14 @@ export class RunnerOperationState {
settle();
}
- #ack(throughSequence: number): OperationAck {
- return createOperationAck(this.start, this.#createId(), throughSequence);
+ // A frame recorded under an earlier epoch of the start is acknowledged
+ // under that epoch, the identity the Daemon's ledger holds it by.
+ #ack(throughSequence: number, connectionEpoch: number): OperationAck {
+ return createOperationAck(
+ this.#identityAt(connectionEpoch),
+ this.#createId(),
+ throughSequence,
+ );
}
}
diff --git a/apps/node-services/src/agent/runner-gateway/runner-operations.ts b/apps/node-services/src/agent/runner-gateway/runner-operations.ts
index cc832ddf..10f74581 100644
--- a/apps/node-services/src/agent/runner-gateway/runner-operations.ts
+++ b/apps/node-services/src/agent/runner-gateway/runner-operations.ts
@@ -460,12 +460,16 @@ export class RunnerOperations {
),
);
for (const operation of this.retainedOperations(connection.runnerId)) {
+ const wasTerminal = operation.terminal;
for (const command of operation.reconnectCommands({
connectionEpoch: connection.connectionEpoch,
retainedByDaemon: retainedByDaemon.has(operation.start.operation_id),
})) {
await this.owners.connections().send(connection, command);
}
+ // An unaccepted start past its re-send bound ends here instead.
+ if (!wasTerminal && operation.terminal)
+ this.#retireOperation(operation);
}
for (const orphan of connection.reportedActiveOperations) {
if (
diff --git a/apps/node-services/tests/agent/runner-gateway/runner-operations-public.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-operations-public.test.ts
index b264449c..035e8499 100644
--- a/apps/node-services/tests/agent/runner-gateway/runner-operations-public.test.ts
+++ b/apps/node-services/tests/agent/runner-gateway/runner-operations-public.test.ts
@@ -871,6 +871,150 @@ describe("RunnerGateway", () => {
second.disconnect();
});
+ it("ends a rebased start with the terminal the daemon recorded on its first epoch", async () => {
+ const gateway = createTestRunnerGateway({
+ heartbeatIntervalMs: 1_000,
+ createId: sequenceIds(),
+ });
+ const firstPeer = new RecordingPeer();
+ const first = await acceptReadyConnection(gateway, firstPeer);
+ const operation = await gateway.startOperation(sessionTarget());
+ void operation.result.catch(() => undefined);
+ const original = firstPeer.sent[1] as OperationStart;
+ first.disconnect();
+
+ const secondPeer = new RecordingPeer();
+ const second = await acceptReadyConnection(gateway, secondPeer);
+ expect(secondPeer.sent[1]).toMatchObject({
+ type: "operation.start",
+ connection_epoch: 2,
+ });
+ // The Daemon failed it on the first connection and replays that terminal.
+ await second.receive(
+ event(original, 1, {
+ type: "operation.failed",
+ stage: "operation_admission",
+ error: {
+ code: "EXECUTION_FAILED",
+ message: "Operation acceptance delivery failed",
+ retryable: false,
+ },
+ }),
+ );
+ await expect(operation.result).rejects.toMatchObject({
+ code: "EXECUTION_FAILED",
+ });
+ expect(secondPeer.sent.at(-1)).toMatchObject({
+ type: "operation.ack",
+ through_seq: 1,
+ connection_epoch: 1,
+ });
+ expect(secondPeer.closed).toEqual([]);
+ });
+
+ it("rejects a frame stamped with an epoch the start was never sent with", async () => {
+ const gateway = createTestRunnerGateway({
+ heartbeatIntervalMs: 1_000,
+ createId: sequenceIds(),
+ });
+ const firstPeer = new RecordingPeer();
+ const first = await acceptReadyConnection(gateway, firstPeer);
+ const operation = await gateway.startOperation(sessionTarget());
+ void operation.result.catch(() => undefined);
+ const original = firstPeer.sent[1] as OperationStart;
+ first.disconnect();
+
+ const secondPeer = new RecordingPeer();
+ const second = await acceptReadyConnection(gateway, secondPeer);
+ await expect(
+ second.receive(
+ event({ ...original, connection_epoch: 7 }, 1, {
+ type: "operation.failed",
+ stage: "operation_admission",
+ error: { code: "EXECUTION_FAILED", message: "x", retryable: false },
+ }),
+ ),
+ ).rejects.toThrow("identity mismatch at connection_epoch");
+ });
+
+ it("ends an unaccepted start with an unknown outcome after three re-sends", async () => {
+ const gateway = createTestRunnerGateway({
+ heartbeatIntervalMs: 1_000,
+ createId: sequenceIds(),
+ });
+ let peer = new RecordingPeer();
+ let connection = await acceptReadyConnection(gateway, peer);
+ const operation = await gateway.startOperation(sessionTarget());
+ void operation.result.catch(() => undefined);
+ const original = peer.sent[1] as OperationStart;
+ for (let resend = 1; resend <= 3; resend++) {
+ connection.disconnect();
+ peer = new RecordingPeer();
+ connection = await acceptReadyConnection(gateway, peer);
+ expect(peer.sent).toContainEqual(
+ expect.objectContaining({
+ type: "operation.start",
+ operation_id: original.operation_id,
+ }),
+ );
+ }
+ connection.disconnect();
+ peer = new RecordingPeer();
+ await acceptReadyConnection(gateway, peer);
+ expect(peer.sent).not.toContainEqual(
+ expect.objectContaining({ type: "operation.start" }),
+ );
+ await expect(operation.result).rejects.toMatchObject({
+ code: "OPERATION_OUTCOME_UNKNOWN",
+ retryable: false,
+ });
+ });
+
+ it("keeps re-sending an unaccepted start the daemon reports active", async () => {
+ const gateway = createTestRunnerGateway({
+ heartbeatIntervalMs: 1_000,
+ createId: sequenceIds(),
+ });
+ let peer = new RecordingPeer();
+ let connection = await acceptReadyConnection(gateway, peer);
+ const operation = await gateway.startOperation(sessionTarget());
+ void operation.result.catch(() => undefined);
+ const start = peer.sent[1] as OperationStart;
+ const retained = hello([
+ {
+ tenant_id: start.tenant_id,
+ runner_id: start.runner_id,
+ protocol_version: start.protocol_version,
+ host_access: start.host_access,
+ registration_id: start.registration_id,
+ assignment_revision: start.assignment_revision,
+ execution_context_key: start.execution_context_key,
+ runtime_instance_id: start.runtime_instance_id,
+ context_view_ref: start.context_view_ref,
+ agent_id: start.agent_id,
+ operation_id: start.operation_id,
+ connection_epoch: start.connection_epoch,
+ runner_revision: start.runner_revision,
+ generation: start.generation,
+ execution_lease_id: start.execution_lease_id,
+ workspace_grant_id: start.workspace_grant_id,
+ runtime_type: start.runtime_type,
+ kind: start.request.kind,
+ last_emitted_seq: 0,
+ last_acked_seq: 0,
+ },
+ ]);
+ for (let reconnect = 1; reconnect <= 5; reconnect++) {
+ connection.disconnect();
+ peer = new RecordingPeer();
+ connection = await acceptReadyConnection(gateway, peer, retained);
+ expect(peer.sent).toContainEqual(start);
+ }
+ await expect(
+ Promise.race([operation.result, Promise.resolve("pending")]),
+ ).resolves.toBe("pending");
+ });
+
it("retires terminal state when acknowledgement delivery is indeterminate", async () => {
const gateway = createTestRunnerGateway({
heartbeatIntervalMs: 1_000,