diff --git a/ci/full-e2e-cold-path-calibration.json b/ci/full-e2e-cold-path-calibration.json new file mode 100644 index 00000000000..dab55d06d96 --- /dev/null +++ b/ci/full-e2e-cold-path-calibration.json @@ -0,0 +1,164 @@ +{ + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nFive independent workflow_dispatch full-e2e samples of current-main baseline 1a74b8348c2182fbf806726341186f008444e28e with the phase-measurement changes at 4544d07c8bfd500c3b64a74380ef5cd0e62089f5. All runs completed install, BuildKit prebuild without fallback, the silence assertion, and the expected first turn. Each budget is derived independently so phase caps diagnose regressions; they are not portions that must sum to the root-start budget.", + "schemaVersion": 1, + "calibratedAt": "2026-07-13", + "baselineMainSha": "1a74b8348c2182fbf806726341186f008444e28e", + "measurementHeadSha": "4544d07c8bfd500c3b64a74380ef5cd0e62089f5", + "workflowPath": ".github/workflows/e2e.yaml", + "job": "full-e2e", + "derivation": { + "percentile": 95, + "percentileMethod": "nearest-rank", + "minimumHeadroomMs": 5000, + "relativeHeadroomPercent": 10, + "roundUpMs": 1000 + }, + "samples": [ + { + "runId": 29285379553, + "runUrl": "https://github.com/NVIDIA/NemoClaw/actions/runs/29285379553", + "headSha": "4544d07c8bfd500c3b64a74380ef5cd0e62089f5", + "conclusion": "success", + "installExitCode": 0, + "firstTurnExitCode": 0, + "performancePassed": true, + "usedBuildKitPrebuild": true, + "buildKitFallback": false, + "maxSilenceSecs": 31, + "responseChars": 23, + "measurementsMs": { + "onboardRoot": 170850, + "rootStartToFirstTurnCompletion": 178403, + "rootEndToInstallCompletion": 137, + "firstTurnCommand": 7413, + "rootEndToFirstTurnCompletion": 7553, + "phases": { + "nemoclaw.onboard.phase.preflight": 1251, + "nemoclaw.onboard.phase.gateway": 65, + "nemoclaw.onboard.phase.provider_selection": 2312, + "nemoclaw.onboard.phase.inference": 669, + "nemoclaw.onboard.phase.sandbox": 126615 + } + } + }, + { + "runId": 29285384233, + "runUrl": "https://github.com/NVIDIA/NemoClaw/actions/runs/29285384233", + "headSha": "4544d07c8bfd500c3b64a74380ef5cd0e62089f5", + "conclusion": "success", + "installExitCode": 0, + "firstTurnExitCode": 0, + "performancePassed": true, + "usedBuildKitPrebuild": true, + "buildKitFallback": false, + "maxSilenceSecs": 31, + "responseChars": 23, + "measurementsMs": { + "onboardRoot": 149056, + "rootStartToFirstTurnCompletion": 155856, + "rootEndToInstallCompletion": 135, + "firstTurnCommand": 6662, + "rootEndToFirstTurnCompletion": 6800, + "phases": { + "nemoclaw.onboard.phase.preflight": 1132, + "nemoclaw.onboard.phase.gateway": 58, + "nemoclaw.onboard.phase.provider_selection": 1142, + "nemoclaw.onboard.phase.inference": 563, + "nemoclaw.onboard.phase.sandbox": 105938 + } + } + }, + { + "runId": 29285387079, + "runUrl": "https://github.com/NVIDIA/NemoClaw/actions/runs/29285387079", + "headSha": "4544d07c8bfd500c3b64a74380ef5cd0e62089f5", + "conclusion": "success", + "installExitCode": 0, + "firstTurnExitCode": 0, + "performancePassed": true, + "usedBuildKitPrebuild": true, + "buildKitFallback": false, + "maxSilenceSecs": 32, + "responseChars": 23, + "measurementsMs": { + "onboardRoot": 177334, + "rootStartToFirstTurnCompletion": 186018, + "rootEndToInstallCompletion": 168, + "firstTurnCommand": 8512, + "rootEndToFirstTurnCompletion": 8684, + "phases": { + "nemoclaw.onboard.phase.preflight": 1193, + "nemoclaw.onboard.phase.gateway": 51, + "nemoclaw.onboard.phase.provider_selection": 1358, + "nemoclaw.onboard.phase.inference": 638, + "nemoclaw.onboard.phase.sandbox": 132561 + } + } + }, + { + "runId": 29285389469, + "runUrl": "https://github.com/NVIDIA/NemoClaw/actions/runs/29285389469", + "headSha": "4544d07c8bfd500c3b64a74380ef5cd0e62089f5", + "conclusion": "success", + "installExitCode": 0, + "firstTurnExitCode": 0, + "performancePassed": true, + "usedBuildKitPrebuild": true, + "buildKitFallback": false, + "maxSilenceSecs": 32, + "responseChars": 23, + "measurementsMs": { + "onboardRoot": 175231, + "rootStartToFirstTurnCompletion": 182517, + "rootEndToInstallCompletion": 131, + "firstTurnCommand": 7152, + "rootEndToFirstTurnCompletion": 7286, + "phases": { + "nemoclaw.onboard.phase.preflight": 1205, + "nemoclaw.onboard.phase.gateway": 62, + "nemoclaw.onboard.phase.provider_selection": 1377, + "nemoclaw.onboard.phase.inference": 805, + "nemoclaw.onboard.phase.sandbox": 130203 + } + } + }, + { + "runId": 29285391845, + "runUrl": "https://github.com/NVIDIA/NemoClaw/actions/runs/29285391845", + "headSha": "4544d07c8bfd500c3b64a74380ef5cd0e62089f5", + "conclusion": "success", + "installExitCode": 0, + "firstTurnExitCode": 0, + "performancePassed": true, + "usedBuildKitPrebuild": true, + "buildKitFallback": false, + "maxSilenceSecs": 30, + "responseChars": 23, + "measurementsMs": { + "onboardRoot": 155691, + "rootStartToFirstTurnCompletion": 160740, + "rootEndToInstallCompletion": 104, + "firstTurnCommand": 4942, + "rootEndToFirstTurnCompletion": 5049, + "phases": { + "nemoclaw.onboard.phase.preflight": 5101, + "nemoclaw.onboard.phase.gateway": 211, + "nemoclaw.onboard.phase.provider_selection": 1585, + "nemoclaw.onboard.phase.inference": 583, + "nemoclaw.onboard.phase.sandbox": 118007 + } + } + } + ], + "derivedBudgetsMs": { + "rootStartToFirstTurnCompletionBudgetMs": 205000, + "rootEndToFirstTurnCompletionBudgetMs": 14000, + "phaseBudgetsMs": { + "nemoclaw.onboard.phase.preflight": 11000, + "nemoclaw.onboard.phase.gateway": 6000, + "nemoclaw.onboard.phase.provider_selection": 8000, + "nemoclaw.onboard.phase.inference": 6000, + "nemoclaw.onboard.phase.sandbox": 146000 + } + } +} diff --git a/ci/onboard-performance-budget.json b/ci/onboard-performance-budget.json index 3f9879c82b8..7b7405900de 100644 --- a/ci/onboard-performance-budget.json +++ b/ci/onboard-performance-budget.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nInitial advisory budget for the cloud-onboard-e2e warm-system trace signal. Profiling traces from #3769 were not available in durable CI artifacts when #3776 was implemented. The latest three release tags only exposed one tag-matching trace artifact, from a failed v0.0.66 nightly run, so this cap is calibrated from the latest ten distinct successful main full-trace samples available on 2026-06-23. Those samples had total durations of 298250 ms, 296926 ms, 304190 ms, 294859 ms, 305013 ms, 316147 ms, 300843 ms, 292702 ms, 201332 ms, and 206250 ms; the cap uses p95 via linear interpolation (index 8.55 between samples 8 and 9) plus 25 percent, rounded up to the nearest 30 seconds.", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nInitial advisory budget for the cloud-onboard-e2e warm-system trace signal. Profiling traces from #3769 were not available in durable CI artifacts when #3776 was implemented. The latest three release tags only exposed one tag-matching trace artifact, from a failed v0.0.66 nightly run, so this cap is calibrated from the latest ten distinct successful main full-trace samples available on 2026-06-23. Those samples had total durations of 298250 ms, 296926 ms, 304190 ms, 294859 ms, 305013 ms, 316147 ms, 300843 ms, 292702 ms, 201332 ms, and 206250 ms; the cap uses p95 via linear interpolation (index 8.55 between samples 8 and 9) plus 25 percent, rounded up to the nearest 30 seconds.\n\nThe full-e2e cold-path budgets are derived from the five exact-head current-main samples recorded in ci/full-e2e-cold-path-calibration.json. For each interval and phase independently, the budget is nearest-rank p95 plus the larger of 5 seconds or 10 percent, rounded up to the nearest second. Independent phase caps are diagnostic regression gates, not additive portions of the root-start interval.", "schemaVersion": 1, "mode": "advisory", "scope": "cloud-onboard-e2e warm-system", @@ -11,5 +11,16 @@ "phaseRegressionWarning": { "minDeltaMs": 30000, "minPercent": 30 + }, + "fullE2eColdPath": { + "rootStartToFirstTurnCompletionBudgetMs": 205000, + "rootEndToFirstTurnCompletionBudgetMs": 14000, + "phaseBudgetsMs": { + "nemoclaw.onboard.phase.preflight": 11000, + "nemoclaw.onboard.phase.gateway": 6000, + "nemoclaw.onboard.phase.provider_selection": 8000, + "nemoclaw.onboard.phase.inference": 6000, + "nemoclaw.onboard.phase.sandbox": 146000 + } } } diff --git a/ci/source-shape-test-budget.json b/ci/source-shape-test-budget.json index 61e23330b20..b9c129b47b6 100644 --- a/ci/source-shape-test-budget.json +++ b/ci/source-shape-test-budget.json @@ -266,6 +266,16 @@ "test": "keeps the setup docs aligned with the stable default", "category": "compatibility" }, + { + "file": "test/onboard-performance-config-schema.test.ts", + "test": "keeps configured budgets derived from the checked-in samples", + "category": "compatibility" + }, + { + "file": "test/onboard-performance-config-schema.test.ts", + "test": "records five independent successful exact-head samples", + "category": "compatibility" + }, { "file": "test/openclaw-dependency-review.test.ts", "test": "runs and gates the real patched-distribution harness only from trusted main code", diff --git a/schemas/onboard-config.schema.json b/schemas/onboard-config.schema.json index 23329db0ec1..2af53218228 100644 --- a/schemas/onboard-config.schema.json +++ b/schemas/onboard-config.schema.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/NVIDIA/NemoClaw/schemas/onboard-config.schema.json", "title": "NemoClaw onboard performance budget config", - "description": "Advisory warm-system cloud onboard timing budget consumed by the nightly scorecard.", + "description": "Advisory warm-system cloud onboard timing budget and full-E2E cold-path phase budget.", "type": "object", "additionalProperties": false, "required": [ @@ -12,7 +12,8 @@ "scope", "totalBudgetMs", "regressionWarning", - "phaseRegressionWarning" + "phaseRegressionWarning", + "fullE2eColdPath" ], "properties": { "$comment": { @@ -37,6 +38,48 @@ }, "phaseRegressionWarning": { "$ref": "#/$defs/threshold" + }, + "fullE2eColdPath": { + "type": "object", + "additionalProperties": false, + "required": [ + "rootStartToFirstTurnCompletionBudgetMs", + "rootEndToFirstTurnCompletionBudgetMs", + "phaseBudgetsMs" + ], + "properties": { + "rootStartToFirstTurnCompletionBudgetMs": { + "type": "number", + "minimum": 0, + "description": "Maximum time from the nemoclaw.onboard root start until the first agent-turn command completes." + }, + "rootEndToFirstTurnCompletionBudgetMs": { + "type": "number", + "minimum": 0, + "maximum": { + "$data": "1/rootStartToFirstTurnCompletionBudgetMs" + }, + "description": "Maximum time from the nemoclaw.onboard root end until the first agent-turn command completes." + }, + "phaseBudgetsMs": { + "type": "object", + "additionalProperties": false, + "required": [ + "nemoclaw.onboard.phase.preflight", + "nemoclaw.onboard.phase.gateway", + "nemoclaw.onboard.phase.provider_selection", + "nemoclaw.onboard.phase.inference", + "nemoclaw.onboard.phase.sandbox" + ], + "properties": { + "nemoclaw.onboard.phase.preflight": { "$ref": "#/$defs/milliseconds" }, + "nemoclaw.onboard.phase.gateway": { "$ref": "#/$defs/milliseconds" }, + "nemoclaw.onboard.phase.provider_selection": { "$ref": "#/$defs/milliseconds" }, + "nemoclaw.onboard.phase.inference": { "$ref": "#/$defs/milliseconds" }, + "nemoclaw.onboard.phase.sandbox": { "$ref": "#/$defs/milliseconds" } + } + } + } } }, "$defs": { @@ -54,6 +97,10 @@ "minimum": 0 } } + }, + "milliseconds": { + "type": "number", + "minimum": 0 } } } diff --git a/scripts/validate-configs.ts b/scripts/validate-configs.ts index bb908f4011b..0e028cf40ad 100755 --- a/scripts/validate-configs.ts +++ b/scripts/validate-configs.ts @@ -190,6 +190,13 @@ function loadSchema(repoRelative: string): object { return schema; } +function compileConfigSchema( + repoRelative: string, + ajv = new Ajv({ allErrors: true, strict: false, $data: true }), +) { + return ajv.compile(loadSchema(repoRelative)); +} + type ValidationParams = { additionalProperty?: string; unevaluatedProperty?: string }; /** @@ -300,7 +307,7 @@ function main(): void { targets = discoverTargets(); } - const ajv = new Ajv({ allErrors: true, strict: false }); + const ajv = new Ajv({ allErrors: true, strict: false, $data: true }); let totalErrors = 0; let totalFiles = 0; @@ -309,8 +316,7 @@ function main(): void { for (const target of targets) { let validate; try { - const schema = loadSchema(target.schema); - validate = ajv.compile(schema); + validate = compileConfigSchema(target.schema, ajv); } catch (err) { console.error(`FAIL: ${target.schema}`); console.error(` Could not compile schema: ${err}`); @@ -367,6 +373,7 @@ function main(): void { // Export for unit tests without re-running main(). export { DANGEROUS_HOSTS, + compileConfigSchema, discoverTargets, findDangerousHosts, findDangerousRouterApiBases, diff --git a/src/lib/onboard/machine/handlers/gateway.test.ts b/src/lib/onboard/machine/handlers/gateway.test.ts index 11aef3f99df..f5be1e5a55d 100644 --- a/src/lib/onboard/machine/handlers/gateway.test.ts +++ b/src/lib/onboard/machine/handlers/gateway.test.ts @@ -1,12 +1,16 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; import { describe, expect, it, vi } from "vitest"; - +import type { GatewayReuseState } from "../../../state/gateway"; import { createSession, type Session } from "../../../state/onboard-session"; +import { flushTrace, resetTraceForTests, TRACE_FILE_ENV, type TraceArtifact } from "../../../trace"; import type { GatewayContainerState } from "../../gateway-container-running"; -import type { GatewayReuseState } from "../../../state/gateway"; -import { handleGatewayState, type GatewayStateOptions } from "./gateway"; +import { ONBOARD_TRACE_PHASE_NAMES } from "../../tracing"; +import { type GatewayStateOptions, handleGatewayState } from "./gateway"; type Gpu = { type: string } | null; @@ -85,6 +89,32 @@ function baseOptions( }; } +async function captureTraceArtifact(run: () => Promise): Promise { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-trace-")); + const traceFile = path.join(directory, "trace.json"); + const previousTraceFile = process.env[TRACE_FILE_ENV]; + process.env[TRACE_FILE_ENV] = traceFile; + resetTraceForTests(); + + try { + await run(); + flushTrace(); + return JSON.parse(fs.readFileSync(traceFile, "utf8")) as TraceArtifact; + } finally { + previousTraceFile === undefined + ? Reflect.deleteProperty(process.env, TRACE_FILE_ENV) + : Reflect.set(process.env, TRACE_FILE_ENV, previousTraceFile); + resetTraceForTests(); + fs.rmSync(directory, { recursive: true, force: true }); + } +} + +function gatewaySpans(artifact: TraceArtifact) { + return artifact.resource_spans[0].scope_spans[0].spans.filter( + (span) => span.name === ONBOARD_TRACE_PHASE_NAMES.gateway, + ); +} + describe("handleGatewayState", () => { it("starts the gateway when no reusable gateway exists", async () => { const { deps, calls } = createDeps(); @@ -119,6 +149,40 @@ describe("handleGatewayState", () => { expect(calls.complete).toHaveBeenCalledWith("gateway"); }); + it("emits one successful gateway phase when reusing a healthy gateway", async () => { + const artifact = await captureTraceArtifact(async () => { + const { deps } = createDeps(); + + await handleGatewayState(baseOptions(deps, "healthy")); + }); + + expect(gatewaySpans(artifact)).toEqual([ + expect.objectContaining({ + status: { code: "OK" }, + attributes: { reuse_state: "healthy", gpu_passthrough: true }, + }), + ]); + }); + + it("emits one failed gateway phase when stopped-container recovery fails", async () => { + const artifact = await captureTraceArtifact(async () => { + const { deps } = createDeps({ + gatewayCliSupportsLifecycleCommands: vi.fn(() => true), + verifyGatewayContainerRunning: vi.fn(() => "stopped" as GatewayContainerState), + recoverGatewayRuntime: vi.fn(async () => false), + }); + + await expect(handleGatewayState(baseOptions(deps, "healthy"))).rejects.toThrow("exit 1"); + }); + + expect(gatewaySpans(artifact)).toEqual([ + expect.objectContaining({ + status: { code: "ERROR", message: "exit 1" }, + attributes: { reuse_state: "healthy", gpu_passthrough: true }, + }), + ]); + }); + it("reuses healthy gateways on resume only when the gateway step was complete", async () => { const session = createSession(); session.steps.gateway.status = "complete"; diff --git a/src/lib/onboard/machine/handlers/gateway.ts b/src/lib/onboard/machine/handlers/gateway.ts index 72812d601db..bd3401b977c 100644 --- a/src/lib/onboard/machine/handlers/gateway.ts +++ b/src/lib/onboard/machine/handlers/gateway.ts @@ -71,7 +71,15 @@ export interface GatewayStateResult { stateResult: OnboardStateTransitionResult; } -export async function handleGatewayState({ +export async function handleGatewayState( + options: GatewayStateOptions, +): Promise { + return withGatewayTrace(options.initialGatewayReuseState, options.gpuPassthrough, () => + handleGatewayStatePhase(options), + ); +} + +async function handleGatewayStatePhase({ resume, session, initialGatewayReuseState, @@ -223,9 +231,7 @@ export async function handleGatewayState({ } else if (gatewayReuseState === "foreign-active") { gatewayReuseState = "missing"; } - await withGatewayTrace(gatewayReuseState, gpuPassthrough, () => - deps.startGateway(gpu, { gpuPassthrough }), - ); + await deps.startGateway(gpu, { gpuPassthrough }); session = await deps.recordStepComplete("gateway"); } diff --git a/test/e2e/fixtures/onboard-performance.ts b/test/e2e/fixtures/onboard-performance.ts index f8550398c78..f54f96f1fab 100644 --- a/test/e2e/fixtures/onboard-performance.ts +++ b/test/e2e/fixtures/onboard-performance.ts @@ -6,31 +6,165 @@ import type { ShellProbeOutputEvent } from "./shell-probe.ts"; const ONBOARD_SCOPE = "nemoclaw.onboard"; const ONBOARD_ROOT_SPAN = "nemoclaw.onboard"; const NANOSECONDS_PER_MILLISECOND = 1_000_000n; +const DURATION_TOLERANCE_MS = 0.001; +const TRACE_ID_PATTERN = /^[0-9a-f]{32}$/u; +const SPAN_ID_PATTERN = /^[0-9a-f]{16}$/u; +export const ONBOARD_PHASE_NAMES = [ + "nemoclaw.onboard.phase.preflight", + "nemoclaw.onboard.phase.gateway", + "nemoclaw.onboard.phase.provider_selection", + "nemoclaw.onboard.phase.inference", + "nemoclaw.onboard.phase.sandbox", +] as const; + +export type OnboardPhaseName = (typeof ONBOARD_PHASE_NAMES)[number]; + +const ONBOARD_PHASE_NAME_SET = new Set(ONBOARD_PHASE_NAMES); +const COLD_ONBOARD_BUDGET_KEYS = new Set([ + "rootStartToFirstTurnCompletionBudgetMs", + "rootEndToFirstTurnCompletionBudgetMs", + "phaseBudgetsMs", +]); export interface OnboardTraceWindow { durationMs: number; finishedAtMs: number; + phaseDurationsMs: Record; startedAtMs: number; } +export interface ColdOnboardPerformanceBudget { + phaseBudgetsMs: Record; + rootEndToFirstTurnCompletionBudgetMs: number; + rootStartToFirstTurnCompletionBudgetMs: number; +} + +export interface ColdOnboardPerformanceEvaluation { + passed: boolean; + rootEndToFirstTurnCompletionMs: number; + rootStartToFirstTurnCompletionMs: number; + violations: string[]; +} + +interface ParsedSpan { + durationMs: number; + endNs: bigint; + record: Record; + spanId: string; + startNs: bigint; +} + function asRecord(value: unknown): Record | null { return value !== null && typeof value === "object" ? (value as Record) : null; } -function unixNanoseconds(value: unknown, field: string): bigint { +function unixNanoseconds(value: unknown, spanLabel: string, field: string): bigint { if (typeof value !== "string" || !/^\d+$/u.test(value)) { - throw new Error(`onboard root span has an invalid ${field}`); + throw new Error(`${spanLabel} span has an invalid ${field}`); } return BigInt(value); } +function durationMilliseconds(value: unknown, spanLabel: string): number { + if (typeof value !== "number" || !Number.isFinite(value) || value < 0) { + throw new Error(`${spanLabel} span has an invalid duration`); + } + return value; +} + +function identifier(value: unknown, pattern: RegExp, field: string): string { + if (typeof value !== "string" || !pattern.test(value)) { + throw new Error(`trace artifact has an invalid ${field}`); + } + return value; +} + +function parseSpan( + record: Record, + spanLabel: string, + expectedTraceId: string, +): ParsedSpan { + const traceId = identifier(record.trace_id, TRACE_ID_PATTERN, `${spanLabel} trace_id`); + if (traceId !== expectedTraceId) { + throw new Error(`${spanLabel} span does not belong to the onboard trace`); + } + const spanId = identifier(record.span_id, SPAN_ID_PATTERN, `${spanLabel} span_id`); + if (asRecord(record.status)?.code !== "OK") { + throw new Error(`${spanLabel} span status is missing or not OK`); + } + const startNs = unixNanoseconds(record.start_time_unix_nano, spanLabel, "start time"); + const endNs = unixNanoseconds(record.end_time_unix_nano, spanLabel, "end time"); + if (endNs < startNs) { + throw new Error(`${spanLabel} span ends before it starts`); + } + const durationMs = durationMilliseconds(record.duration_ms, spanLabel); + const timestampDurationMs = Number(endNs - startNs) / Number(NANOSECONDS_PER_MILLISECOND); + if (Math.abs(timestampDurationMs - durationMs) > DURATION_TOLERANCE_MS) { + throw new Error(`${spanLabel} span duration does not match its timestamps`); + } + return { durationMs, endNs, record, spanId, startNs }; +} + +function nonNegativeMilliseconds(value: unknown): number | null { + return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null; +} + +function asColdOnboardBudget(value: unknown): ColdOnboardPerformanceBudget | null { + const record = asRecord(value); + if (!record || Object.keys(record).some((key) => !COLD_ONBOARD_BUDGET_KEYS.has(key))) return null; + const rootStartToFirstTurnCompletionBudgetMs = nonNegativeMilliseconds( + record.rootStartToFirstTurnCompletionBudgetMs, + ); + const rootEndToFirstTurnCompletionBudgetMs = nonNegativeMilliseconds( + record.rootEndToFirstTurnCompletionBudgetMs, + ); + const phaseBudgets = asRecord(record.phaseBudgetsMs); + if ( + rootStartToFirstTurnCompletionBudgetMs === null || + rootEndToFirstTurnCompletionBudgetMs === null || + rootEndToFirstTurnCompletionBudgetMs > rootStartToFirstTurnCompletionBudgetMs || + !phaseBudgets + ) { + return null; + } + + if (Object.keys(phaseBudgets).some((name) => !ONBOARD_PHASE_NAME_SET.has(name))) return null; + const phaseBudgetsMs = {} as Record; + for (const name of ONBOARD_PHASE_NAMES) { + const validatedBudgetMs = nonNegativeMilliseconds(phaseBudgets[name]); + if (validatedBudgetMs === null) return null; + phaseBudgetsMs[name] = validatedBudgetMs; + } + + return { + rootStartToFirstTurnCompletionBudgetMs, + rootEndToFirstTurnCompletionBudgetMs, + phaseBudgetsMs, + }; +} + +export function readColdOnboardPerformanceBudget(value: unknown): ColdOnboardPerformanceBudget { + const budget = asColdOnboardBudget(asRecord(value)?.fullE2eColdPath); + if (!budget) { + throw new Error("fullE2eColdPath performance budget is invalid or missing"); + } + return budget; +} + export function readOnboardTraceWindow(artifact: unknown): OnboardTraceWindow { - const resourceSpans = asRecord(artifact)?.resource_spans; + const artifactRecord = asRecord(artifact); + const summaryTraceId = identifier( + asRecord(artifactRecord?.summary)?.trace_id, + TRACE_ID_PATTERN, + "summary trace_id", + ); + const resourceSpans = artifactRecord?.resource_spans; if (!Array.isArray(resourceSpans)) { throw new Error("trace artifact is missing resource_spans"); } const roots: Record[] = []; + const phases = new Map>(); for (const resourceSpan of resourceSpans) { const scopeSpans = asRecord(resourceSpan)?.scope_spans; if (!Array.isArray(scopeSpans)) continue; @@ -38,10 +172,20 @@ export function readOnboardTraceWindow(artifact: unknown): OnboardTraceWindow { const scopeSpanRecord = asRecord(scopeSpan); if (asRecord(scopeSpanRecord?.scope)?.name !== ONBOARD_SCOPE) continue; const spans = scopeSpanRecord?.spans; - if (!Array.isArray(spans)) continue; + if (!Array.isArray(spans) || spans.some((span) => asRecord(span) === null)) { + throw new Error("onboard trace scope contains malformed spans"); + } for (const span of spans) { - const record = asRecord(span); + const record = span as Record; + if (record.trace_id !== summaryTraceId) continue; if (record?.name === ONBOARD_ROOT_SPAN) roots.push(record); + if (typeof record?.name === "string" && ONBOARD_PHASE_NAME_SET.has(record.name)) { + const phaseName = record.name as OnboardPhaseName; + if (phases.has(phaseName)) { + throw new Error(`trace artifact must contain exactly one ${phaseName} span`); + } + phases.set(phaseName, record); + } } } } @@ -49,21 +193,86 @@ export function readOnboardTraceWindow(artifact: unknown): OnboardTraceWindow { if (roots.length !== 1) { throw new Error("trace artifact must contain exactly one onboard root span"); } - const root = roots[0]; - if (asRecord(root.status)?.code !== "OK") { - throw new Error("onboard root span status is missing or not OK"); + const root = parseSpan(roots[0], "onboard root", summaryTraceId); + if (root.record.parent_span_id !== undefined) { + throw new Error("onboard root span must not have a parent"); } - const startedAtNs = unixNanoseconds(root.start_time_unix_nano, "start time"); - const finishedAtNs = unixNanoseconds(root.end_time_unix_nano, "end time"); - if (finishedAtNs < startedAtNs) { - throw new Error("onboard root span ends before it starts"); + const phaseDurationsMs = {} as Record; + const spanIds = new Set([root.spanId]); + let previousPhaseEndNs = root.startNs; + for (const phaseName of ONBOARD_PHASE_NAMES) { + const record = phases.get(phaseName); + if (!record) { + throw new Error(`trace artifact is missing ${phaseName} span`); + } + const phase = parseSpan(record, `onboard phase ${phaseName}`, summaryTraceId); + if (spanIds.has(phase.spanId)) { + throw new Error(`trace artifact contains duplicate span_id ${phase.spanId}`); + } + spanIds.add(phase.spanId); + if (phase.record.parent_span_id !== root.spanId) { + throw new Error(`${phaseName} span is not a child of the onboard root`); + } + if (phase.startNs < root.startNs || phase.endNs > root.endNs) { + throw new Error(`${phaseName} span is outside the onboard root window`); + } + if (phase.startNs < previousPhaseEndNs) { + throw new Error(`${phaseName} span overlaps or precedes the prior onboard phase`); + } + previousPhaseEndNs = phase.endNs; + phaseDurationsMs[phaseName] = phase.durationMs; + } + + return { + durationMs: root.durationMs, + finishedAtMs: Number(root.endNs / NANOSECONDS_PER_MILLISECOND), + phaseDurationsMs, + startedAtMs: Number(root.startNs / NANOSECONDS_PER_MILLISECOND), + }; +} + +export function evaluateColdOnboardPerformance( + trace: Pick, + firstTurnCompletedAtMs: number, + budget: ColdOnboardPerformanceBudget, +): ColdOnboardPerformanceEvaluation { + if ( + !Number.isFinite(firstTurnCompletedAtMs) || + !Number.isFinite(trace.startedAtMs) || + !Number.isFinite(trace.finishedAtMs) || + trace.finishedAtMs < trace.startedAtMs || + firstTurnCompletedAtMs < trace.finishedAtMs + ) { + throw new Error("cold onboard timing boundaries are invalid"); + } + + const rootStartToFirstTurnCompletionMs = firstTurnCompletedAtMs - trace.startedAtMs; + const rootEndToFirstTurnCompletionMs = firstTurnCompletedAtMs - trace.finishedAtMs; + const violations: string[] = []; + if (rootStartToFirstTurnCompletionMs > budget.rootStartToFirstTurnCompletionBudgetMs) { + violations.push( + `root-start-to-first-turn-completion ${rootStartToFirstTurnCompletionMs}ms exceeds ${budget.rootStartToFirstTurnCompletionBudgetMs}ms`, + ); + } + if (rootEndToFirstTurnCompletionMs > budget.rootEndToFirstTurnCompletionBudgetMs) { + violations.push( + `root-end-to-first-turn-completion ${rootEndToFirstTurnCompletionMs}ms exceeds ${budget.rootEndToFirstTurnCompletionBudgetMs}ms`, + ); + } + for (const phaseName of ONBOARD_PHASE_NAMES) { + const phaseBudgetMs = budget.phaseBudgetsMs[phaseName]; + const phaseDurationMs = trace.phaseDurationsMs[phaseName]; + if (phaseBudgetMs !== undefined && phaseDurationMs > phaseBudgetMs) { + violations.push(`${phaseName} ${phaseDurationMs}ms exceeds ${phaseBudgetMs}ms`); + } } return { - durationMs: Number((finishedAtNs - startedAtNs) / NANOSECONDS_PER_MILLISECOND), - finishedAtMs: Number(finishedAtNs / NANOSECONDS_PER_MILLISECOND), - startedAtMs: Number(startedAtNs / NANOSECONDS_PER_MILLISECOND), + passed: violations.length === 0, + rootStartToFirstTurnCompletionMs, + rootEndToFirstTurnCompletionMs, + violations, }; } diff --git a/test/e2e/live/full-e2e.test.ts b/test/e2e/live/full-e2e.test.ts index c177fa43fd4..05ee1613be9 100644 --- a/test/e2e/live/full-e2e.test.ts +++ b/test/e2e/live/full-e2e.test.ts @@ -17,8 +17,11 @@ import { import { expect, test } from "../fixtures/e2e-test.ts"; import { requireHostedInferenceConfig } from "../fixtures/hosted-inference.ts"; import { + type ColdOnboardPerformanceBudget, + evaluateColdOnboardPerformance, maximumOutputSilenceMs, type OnboardTraceWindow, + readColdOnboardPerformanceBudget, readOnboardTraceWindow, } from "../fixtures/onboard-performance.ts"; import { CLI_ENTRYPOINT, REPO_ROOT } from "../fixtures/paths.ts"; @@ -33,15 +36,6 @@ import { extractOpenClawAgentPayloadText } from "./agent-turn-latency-helpers.ts const SANDBOX_NAME = process.env.NEMOCLAW_SANDBOX_NAME ?? "e2e-full"; const LIVE_TIMEOUT_MS = 50 * 60_000; const FIRST_TURN_TIMEOUT_MS = 240_000; -// Cold-path acceptance budget for install + BuildKit image build + gateway -// health + first hosted agent turn (#6002, #6265). The dominant term is the -// cold BuildKit image build, which swings run-to-run with Docker Hub pull -// speed and hosted-runner I/O. Observed post-#6265 onboard phase alone ranged -// 163s (pass) to 173s (fail) on identical `main` commits — a ~10s swing — so -// the original 180s cap left only ~7s of headroom and tipped over on slow -// builds. Raised to 205s to absorb build-phase variance while still catching -// gross onboard regressions (first hosted turn itself is only ~5-8s). -const ONBOARD_BUDGET_SECS = 205; const MAX_SILENCE_SECS = 60; const EXPECTED_FIRST_REPLY = "NEMOCLAW_E2E_READY_6002"; const MEASURE_COLD_ONBOARD = process.env.E2E_TARGET_ID === "full-e2e"; @@ -146,16 +140,37 @@ function createColdOnboardCapture(): ColdOnboardCapture | null { : null; } +function readFullE2eColdPathBudget() { + try { + return readColdOnboardPerformanceBudget( + JSON.parse( + fs.readFileSync(path.join(REPO_ROOT, "ci", "onboard-performance-budget.json"), "utf8"), + ) as unknown, + ); + } catch (error) { + throw new Error( + `Full E2E cold-path performance budget is invalid: ${error instanceof Error ? error.message : String(error)}`, + { cause: error }, + ); + } +} + async function assertColdOnboardPerformance(input: { apiKey: string; artifacts: ArtifactSink; + budget: ColdOnboardPerformanceBudget; install: ShellProbeResult; + installCompletedAtMs: number; outputEvents: readonly ShellProbeOutputEvent[]; sandbox: SandboxClient; traceDirectory: string; traceFile: string; }): Promise { const traceWindow = readAndDeleteTraceWindow(input.traceFile, input.traceDirectory); + expect( + input.installCompletedAtMs, + "install completion must not precede the onboard root end", + ).toBeGreaterThanOrEqual(traceWindow.finishedAtMs); const ansiSgr = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g"); const plain = resultText(input.install).replace(ansiSgr, ""); const heartbeatCount = (plain.match(/Still working on /g) ?? []).length; @@ -167,7 +182,9 @@ async function assertColdOnboardPerformance(input: { const classicBuildSteps = (plain.match(/Step \d+\/\d+ :/gu) ?? []).length; const maxSilenceMs = maximumOutputSilenceMs(traceWindow, input.outputEvents); const maxSilenceSecs = Math.ceil(maxSilenceMs / 1_000); + const rootEndToInstallCompletionMs = input.installCompletedAtMs - traceWindow.finishedAtMs; + const firstTurnStartedAtMs = Date.now(); const turn = await input.sandbox.execShell( SANDBOX_NAME, trustedSandboxShellScript( @@ -181,21 +198,41 @@ async function assertColdOnboardPerformance(input: { timeoutMs: FIRST_TURN_TIMEOUT_MS, }, ); - const totalMs = Date.now() - traceWindow.startedAtMs; - const totalSecs = Math.ceil(totalMs / 1_000); + const firstTurnCompletedAtMs = Date.now(); + const firstTurnCommandMs = firstTurnCompletedAtMs - firstTurnStartedAtMs; + const performanceEvaluation = evaluateColdOnboardPerformance( + traceWindow, + firstTurnCompletedAtMs, + input.budget, + ); + const rootStartToFirstTurnCompletionSecs = Math.ceil( + performanceEvaluation.rootStartToFirstTurnCompletionMs / 1_000, + ); const turnText = resultText(turn); const assistantReply = extractOpenClawAgentPayloadText(turnText).trim(); const compactAssistantReply = assistantReply.replace(/\s+/gu, ""); const responseChars = assistantReply.length; await input.artifacts.writeJson("onboard-progress-budget.json", { + schemaVersion: "nemoclaw.full_e2e_cold_performance.v2", sandbox: SANDBOX_NAME, installExitCode: input.install.exitCode, firstTurnExitCode: turn.exitCode, + phaseMeasurements: { + onboardRootMs: traceWindow.durationMs, + rootStartToFirstTurnCompletionMs: performanceEvaluation.rootStartToFirstTurnCompletionMs, + rootEndToInstallCompletionMs, + firstTurnCommandMs, + rootEndToFirstTurnCompletionMs: performanceEvaluation.rootEndToFirstTurnCompletionMs, + tracePhasesMs: traceWindow.phaseDurationsMs, + }, onboardSecs: Math.ceil(traceWindow.durationMs / 1_000), - totalMs, - totalSecs, - budgetSecs: ONBOARD_BUDGET_SECS, + rootStartToFirstTurnCompletionSecs, + budget: input.budget, + performance: { + passed: performanceEvaluation.passed, + violations: performanceEvaluation.violations, + }, heartbeatCount, maxSilenceSecs, maxSilenceBudgetSecs: MAX_SILENCE_SECS, @@ -219,15 +256,16 @@ async function assertColdOnboardPerformance(input: { `expected the sentinel first agent reply, got: ${turnText}`, ).toContain(EXPECTED_FIRST_REPLY); expect( - totalMs, - `[1/8]-to-first-response took ${totalSecs}s, over the ${ONBOARD_BUDGET_SECS}s budget`, - ).toBeLessThanOrEqual(ONBOARD_BUDGET_SECS * 1_000); + performanceEvaluation.passed, + `onboard-root-start-to-first-turn-completion took ${rootStartToFirstTurnCompletionSecs}s; ${performanceEvaluation.violations.join("; ")}`, + ).toBe(true); } test("full e2e: install, onboard, inference, cli operations, and cleanup", { timeout: LIVE_TIMEOUT_MS, }, async ({ artifacts, cleanup: cleanupRegistry, host, sandbox, secrets, skip }) => { const hosted = requireHostedInferenceConfig(secrets); + const coldOnboardBudget = readFullE2eColdPathBudget(); const redactionValues = [hosted.apiKey]; await artifacts.target.declare({ id: "full-e2e", @@ -298,12 +336,15 @@ test("full e2e: install, onboard, inference, cli operations, and cleanup", { redactionValues, timeoutMs: 25 * 60_000, }); + const installCompletedAtMs = Date.now(); expect(install.exitCode, resultText(install)).toBe(0); await (coldOnboard ? assertColdOnboardPerformance({ apiKey: hosted.apiKey, artifacts, + budget: coldOnboardBudget, install, + installCompletedAtMs, outputEvents: coldOnboard.outputEvents, sandbox, traceDirectory: coldOnboard.traceDirectory, diff --git a/test/e2e/support/onboard-performance.test.ts b/test/e2e/support/onboard-performance.test.ts index 661fa74b01f..c69f11168e8 100644 --- a/test/e2e/support/onboard-performance.test.ts +++ b/test/e2e/support/onboard-performance.test.ts @@ -2,10 +2,56 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it } from "vitest"; -import { maximumOutputSilenceMs, readOnboardTraceWindow } from "../fixtures/onboard-performance.ts"; +import { + evaluateColdOnboardPerformance, + maximumOutputSilenceMs, + ONBOARD_PHASE_NAMES, + readColdOnboardPerformanceBudget, + readOnboardTraceWindow, +} from "../fixtures/onboard-performance.ts"; import { extractOpenClawAgentPayloadText } from "../live/agent-turn-latency-helpers.ts"; -function traceArtifact(overrides: Partial> = {}): Record { +const TRACE_ID = "0123456789abcdef0123456789abcdef"; +const FOREIGN_TRACE_ID = "fedcba9876543210fedcba9876543210"; +const ROOT_SPAN_ID = "0000000000000001"; +const ROOT_START_MS = 1_000; +const ROOT_END_MS = 6_000; + +function timestampNs(milliseconds: number): string { + return String(milliseconds * 1_000_000); +} + +function phaseSpan( + name: (typeof ONBOARD_PHASE_NAMES)[number], + spanId: string, + startMs: number, + durationMs: number, +): Record { + return { + trace_id: TRACE_ID, + span_id: spanId, + parent_span_id: ROOT_SPAN_ID, + name, + start_time_unix_nano: timestampNs(startMs), + end_time_unix_nano: timestampNs(startMs + durationMs), + duration_ms: durationMs, + status: { code: "OK" }, + }; +} + +const PHASE_SPANS: Array> = [ + phaseSpan(ONBOARD_PHASE_NAMES[0], "0000000000000002", 1_100, 250), + phaseSpan(ONBOARD_PHASE_NAMES[1], "0000000000000003", 1_400, 500), + phaseSpan(ONBOARD_PHASE_NAMES[2], "0000000000000004", 2_000, 750), + phaseSpan(ONBOARD_PHASE_NAMES[3], "0000000000000005", 2_800, 1_000), + phaseSpan(ONBOARD_PHASE_NAMES[4], "0000000000000006", 4_000, 1_250), +]; + +function traceArtifact( + rootOverrides: Partial> = {}, + phaseSpans = PHASE_SPANS, + summaryOverrides: Partial> = {}, +): Record { return { resource_spans: [ { @@ -14,36 +60,221 @@ function traceArtifact(overrides: Partial> = {}): Record scope: { name: "nemoclaw.onboard" }, spans: [ { + trace_id: TRACE_ID, + span_id: ROOT_SPAN_ID, name: "nemoclaw.onboard", - start_time_unix_nano: "1000000000", - end_time_unix_nano: "4750000000", + start_time_unix_nano: timestampNs(ROOT_START_MS), + end_time_unix_nano: timestampNs(ROOT_END_MS), + duration_ms: ROOT_END_MS - ROOT_START_MS, status: { code: "OK" }, - ...overrides, + ...rootOverrides, }, + ...phaseSpans, ], }, ], }, ], + summary: { trace_id: TRACE_ID, ...summaryOverrides }, }; } +function replacePhase(index: number, overrides: Record) { + return PHASE_SPANS.map((span, phaseIndex) => + phaseIndex === index ? { ...span, ...overrides } : span, + ); +} + +function completePhaseBudgets(value = 1_500) { + return Object.fromEntries(ONBOARD_PHASE_NAMES.map((name) => [name, value])); +} + describe("onboard performance evidence", () => { - it("reads the successful onboard root span using integer nanosecond timestamps", () => { + it("reads one successful, root-bound onboard trace with consistent timing", () => { expect(readOnboardTraceWindow(traceArtifact())).toEqual({ - durationMs: 3_750, - finishedAtMs: 4_750, + durationMs: 5_000, + finishedAtMs: 6_000, + phaseDurationsMs: { + "nemoclaw.onboard.phase.preflight": 250, + "nemoclaw.onboard.phase.gateway": 500, + "nemoclaw.onboard.phase.provider_selection": 750, + "nemoclaw.onboard.phase.inference": 1_000, + "nemoclaw.onboard.phase.sandbox": 1_250, + }, startedAtMs: 1_000, }); }); it.each([ - ["missing root", { name: "nemoclaw.onboard.phase.gateway" }], - ["failed root", { status: { code: "ERROR" } }], - ["malformed timestamp", { start_time_unix_nano: "yesterday" }], - ["reversed timestamps", { end_time_unix_nano: "999999999" }], - ])("rejects a %s trace", (_label, overrides) => { - expect(() => readOnboardTraceWindow(traceArtifact(overrides))).toThrow(); + ["missing root", { name: "not-onboard" }, {}, "exactly one onboard root"], + ["failed root", { status: { code: "ERROR" } }, {}, "status is missing or not OK"], + ["root parent", { parent_span_id: "0000000000000099" }, {}, "must not have a parent"], + ["malformed timestamp", { start_time_unix_nano: "yesterday" }, {}, "start time"], + [ + "reversed timestamps", + { end_time_unix_nano: timestampNs(ROOT_START_MS - 1) }, + {}, + "ends before it starts", + ], + ["inconsistent duration", { duration_ms: 4_999 }, {}, "does not match its timestamps"], + ["foreign summary", {}, { trace_id: FOREIGN_TRACE_ID }, "exactly one onboard root"], + ])("rejects a %s trace", (_label, rootOverrides, summaryOverrides, message) => { + expect(() => + readOnboardTraceWindow(traceArtifact(rootOverrides, PHASE_SPANS, summaryOverrides)), + ).toThrow(message); + }); + + it("requires every stable onboarding phase exactly once", () => { + expect(() => readOnboardTraceWindow(traceArtifact({}, PHASE_SPANS.slice(0, -1)))).toThrow( + "phase.sandbox", + ); + expect(() => + readOnboardTraceWindow( + traceArtifact({}, [ + ...PHASE_SPANS, + phaseSpan(ONBOARD_PHASE_NAMES[4], "0000000000000007", 5_300, 1), + ]), + ), + ).toThrow("exactly one"); + }); + + it.each([ + ["foreign trace", 0, { trace_id: FOREIGN_TRACE_ID }, "phase.preflight"], + ["wrong parent", 1, { parent_span_id: "0000000000000099" }, "not a child"], + ["failed status", 2, { status: { code: "ERROR" } }, "status is missing or not OK"], + ["malformed span id", 3, { span_id: "short" }, "span_id"], + [ + "out-of-root window", + 4, + { + start_time_unix_nano: timestampNs(5_000), + end_time_unix_nano: timestampNs(6_250), + }, + "outside the onboard root window", + ], + ["inconsistent duration", 4, { duration_ms: 1_249 }, "does not match its timestamps"], + ])("rejects a phase with %s", (_label, index, overrides, message) => { + expect(() => + readOnboardTraceWindow(traceArtifact({}, replacePhase(index as number, overrides))), + ).toThrow(message); + }); + + it("ignores duplicate root and phase names from a different trace", () => { + const foreignRoot = { + trace_id: FOREIGN_TRACE_ID, + span_id: "0000000000000098", + name: "nemoclaw.onboard", + }; + const foreignPhase = { + ...PHASE_SPANS[0], + trace_id: FOREIGN_TRACE_ID, + span_id: "0000000000000099", + }; + + expect( + readOnboardTraceWindow(traceArtifact({}, [...PHASE_SPANS, foreignRoot, foreignPhase])), + ).toEqual(readOnboardTraceWindow(traceArtifact())); + }); + + it("rejects duplicate IDs and overlapping or reordered phases", () => { + expect(() => + readOnboardTraceWindow(traceArtifact({}, replacePhase(0, { span_id: ROOT_SPAN_ID }))), + ).toThrow("duplicate span_id"); + expect(() => + readOnboardTraceWindow( + traceArtifact( + {}, + replacePhase(1, { + start_time_unix_nano: timestampNs(1_200), + end_time_unix_nano: timestampNs(1_700), + }), + ), + ), + ).toThrow("overlaps or precedes"); + }); + + it("evaluates root-boundary and configured phase budgets independently", () => { + const trace = readOnboardTraceWindow(traceArtifact()); + const budget = readColdOnboardPerformanceBudget({ + fullE2eColdPath: { + rootStartToFirstTurnCompletionBudgetMs: 5_000, + rootEndToFirstTurnCompletionBudgetMs: 1_000, + phaseBudgetsMs: completePhaseBudgets(), + }, + }); + + expect(evaluateColdOnboardPerformance(trace, 6_000, budget)).toEqual({ + passed: true, + rootStartToFirstTurnCompletionMs: 5_000, + rootEndToFirstTurnCompletionMs: 0, + violations: [], + }); + expect(evaluateColdOnboardPerformance(trace, 7_500, budget)).toEqual({ + passed: false, + rootStartToFirstTurnCompletionMs: 6_500, + rootEndToFirstTurnCompletionMs: 1_500, + violations: [ + "root-start-to-first-turn-completion 6500ms exceeds 5000ms", + "root-end-to-first-turn-completion 1500ms exceeds 1000ms", + ], + }); + + trace.phaseDurationsMs[ONBOARD_PHASE_NAMES[4]] = 1_501; + expect(evaluateColdOnboardPerformance(trace, 6_000, budget).violations).toEqual([ + "nemoclaw.onboard.phase.sandbox 1501ms exceeds 1500ms", + ]); + }); + + it("rejects malformed or incomplete cold-path budget configuration", () => { + expect(() => readColdOnboardPerformanceBudget({})).toThrow("fullE2eColdPath"); + const fullE2eColdPath = { + rootStartToFirstTurnCompletionBudgetMs: 1_000, + rootEndToFirstTurnCompletionBudgetMs: 1_001, + phaseBudgetsMs: completePhaseBudgets(), + }; + expect(() => readColdOnboardPerformanceBudget({ fullE2eColdPath })).toThrow(); + const { [ONBOARD_PHASE_NAMES[0]]: _, ...incompletePhases } = completePhaseBudgets(); + expect(() => + readColdOnboardPerformanceBudget({ + fullE2eColdPath: { + ...fullE2eColdPath, + rootEndToFirstTurnCompletionBudgetMs: 1_000, + phaseBudgetsMs: incompletePhases, + }, + }), + ).toThrow(); + expect(() => + readColdOnboardPerformanceBudget({ + fullE2eColdPath: { + ...fullE2eColdPath, + rootEndToFirstTurnCompletionBudgetMs: 1_000, + phaseBudgetsMs: { ...completePhaseBudgets(), unknown: 1 }, + }, + }), + ).toThrow(); + expect(() => + readColdOnboardPerformanceBudget({ + fullE2eColdPath: { + ...fullE2eColdPath, + rootEndToFirstTurnCompletionBudgetMs: 1_000, + unexpected: true, + }, + }), + ).toThrow(); + }); + + it("rejects impossible first-turn timing boundaries", () => { + const trace = readOnboardTraceWindow(traceArtifact()); + const budget = readColdOnboardPerformanceBudget({ + fullE2eColdPath: { + rootStartToFirstTurnCompletionBudgetMs: 5_000, + rootEndToFirstTurnCompletionBudgetMs: 1_000, + phaseBudgetsMs: completePhaseBudgets(), + }, + }); + expect(() => evaluateColdOnboardPerformance(trace, trace.finishedAtMs - 1, budget)).toThrow( + "timing boundaries", + ); }); it("measures the largest in-window gap after ordering and filtering output events", () => { diff --git a/test/onboard-performance-config-schema.test.ts b/test/onboard-performance-config-schema.test.ts new file mode 100644 index 00000000000..88f6c5e5497 --- /dev/null +++ b/test/onboard-performance-config-schema.test.ts @@ -0,0 +1,221 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { describe, expect, it } from "vitest"; + +import { compileConfigSchema } from "../scripts/validate-configs"; + +const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), ".."); +const PHASE_NAMES = [ + "nemoclaw.onboard.phase.preflight", + "nemoclaw.onboard.phase.gateway", + "nemoclaw.onboard.phase.provider_selection", + "nemoclaw.onboard.phase.inference", + "nemoclaw.onboard.phase.sandbox", +] as const; +type PhaseName = (typeof PHASE_NAMES)[number]; +type PhaseBudgets = Record; +interface ColdPathBudget { + rootStartToFirstTurnCompletionBudgetMs: number; + rootEndToFirstTurnCompletionBudgetMs: number; + phaseBudgetsMs: PhaseBudgets; +} +interface CalibrationSample { + runId: number; + runUrl: string; + headSha: string; + conclusion: string; + installExitCode: number; + firstTurnExitCode: number; + performancePassed: boolean; + usedBuildKitPrebuild: boolean; + buildKitFallback: boolean; + maxSilenceSecs: number; + responseChars: number; + measurementsMs: { + onboardRoot: number; + rootStartToFirstTurnCompletion: number; + rootEndToInstallCompletion: number; + firstTurnCommand: number; + rootEndToFirstTurnCompletion: number; + phases: PhaseBudgets; + }; +} +interface Calibration { + schemaVersion: number; + baselineMainSha: string; + measurementHeadSha: string; + derivation: { + percentile: number; + percentileMethod: string; + minimumHeadroomMs: number; + relativeHeadroomPercent: number; + roundUpMs: number; + }; + samples: CalibrationSample[]; + derivedBudgetsMs: ColdPathBudget; +} + +const checkedInConfig = JSON.parse( + readFileSync(join(REPO_ROOT, "ci", "onboard-performance-budget.json"), "utf8"), +) as { fullE2eColdPath: ColdPathBudget }; +const calibration = JSON.parse( + readFileSync(join(REPO_ROOT, "ci", "full-e2e-cold-path-calibration.json"), "utf8"), +) as Calibration; + +const validate = compileConfigSchema("schemas/onboard-config.schema.json"); +const phaseBudgetsMs = Object.fromEntries(PHASE_NAMES.map((name) => [name, 1_000])); +const validConfig = { + $comment: "Schema fixture", + schemaVersion: 1, + mode: "advisory", + scope: "fixture", + totalBudgetMs: 1_000, + regressionWarning: { minDeltaMs: 0, minPercent: 0 }, + phaseRegressionWarning: { minDeltaMs: 0, minPercent: 0 }, + fullE2eColdPath: { + rootStartToFirstTurnCompletionBudgetMs: 5_000, + rootEndToFirstTurnCompletionBudgetMs: 1_000, + phaseBudgetsMs, + }, +}; + +describe("onboard performance config schema", () => { + it("accepts a complete synthetic config", () => { + expect(validate(validConfig), JSON.stringify(validate.errors)).toBe(true); + }); + + it("requires the cold-path config at the root", () => { + const { fullE2eColdPath: _, ...withoutColdPath } = validConfig; + expect(validate(withoutColdPath)).toBe(false); + }); + + it("enforces the root-end budget against the root-start budget", () => { + expect( + validate({ + ...validConfig, + fullE2eColdPath: { + ...validConfig.fullE2eColdPath, + rootEndToFirstTurnCompletionBudgetMs: 5_001, + }, + }), + ).toBe(false); + }); + + it.each(PHASE_NAMES)("requires the %s budget", (phaseName) => { + const incompletePhases = { ...phaseBudgetsMs }; + delete incompletePhases[phaseName]; + expect( + validate({ + ...validConfig, + fullE2eColdPath: { ...validConfig.fullE2eColdPath, phaseBudgetsMs: incompletePhases }, + }), + ).toBe(false); + }); + + it("rejects unknown, negative, and non-schema threshold values", () => { + expect( + validate({ + ...validConfig, + fullE2eColdPath: { + ...validConfig.fullE2eColdPath, + phaseBudgetsMs: { ...phaseBudgetsMs, "nemoclaw.onboard.phase.typo": 1 }, + }, + }), + ).toBe(false); + expect( + validate({ + ...validConfig, + fullE2eColdPath: { + ...validConfig.fullE2eColdPath, + rootStartToFirstTurnCompletionBudgetMs: -1, + }, + }), + ).toBe(false); + expect( + validate({ + ...validConfig, + regressionWarning: { minDeltaMs: -1, minPercent: 20 }, + }), + ).toBe(false); + }); +}); + +function derivedThreshold(values: number[], derivation: Calibration["derivation"]): number { + const sorted = [...values].sort((left, right) => left - right); + const rank = Math.max(1, Math.ceil((derivation.percentile / 100) * sorted.length)); + const percentileValue = sorted[rank - 1]; + const headroom = Math.max( + derivation.minimumHeadroomMs, + percentileValue * (derivation.relativeHeadroomPercent / 100), + ); + return Math.ceil((percentileValue + headroom) / derivation.roundUpMs) * derivation.roundUpMs; +} + +function deriveBudgets(input: Calibration): ColdPathBudget { + const threshold = (values: number[]) => derivedThreshold(values, input.derivation); + const phaseBudgets = {} as PhaseBudgets; + for (const phaseName of PHASE_NAMES) { + phaseBudgets[phaseName] = threshold( + input.samples.map((sample) => sample.measurementsMs.phases[phaseName]), + ); + } + return { + rootStartToFirstTurnCompletionBudgetMs: threshold( + input.samples.map((sample) => sample.measurementsMs.rootStartToFirstTurnCompletion), + ), + rootEndToFirstTurnCompletionBudgetMs: threshold( + input.samples.map((sample) => sample.measurementsMs.rootEndToFirstTurnCompletion), + ), + phaseBudgetsMs: phaseBudgets, + }; +} + +describe("full-E2E cold-path calibration", () => { + // source-shape-contract: compatibility -- Exact-head provenance is durable evidence for the hosted-run budget calibration + it("records five independent successful exact-head samples", () => { + expect(calibration.schemaVersion).toBe(1); + expect(calibration.baselineMainSha).toMatch(/^[0-9a-f]{40}$/u); + expect(calibration.measurementHeadSha).toMatch(/^[0-9a-f]{40}$/u); + expect(calibration.derivation.percentileMethod).toBe("nearest-rank"); + expect(calibration.samples).toHaveLength(5); + expect(new Set(calibration.samples.map((sample) => sample.runId)).size).toBe(5); + + for (const sample of calibration.samples) { + expect(sample.runUrl).toBe(`https://github.com/NVIDIA/NemoClaw/actions/runs/${sample.runId}`); + expect(sample.headSha).toBe(calibration.measurementHeadSha); + expect(sample).toMatchObject({ + conclusion: "success", + installExitCode: 0, + firstTurnExitCode: 0, + performancePassed: true, + usedBuildKitPrebuild: true, + buildKitFallback: false, + }); + expect(sample.maxSilenceSecs).toBeLessThanOrEqual(60); + expect(sample.responseChars).toBeGreaterThan(0); + expect(Object.keys(sample.measurementsMs.phases).sort()).toEqual([...PHASE_NAMES].sort()); + for (const value of [ + sample.measurementsMs.onboardRoot, + sample.measurementsMs.rootStartToFirstTurnCompletion, + sample.measurementsMs.rootEndToInstallCompletion, + sample.measurementsMs.firstTurnCommand, + sample.measurementsMs.rootEndToFirstTurnCompletion, + ...Object.values(sample.measurementsMs.phases), + ]) { + expect(Number.isFinite(value) && value >= 0).toBe(true); + } + } + }); + + // source-shape-contract: compatibility -- Recomputed thresholds keep enforced budgets tied to the reviewed calibration evidence + it("keeps configured budgets derived from the checked-in samples", () => { + const derived = deriveBudgets(calibration); + expect(calibration.derivedBudgetsMs).toEqual(derived); + expect(checkedInConfig.fullE2eColdPath).toEqual(derived); + }); +}); diff --git a/test/validate-config-schemas.test.ts b/test/validate-config-schemas.test.ts index 577cf7901bf..98c2f458254 100644 --- a/test/validate-config-schemas.test.ts +++ b/test/validate-config-schemas.test.ts @@ -59,7 +59,7 @@ function loadJSON(path: string): LooseObject { } function compileSchema(schemaRelPath: string): ValidateFunction { - const ajv = new Ajv({ allErrors: true, strict: false }); + const ajv = new Ajv({ allErrors: true, strict: false, $data: true }); const schema = loadJSON(repoPath(schemaRelPath)); return ajv.compile(schema); } @@ -279,33 +279,6 @@ describe("config validation target discovery", () => { }); }); -// ── Onboard performance budget ────────────────────────────────────────────── - -describe("onboard-config.schema.json", () => { - const validate = compileSchema("schemas/onboard-config.schema.json"); - const validOnboardConfig = { - $comment: "Schema fixture", - schemaVersion: 1, - mode: "advisory", - scope: "fixture", - totalBudgetMs: 0, - regressionWarning: { minDeltaMs: 0, minPercent: 0 }, - phaseRegressionWarning: { minDeltaMs: 0, minPercent: 0 }, - }; - - it("accepts a minimal onboard performance budget", () => { - expectValid(validate, validOnboardConfig, "minimal onboard config"); - }); - - it("rejects invalid threshold shapes", () => { - const bad = { - ...validOnboardConfig, - regressionWarning: { minDeltaMs: -1, minPercent: 20 }, - }; - expect(validate(bad)).toBe(false); - }); -}); - // ── Blueprint ──────────────────────────────────────────────────────────────── describe("blueprint.schema.json", () => {