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
1 change: 1 addition & 0 deletions packages/tui-rs/src/headless/async_transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ pub enum RemoteErrorKind {
RoleConflict,
AccessDenied,
OwnershipConflict,
RuntimeNotReady,
}

/// Error type for async transport operations
Expand Down
23 changes: 23 additions & 0 deletions packages/tui-rs/src/headless/remote_transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1480,6 +1480,9 @@ fn classify_remote_status(
if body_has_remote_error_code(trimmed_body, "runtime_owned_elsewhere") {
return (false, RemoteErrorKind::OwnershipConflict);
}
if body_has_remote_error_code(trimmed_body, "runtime_not_ready") {
return (true, RemoteErrorKind::RuntimeNotReady);
}

if trimmed_body.contains("Headless connection not found") {
return (
Expand Down Expand Up @@ -2957,6 +2960,26 @@ mod tests {
);
}

#[test]
fn retryability_classifies_structured_runtime_not_ready_as_retryable() {
assert_eq!(
classify_remote_status(
StatusCode::SERVICE_UNAVAILABLE,
RemoteRequestKind::Subscribe,
r#"{"error":"Hosted runner is draining and not accepting headless session traffic","code":"UNAVAILABLE","error_type":"runtime_not_ready"}"#,
),
(true, RemoteErrorKind::RuntimeNotReady)
);
assert_eq!(
classify_remote_status(
StatusCode::SERVICE_UNAVAILABLE,
RemoteRequestKind::Message,
r#"{"error":"Hosted runner is draining and not accepting headless session traffic","code":"UNAVAILABLE","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"runtime_not_ready","domain":"maestro.hosted_runner","metadata":{"draining":"true","maestro_session_id":"sess_owner"}}]}"#,
),
(true, RemoteErrorKind::RuntimeNotReady)
);
}

#[test]
fn retryability_keeps_subscriber_not_found_retryable_for_streams() {
assert_eq!(
Expand Down
58 changes: 51 additions & 7 deletions src/server/handlers/headless-sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ import {
import { createSessionManagerForRequest } from "../session-scope.js";
import { parseAndValidateJson, validatePayload } from "../validation.js";

export enum HostedRunnerErrorType {
RuntimeNotReady = "runtime_not_ready",
RuntimeOwnedElsewhere = "runtime_owned_elsewhere",
}

const HOSTED_RUNNER_ERROR_DOMAIN = "maestro.hosted_runner";

function stringLiteralUnion<const T extends readonly string[]>(values: T) {
return Type.Unsafe<T[number]>(
Type.Union(
Expand Down Expand Up @@ -279,11 +286,10 @@ function getScopeKey(req: IncomingMessage): string {
return getAuthScopeKey(req);
}

function hostedRunnerOwnershipError(
function hostedRunnerErrorMetadata(
context: WebServerContext,
message: string,
metadata: Record<string, string | undefined>,
): ApiError {
): Record<string, string> {
const hostedRunner = context.hostedRunner;
const detailMetadata: Record<string, string> = {};
for (const [key, value] of Object.entries({
Expand All @@ -297,17 +303,44 @@ function hostedRunnerOwnershipError(
detailMetadata[key] = value;
}
}
return detailMetadata;
}

function hostedRunnerOwnershipError(
context: WebServerContext,
message: string,
metadata: Record<string, string | undefined>,
): ApiError {
return new ApiError(
409,
message,
[
{
reason: "runtime_owned_elsewhere",
domain: "maestro.hosted_runner",
metadata: detailMetadata,
reason: HostedRunnerErrorType.RuntimeOwnedElsewhere,
domain: HOSTED_RUNNER_ERROR_DOMAIN,
metadata: hostedRunnerErrorMetadata(context, metadata),
},
],
"runtime_owned_elsewhere",
HostedRunnerErrorType.RuntimeOwnedElsewhere,
);
}

function hostedRunnerNotReadyError(
context: WebServerContext,
message: string,
metadata: Record<string, string | undefined>,
): ApiError {
return new ApiError(
503,
message,
[
{
reason: HostedRunnerErrorType.RuntimeNotReady,
domain: HOSTED_RUNNER_ERROR_DOMAIN,
metadata: hostedRunnerErrorMetadata(context, metadata),
},
],
HostedRunnerErrorType.RuntimeNotReady,
);
}

Expand All @@ -322,6 +355,17 @@ function ensureHostedRunnerCanUseSession(
const activeSessionId =
hostedRunner.activeMaestroSessionId ??
hostedRunner.configuredMaestroSessionId;
if (hostedRunner.draining) {
throw hostedRunnerNotReadyError(
context,
"Hosted runner is draining and not accepting headless session traffic",
{
draining: "true",
maestro_session_id: activeSessionId,
requested_maestro_session_id: requestedSessionId,
},
);
}
if (!activeSessionId) {
return;
}
Expand Down
145 changes: 145 additions & 0 deletions test/web/headless-sessions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import type { RegisteredModel } from "../../src/models/registry.js";
import type { WebServerContext } from "../../src/server/app-context.js";
import { clientToolService } from "../../src/server/client-tools-service.js";
import {
HostedRunnerErrorType,
handleHeadlessConnectionCreate,
handleHeadlessSessionCreate,
handleHeadlessSessionDisconnect,
Expand Down Expand Up @@ -2845,6 +2846,150 @@ describe("headless session handlers", () => {
}
});

it("returns structured runtime-not-ready errors while hosted runners drain", async () => {
const workspaceRoot = await mkdtemp(
join(tmpdir(), "maestro-headless-hosted-draining-"),
);
try {
const context = createContext({
hostedRunner: {
enabled: true,
runnerSessionId: "mrs_test",
ownerInstanceId: "pod-a",
workspaceRoot,
workspaceId: "ws_1",
agentRunId: "run_1",
activeMaestroSessionId: "session_owner",
draining: true,
},
});
const req = createJsonRequest("POST", "/api/headless/sessions", {
model: TEST_MODEL.id,
});
const res = new MockResponse();
res.req = req;

let caught: unknown;
try {
await handleHeadlessSessionCreate(
req,
res as unknown as ServerResponse,
context,
);
} catch (error) {
caught = error;
}

expect(caught).toBeInstanceOf(ApiError);
expect((caught as ApiError).errorType).toBe(
HostedRunnerErrorType.RuntimeNotReady,
);

const errorRes = new MockResponse();
errorRes.req = req;
respondWithApiError(
errorRes as unknown as ServerResponse,
caught,
500,
{},
req,
);

expect(errorRes.statusCode).toBe(503);
expect(JSON.parse(errorRes.body)).toMatchObject({
error:
"Hosted runner is draining and not accepting headless session traffic",
code: "UNAVAILABLE",
error_type: HostedRunnerErrorType.RuntimeNotReady,
details: [
{
reason: HostedRunnerErrorType.RuntimeNotReady,
domain: "maestro.hosted_runner",
metadata: {
runner_session_id: "mrs_test",
owner_instance_id: "pod-a",
workspace_id: "ws_1",
agent_run_id: "run_1",
maestro_session_id: "session_owner",
draining: "true",
},
},
],
});
} finally {
await rm(workspaceRoot, { recursive: true, force: true });
}
});

it("reports hosted runner draining before accepting new session mutations", async () => {
const workspaceRoot = await mkdtemp(
join(tmpdir(), "maestro-headless-hosted-draining-"),
);
try {
const context = createContext({
hostedRunner: {
enabled: true,
runnerSessionId: "mrs_test",
ownerInstanceId: "pod-a",
workspaceRoot,
activeMaestroSessionId: "session_owner",
draining: true,
},
});
const req = createJsonRequest(
"POST",
"/api/headless/sessions/session_owner/messages",
{ type: "prompt", content: "after drain" },
);
const res = new MockResponse();
res.req = req;

let caught: unknown;
try {
await handleHeadlessSessionMessage(
req,
res as unknown as ServerResponse,
context,
{
id: "session_owner",
},
);
} catch (error) {
caught = error;
}

expect(caught).toBeInstanceOf(ApiError);

const errorRes = new MockResponse();
errorRes.req = req;
respondWithApiError(
errorRes as unknown as ServerResponse,
caught,
500,
{},
req,
);

expect(errorRes.statusCode).toBe(503);
expect(JSON.parse(errorRes.body)).toMatchObject({
error_type: HostedRunnerErrorType.RuntimeNotReady,
details: [
{
reason: HostedRunnerErrorType.RuntimeNotReady,
metadata: {
owner_instance_id: "pod-a",
maestro_session_id: "session_owner",
requested_maestro_session_id: "session_owner",
draining: "true",
},
},
],
});
} finally {
await rm(workspaceRoot, { recursive: true, force: true });
}
});

it("returns structured runtime owner errors for hosted session mismatches", async () => {
const workspaceRoot = await mkdtemp(
join(tmpdir(), "maestro-headless-hosted-owner-"),
Expand Down
Loading