@testsprite/testsprite-cli 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -30
- package/dist/commands/agent.js +44 -42
- package/dist/commands/doctor.d.ts +1 -1
- package/dist/commands/doctor.js +4 -7
- package/dist/commands/project.js +3 -2
- package/dist/commands/schedule.d.ts +120 -0
- package/dist/commands/schedule.js +487 -0
- package/dist/commands/test.d.ts +15 -1
- package/dist/commands/test.js +460 -256
- package/dist/commands/testlist.d.ts +88 -0
- package/dist/commands/testlist.js +747 -0
- package/dist/index.js +6 -2
- package/dist/lib/agent-targets.d.ts +13 -4
- package/dist/lib/agent-targets.js +11 -2
- package/dist/lib/conflict-reason.d.ts +30 -0
- package/dist/lib/conflict-reason.js +45 -0
- package/dist/lib/credentials.js +42 -1
- package/dist/lib/cron.d.ts +40 -0
- package/dist/lib/cron.js +190 -0
- package/dist/lib/dry-run/samples.js +177 -55
- package/dist/lib/errors.d.ts +9 -0
- package/dist/lib/errors.js +11 -0
- package/dist/lib/gh-output.d.ts +26 -1
- package/dist/lib/gh-output.js +47 -20
- package/dist/lib/http.d.ts +25 -0
- package/dist/lib/http.js +128 -2
- package/dist/lib/junit-report.d.ts +20 -2
- package/dist/lib/junit-report.js +38 -5
- package/dist/lib/proxy.d.ts +16 -0
- package/dist/lib/proxy.js +19 -1
- package/dist/lib/response-schemas.d.ts +7 -0
- package/dist/lib/response-schemas.js +23 -1
- package/dist/lib/runs.types.d.ts +8 -3
- package/dist/lib/secret-file.d.ts +15 -0
- package/dist/lib/secret-file.js +82 -0
- package/dist/lib/target-url-preflight.d.ts +91 -0
- package/dist/lib/target-url-preflight.js +259 -0
- package/dist/lib/target-url.d.ts +22 -5
- package/dist/lib/target-url.js +60 -28
- package/dist/lib/testlist.types.d.ts +77 -0
- package/dist/lib/testlist.types.js +9 -0
- package/dist/lib/v3-advisory.d.ts +35 -22
- package/dist/lib/v3-advisory.js +44 -24
- package/dist/lib/wait-exit.d.ts +29 -0
- package/dist/lib/wait-exit.js +103 -0
- package/dist/version-guard.d.ts +10 -7
- package/dist/version-guard.js +37 -9
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/commands/test.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createWriteStream, existsSync, readFileSync, readdirSync, statSync, } from 'node:fs';
|
|
2
2
|
import { rename, stat, unlink } from 'node:fs/promises';
|
|
3
3
|
import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
|
|
4
4
|
import { randomUUID } from 'node:crypto';
|
|
@@ -7,8 +7,8 @@ import { openInBrowser } from '../lib/browser.js';
|
|
|
7
7
|
import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
|
|
8
8
|
import { assertContextIntegrity, buildMeta, pickCodeExtension, pickVideoExtension, resolveBundleDir, stepFilenamePrefix, writeBundle, } from '../lib/bundle.js';
|
|
9
9
|
import { findSample, sampleJUnitReportXml } from '../lib/dry-run/samples.js';
|
|
10
|
-
import { assertJUnitReportOptions, buildJUnitReport, resolveBatchReportProjectId, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
|
|
11
|
-
import { ApiError, CLIError, InterruptError, RequestTimeoutError, TransportError, localValidationError, } from '../lib/errors.js';
|
|
10
|
+
import { assertJUnitReportOptions, buildJUnitReport, durationSecondsBetween, resolveBatchReportProjectId, writeJUnitReportFile, parseJUnitReportFormat, } from '../lib/junit-report.js';
|
|
11
|
+
import { ApiError, CLIError, InterruptError, RequestTimeoutError, TransportError, isAuthCode, localValidationError, } from '../lib/errors.js';
|
|
12
12
|
import { globalShutdown } from '../lib/interrupt.js';
|
|
13
13
|
import { assertIdempotencyKey, requireArrayLength, requireEnum, requireString, } from '../lib/validate.js';
|
|
14
14
|
import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS } from '../lib/http.js';
|
|
@@ -16,14 +16,18 @@ import { VERSION } from '../version.js';
|
|
|
16
16
|
import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
|
|
17
17
|
import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
|
|
18
18
|
import { pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
|
|
19
|
+
import { resolveWaitFailure } from '../lib/wait-exit.js';
|
|
19
20
|
import { RUN_SOURCES } from '../lib/runs.types.js';
|
|
21
|
+
import { summarizeConflicts } from '../lib/conflict-reason.js';
|
|
22
|
+
import { isProxyAgentActive } from '../lib/proxy.js';
|
|
20
23
|
import { assertNotLocal } from '../lib/target-url.js';
|
|
24
|
+
import { assertTargetUrlReachable } from '../lib/target-url-preflight.js';
|
|
21
25
|
import { formatTextTableRow, measureTextColumns, renderTextTable, resolveTextColumns, } from '../lib/text-table.js';
|
|
22
26
|
import { createTicker } from '../lib/ticker.js';
|
|
23
27
|
import { RateThrottle } from '../lib/rate-throttle.js';
|
|
24
28
|
import { resolvePortalBase, resolvePortalUrl } from '../lib/facade.js';
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
29
|
+
import { emitTargetUrlMismatchAdvisory } from '../lib/v3-advisory.js';
|
|
30
|
+
import { emitCiArtifacts, summarizeAcceptedPayload, summarizeSingleRun } from '../lib/gh-output.js';
|
|
27
31
|
import { loadConfig } from '../lib/config.js';
|
|
28
32
|
import { flakyExitCode, renderFlakyText, summarizeFlaky, } from '../lib/flaky.js';
|
|
29
33
|
/** The effective shutdown handle for a command invocation (DEV-331). */
|
|
@@ -65,6 +69,25 @@ function rateLimitedDetachMessage(err, runIds) {
|
|
|
65
69
|
` Re-attach with: testsprite test wait ${runIds.join(' ')}\n` +
|
|
66
70
|
` Cancel with: testsprite test cancel ${runIds.join(' ')}`);
|
|
67
71
|
}
|
|
72
|
+
/**
|
|
73
|
+
* The same honest "keeps running (and billing)" subject sentence
|
|
74
|
+
* `interruptDetachMessage`/`rateLimitedDetachMessage` already use, for the
|
|
75
|
+
* two detach paths that build their own text inline instead of going
|
|
76
|
+
* through one of those two helpers: a plain `--timeout` expiry
|
|
77
|
+
* (`TimeoutError`) and a client-side `RequestTimeoutError`. Both used to
|
|
78
|
+
* omit "(and billing)" — the honesty gap this closes — even though a
|
|
79
|
+
* `--timeout` expiry is the single most common of the four detach reasons
|
|
80
|
+
* in practice. Kept as a standalone string helper (not a shared code path
|
|
81
|
+
* for all four branches) deliberately: the four branches differ in how
|
|
82
|
+
* they render the partial envelope and in their exit code, and unifying
|
|
83
|
+
* that shape is out of scope here — see the PR notes.
|
|
84
|
+
*/
|
|
85
|
+
function stillRunningAndBillingSubject(runIds) {
|
|
86
|
+
const ids = Array.isArray(runIds) ? runIds : [runIds];
|
|
87
|
+
return ids.length === 1
|
|
88
|
+
? `Run ${ids[0]} is still executing on the server and will keep running (and billing) until it finishes.`
|
|
89
|
+
: `${ids.length} runs are still executing on the server and will keep running (and billing) until they finish.`;
|
|
90
|
+
}
|
|
68
91
|
const TEST_TYPES = ['frontend', 'backend'];
|
|
69
92
|
// 'cli' added 2026-06-04 (dogfood): backend now stamps createFrom='cli' on
|
|
70
93
|
// tests created via `testsprite test create`, so the `--created-from cli`
|
|
@@ -369,6 +392,23 @@ export async function runCreate(opts, deps = {}) {
|
|
|
369
392
|
const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
|
|
370
393
|
stderrFn("[advisory] --target-url has no effect for backend tests (a backend test's base URL is defined inside its code).");
|
|
371
394
|
}
|
|
395
|
+
// Pre-charge reachability preflight — deliberately BEFORE the
|
|
396
|
+
// create POST below (not after), so a doomed --target-url refuses before
|
|
397
|
+
// this leaves behind a created-but-never-run orphan test row (the same
|
|
398
|
+
// "fail before I/O" idiom `assertChainedRunKeyFits` above already applies
|
|
399
|
+
// to the run idempotency key). Only meaningful when it will actually
|
|
400
|
+
// reach a trigger: skipped for a known-backend test (the advisory just
|
|
401
|
+
// above already covers why --target-url is inert there) and skipped
|
|
402
|
+
// entirely under --dry-run (zero network calls). The delegated
|
|
403
|
+
// `runTestRun` call in the --run chain below sets `skipPreflight: true`
|
|
404
|
+
// so this exact URL is never probed twice.
|
|
405
|
+
if (opts.type !== 'backend' &&
|
|
406
|
+
opts.targetUrl !== undefined &&
|
|
407
|
+
opts.run === true &&
|
|
408
|
+
!opts.dryRun) {
|
|
409
|
+
const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
|
|
410
|
+
await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
|
|
411
|
+
}
|
|
372
412
|
const client = makeClient(opts, deps);
|
|
373
413
|
const out = makeOutput(opts.output, deps);
|
|
374
414
|
// B3: best-effort duplicate-name advisory. Skip under --dry-run.
|
|
@@ -434,6 +474,10 @@ export async function runCreate(opts, deps = {}) {
|
|
|
434
474
|
// Thread the known type so fast BE runs (terminal on first poll, where
|
|
435
475
|
// beFallbackUsed would be false) still render `steps: n/a (backend)`.
|
|
436
476
|
type: opts.type,
|
|
477
|
+
// The preflight above (or its explicit --skip-preflight opt-out)
|
|
478
|
+
// already ran against this exact URL before the create POST — never
|
|
479
|
+
// probe it a second time here.
|
|
480
|
+
skipPreflight: true,
|
|
437
481
|
}, deps);
|
|
438
482
|
return response;
|
|
439
483
|
}
|
|
@@ -1520,6 +1564,15 @@ export async function runCreateFromPlan(opts, deps = {}) {
|
|
|
1520
1564
|
priority: plan.priority,
|
|
1521
1565
|
planSteps: plan.planSteps,
|
|
1522
1566
|
};
|
|
1567
|
+
// Pre-charge reachability preflight — before the create POST
|
|
1568
|
+
// (same "fail before I/O, not after an orphan row" placement as
|
|
1569
|
+
// runCreate). `plan.type` is unconditionally 'frontend' here (backend
|
|
1570
|
+
// plans already threw above), so no type gate is needed. The delegated
|
|
1571
|
+
// `runTestRun` call in the --run chain below sets `skipPreflight: true`
|
|
1572
|
+
// so this exact URL is never probed twice.
|
|
1573
|
+
if (opts.targetUrl !== undefined && opts.run === true && !opts.dryRun) {
|
|
1574
|
+
await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
|
|
1575
|
+
}
|
|
1523
1576
|
const client = makeClient(opts, deps);
|
|
1524
1577
|
const out = makeOutput(opts.output, deps);
|
|
1525
1578
|
// Fix 4: best-effort duplicate-name advisory — same semantics as runCreate.
|
|
@@ -1563,6 +1616,9 @@ export async function runCreateFromPlan(opts, deps = {}) {
|
|
|
1563
1616
|
timeoutIsDefault: opts.timeoutIsDefault ?? false,
|
|
1564
1617
|
wait: opts.wait === true,
|
|
1565
1618
|
createContext: responseWithDashboardUrl,
|
|
1619
|
+
// Already preflighted above (or explicitly skipped) — don't probe
|
|
1620
|
+
// the same URL twice.
|
|
1621
|
+
skipPreflight: true,
|
|
1566
1622
|
}, deps).then(() => response);
|
|
1567
1623
|
}
|
|
1568
1624
|
if (opts.output === 'json') {
|
|
@@ -2080,20 +2136,6 @@ testIdToDashboardState) {
|
|
|
2080
2136
|
// All specs failed at create time — already threw above; unreachable.
|
|
2081
2137
|
return;
|
|
2082
2138
|
}
|
|
2083
|
-
// Finding 2 (dogfood 2026-08-09): this fan-out calls `triggerRunWithMeta`
|
|
2084
|
-
// directly (below), bypassing `runTestRun` entirely — so `runTestRun`'s own
|
|
2085
|
-
// `--target-url` V3 advisory (`emitTargetUrlV3AdvisoryIfNeeded`) never fired
|
|
2086
|
-
// here, even though every triggered run in the batch ignores `--target-url`
|
|
2087
|
-
// exactly like a single V3-routed `test run` does. Reuses the same helper
|
|
2088
|
-
// and advisory text (no duplicated probe logic or copy) and fires exactly
|
|
2089
|
-
// ONCE for the whole batch, before the fan-out — not per item. Mirrors
|
|
2090
|
-
// `runTestRun`'s own gating (only pay the extra `/me` round trip when
|
|
2091
|
-
// `--target-url` was actually supplied) and its "fires under --dry-run too"
|
|
2092
|
-
// behavior (the dry-run client's canned `/me` sample demonstrates the same
|
|
2093
|
-
// advisory at zero real-network cost).
|
|
2094
|
-
if (opts.targetUrl !== undefined) {
|
|
2095
|
-
await emitTargetUrlV3AdvisoryIfNeeded(client, stderrFn);
|
|
2096
|
-
}
|
|
2097
2139
|
// Dry-run: print a descriptor envelope and return without real triggers.
|
|
2098
2140
|
if (opts.dryRun) {
|
|
2099
2141
|
const dryRunResults = testIds.map(testId => ({
|
|
@@ -2116,8 +2158,25 @@ testIdToDashboardState) {
|
|
|
2116
2158
|
out.print(envelope);
|
|
2117
2159
|
return;
|
|
2118
2160
|
}
|
|
2161
|
+
// Pre-charge reachability preflight, ONCE for the whole batch
|
|
2162
|
+
// before the fan-out — not once per item (mirrors the "fire once per
|
|
2163
|
+
// invocation" contract Finding 2 already established for the target-url
|
|
2164
|
+
// advisory below). Real path only (dry-run already returned above); no
|
|
2165
|
+
// type gate is needed here — batch specs are FE-only by construction (a
|
|
2166
|
+
// `type: "backend"` spec always fails create-time server validation, so
|
|
2167
|
+
// it never reaches this fan-out at all — see the `beIndexes` warning in
|
|
2168
|
+
// `runCreateBatch`).
|
|
2169
|
+
if (opts.targetUrl !== undefined) {
|
|
2170
|
+
await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
|
|
2171
|
+
}
|
|
2119
2172
|
const batchRunResults = [];
|
|
2120
2173
|
const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
|
|
2174
|
+
// Response-driven --target-url advisory, fired at most ONCE for the whole
|
|
2175
|
+
// batch (Finding 2's contract) the first time any member's trigger
|
|
2176
|
+
// response reports a target different from what was requested — see the
|
|
2177
|
+
// matching comment in `runTestRun` for why this replaced the old
|
|
2178
|
+
// `v3Enabled`-assumption probe.
|
|
2179
|
+
let targetUrlAdvisoryPrinted = false;
|
|
2121
2180
|
/**
|
|
2122
2181
|
* Client-side sliding-window throttle: caps outgoing triggers at
|
|
2123
2182
|
* BATCH_RUN_RATE_LIMIT (50) per BATCH_RUN_RATE_WINDOW_MS (60 s), sitting
|
|
@@ -2222,6 +2281,16 @@ testIdToDashboardState) {
|
|
|
2222
2281
|
// POSTs per spec (e.g. 50×3 = 150/min), blowing the server's 60/min cap.
|
|
2223
2282
|
{ idempotencyKey: runIdempotencyKey, retryOnRateLimit: false });
|
|
2224
2283
|
triggerResponse = result.body;
|
|
2284
|
+
// Fire the response-driven mismatch advisory at most once for the
|
|
2285
|
+
// whole batch. Synchronous check-and-set (no `await` between the
|
|
2286
|
+
// two) so two members whose triggers resolve in the same tick
|
|
2287
|
+
// can't both slip past the flag and print twice.
|
|
2288
|
+
if (!targetUrlAdvisoryPrinted &&
|
|
2289
|
+
opts.targetUrl !== undefined &&
|
|
2290
|
+
triggerResponse.targetUrl !== opts.targetUrl) {
|
|
2291
|
+
targetUrlAdvisoryPrinted = true;
|
|
2292
|
+
emitTargetUrlMismatchAdvisory(stderrFn, opts.targetUrl, triggerResponse.targetUrl);
|
|
2293
|
+
}
|
|
2225
2294
|
break; // success — exit the outer retry loop
|
|
2226
2295
|
}
|
|
2227
2296
|
catch (err) {
|
|
@@ -4378,78 +4447,6 @@ function parseTimeoutFlag(raw, flagName) {
|
|
|
4378
4447
|
}
|
|
4379
4448
|
return n;
|
|
4380
4449
|
}
|
|
4381
|
-
/**
|
|
4382
|
-
* Short deadline for the best-effort `v3Enabled` lookup behind the
|
|
4383
|
-
* `--target-url` advisory (DEV-749). Mirrors `DUP_NAME_ADVISORY_TIMEOUT_MS`
|
|
4384
|
-
* — a stalled `/me` must never meaningfully delay a run trigger.
|
|
4385
|
-
*/
|
|
4386
|
-
const TARGET_URL_ADVISORY_TIMEOUT_MS = 5_000;
|
|
4387
|
-
/**
|
|
4388
|
-
* DEV-749 (client half): `--target-url` is silently dropped on the V3
|
|
4389
|
-
* execution path — the backend validates it (SSRF guard, defence in depth)
|
|
4390
|
-
* and then discards it, because V3 resolves the run's environment from
|
|
4391
|
-
* `test_environment` at execution time; there is no injection point for a
|
|
4392
|
-
* per-run override. This is a client-side advisory only — the real fix
|
|
4393
|
-
* (an actual per-run override on V3) needs a product decision and is out
|
|
4394
|
-
* of scope here.
|
|
4395
|
-
*
|
|
4396
|
-
* Gated on `v3Enabled`, the same authoritative per-user routing bit
|
|
4397
|
-
* `auth status`/`doctor` already render (`GET /me`, `src/lib/v3-advisory.ts`).
|
|
4398
|
-
* Best-effort: a single bounded lookup (mirrors `emitDupNameAdvisoryIfNeeded`'s
|
|
4399
|
-
* `AbortController` + 5 s deadline), swallows every error, and must never
|
|
4400
|
-
* block or fail the actual run trigger — a broken/slow `/me` degrades to
|
|
4401
|
-
* "no advisory printed", not a failed `test run`.
|
|
4402
|
-
*/
|
|
4403
|
-
/**
|
|
4404
|
-
* `X-CLI-Command` tag for this probe's `GET /me` — same advisory-header
|
|
4405
|
-
* mechanism `runInit` uses (`toAuthDeps`'s `commandTag: 'init'` in
|
|
4406
|
-
* `commands/init.ts`, sent via `AuthDeps.commandTag` in `auth.ts`), reused
|
|
4407
|
-
* directly here rather than invented fresh. The backend's CLI-audit
|
|
4408
|
-
* allowlist (`KNOWN_CLI_COMMANDS` + `resolveCliEvent`'s `/me` branch) maps this
|
|
4409
|
-
* exact string to `null` — no PostHog event at all, not `cli.session_started`
|
|
4410
|
-
* and not `cli.initialized` (init's tag would be a MORE specific, and equally
|
|
4411
|
-
* wrong, misattribution of a probe that is neither a session start nor an
|
|
4412
|
-
* onboarding run).
|
|
4413
|
-
*
|
|
4414
|
-
* Forward-compatible by construction: an unlisted `X-CLI-Command` value is
|
|
4415
|
-
* dropped by the backend before event selection (see
|
|
4416
|
-
* `capturePostHogEvent`/`KNOWN_CLI_COMMANDS` in the interceptor above), so
|
|
4417
|
-
* against a backend that predates this allowlist entry the header is a no-op
|
|
4418
|
-
* and behavior is exactly what it was before this fix — the CLI can ship
|
|
4419
|
-
* this independently of backend deploy order in either direction.
|
|
4420
|
-
*/
|
|
4421
|
-
const TARGET_URL_ADVISORY_CLI_COMMAND = 'run-target-url-probe';
|
|
4422
|
-
async function emitTargetUrlV3AdvisoryIfNeeded(client, stderrFn) {
|
|
4423
|
-
const ac = new AbortController();
|
|
4424
|
-
const timer = setTimeout(() => ac.abort(), TARGET_URL_ADVISORY_TIMEOUT_MS);
|
|
4425
|
-
try {
|
|
4426
|
-
const me = await client.get('/me', {
|
|
4427
|
-
signal: ac.signal,
|
|
4428
|
-
headers: { 'x-cli-command': TARGET_URL_ADVISORY_CLI_COMMAND },
|
|
4429
|
-
// Finding 1 (dogfood 2026-08-09): `HttpClient.sleepBeforeRetry` (src/lib/http.ts)
|
|
4430
|
-
// only observes the process-lifetime shutdown signal, never a per-request
|
|
4431
|
-
// `options.signal` — the abort controller above bounds the FETCH itself but
|
|
4432
|
-
// not a post-response retry sleep. A retryable 429 carrying a real
|
|
4433
|
-
// `Retry-After` (e.g. 60s, a live `inflight_cap` response) would put this
|
|
4434
|
-
// best-effort probe into a retry sleep this 5s deadline cannot interrupt,
|
|
4435
|
-
// stalling the real run trigger behind it. `retryOnRateLimit: false` makes
|
|
4436
|
-
// the HTTP layer throw on the first 429 instead of sleeping — the existing,
|
|
4437
|
-
// already-used-elsewhere knob (see the batch-run trigger site above) rather
|
|
4438
|
-
// than changing `sleepBeforeRetry` itself, which every other caller (e.g.
|
|
4439
|
-
// the polling path) relies on to keep sleeping through a caller signal.
|
|
4440
|
-
retryOnRateLimit: false,
|
|
4441
|
-
});
|
|
4442
|
-
if (me.v3Enabled === true) {
|
|
4443
|
-
emitTargetUrlV3Advisory(stderrFn);
|
|
4444
|
-
}
|
|
4445
|
-
}
|
|
4446
|
-
catch {
|
|
4447
|
-
// Swallow — this is best-effort; must not block or fail the run trigger.
|
|
4448
|
-
}
|
|
4449
|
-
finally {
|
|
4450
|
-
clearTimeout(timer);
|
|
4451
|
-
}
|
|
4452
|
-
}
|
|
4453
4450
|
/**
|
|
4454
4451
|
* `test run <test-id>` — M3.3 piece-3.
|
|
4455
4452
|
*
|
|
@@ -4463,15 +4460,6 @@ export async function runTestRun(opts, deps = {}) {
|
|
|
4463
4460
|
if (opts.targetUrl !== undefined) {
|
|
4464
4461
|
assertNotLocal(opts.targetUrl);
|
|
4465
4462
|
}
|
|
4466
|
-
// DEV-749: only spend the extra `/me` round trip when --target-url was
|
|
4467
|
-
// actually supplied — the common case (no override) pays nothing. Fires
|
|
4468
|
-
// in both the dry-run and real paths below (the dry-run `/me` sample sets
|
|
4469
|
-
// `v3Enabled: true`, so `--dry-run --target-url` demonstrates the same
|
|
4470
|
-
// advisory a real V3-routed caller would see, at zero real-network cost).
|
|
4471
|
-
if (opts.targetUrl !== undefined) {
|
|
4472
|
-
const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
|
|
4473
|
-
await emitTargetUrlV3AdvisoryIfNeeded(makeClient(opts, deps), stderrFn);
|
|
4474
|
-
}
|
|
4475
4463
|
if (opts.dryRun) {
|
|
4476
4464
|
const client = makeClient(opts, deps);
|
|
4477
4465
|
const out = makeOutput(opts.output, deps);
|
|
@@ -4513,6 +4501,16 @@ export async function runTestRun(opts, deps = {}) {
|
|
|
4513
4501
|
const client = makeClient({ ...opts, requestTimeoutMs: resolveWaitRequestTimeoutMs(opts) }, deps);
|
|
4514
4502
|
const out = makeOutput(opts.output, deps);
|
|
4515
4503
|
const stderrFn = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
|
|
4504
|
+
// Pre-charge reachability preflight — real path only (dry-run
|
|
4505
|
+
// makes zero network calls by convention), after `assertNotLocal` and
|
|
4506
|
+
// before the trigger POST so a doomed run never gets a run row or charge.
|
|
4507
|
+
// `opts.skipPreflight` is threaded straight to a zero-network no-op; a
|
|
4508
|
+
// delegating caller (`runCreate`/`runCreateFromPlan` chaining `--run`)
|
|
4509
|
+
// already ran this exact check against the same URL before its own
|
|
4510
|
+
// create POST and sets `skipPreflight: true` here to avoid probing twice.
|
|
4511
|
+
if (opts.targetUrl !== undefined) {
|
|
4512
|
+
await assertTargetUrlReachable(opts.targetUrl, { skipPreflight: opts.skipPreflight }, { fetchImpl: deps.fetchImpl, proxyActive: isProxyAgentActive() }, stderrFn);
|
|
4513
|
+
}
|
|
4516
4514
|
let triggerResponse;
|
|
4517
4515
|
let triggerRequestId;
|
|
4518
4516
|
let resumedFromConflict = false;
|
|
@@ -4619,6 +4617,25 @@ export async function runTestRun(opts, deps = {}) {
|
|
|
4619
4617
|
throw err;
|
|
4620
4618
|
}
|
|
4621
4619
|
}
|
|
4620
|
+
// Response-driven, not assumption-driven: the backend is the ground
|
|
4621
|
+
// truth for whether --target-url was actually applied — V3
|
|
4622
|
+
// deliberately returns `targetUrl: ''` rather than echoing an override it
|
|
4623
|
+
// did not apply ("so the response doesn't claim a target we didn't use"),
|
|
4624
|
+
// while V2 echoes the real applied value. Comparing what we asked for
|
|
4625
|
+
// against what the trigger response reports self-corrects the day the
|
|
4626
|
+
// backend applies the override, with no `v3Enabled` assumption at all.
|
|
4627
|
+
// Skipped for a known-backend caller (`opts.type` threaded from the
|
|
4628
|
+
// `test create --run` chain): a backend trigger response's `targetUrl`
|
|
4629
|
+
// is an unconditional echo of the request body (verified against
|
|
4630
|
+
// backend-v2.0's `CliTestsController.createRun` — `targetUrl: body.targetUrl
|
|
4631
|
+
// ?? ''` on both the V2 and V3 backend branches), so it can never mismatch
|
|
4632
|
+
// and the existing, more specific C1 advisory ("--target-url has no effect
|
|
4633
|
+
// for backend tests") already covers this case at create time.
|
|
4634
|
+
if (opts.targetUrl !== undefined &&
|
|
4635
|
+
opts.type !== 'backend' &&
|
|
4636
|
+
triggerResponse.targetUrl !== opts.targetUrl) {
|
|
4637
|
+
emitTargetUrlMismatchAdvisory(stderrFn, opts.targetUrl, triggerResponse.targetUrl);
|
|
4638
|
+
}
|
|
4622
4639
|
if (!opts.wait) {
|
|
4623
4640
|
printRunOrChain(out, triggerResponse, opts.createContext, data => renderTriggerRunText(data));
|
|
4624
4641
|
if (triggerRequestId && (opts.output === 'json' || opts.verbose || opts.debug))
|
|
@@ -4692,7 +4709,8 @@ export async function runTestRun(opts, deps = {}) {
|
|
|
4692
4709
|
throw ApiError.fromEnvelope({
|
|
4693
4710
|
error: {
|
|
4694
4711
|
code: 'UNSUPPORTED', // exit 7 per errors.md
|
|
4695
|
-
message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}
|
|
4712
|
+
message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${triggerResponse.runId}. ` +
|
|
4713
|
+
stillRunningAndBillingSubject(triggerResponse.runId),
|
|
4696
4714
|
nextAction: `Resume polling: testsprite test wait ${triggerResponse.runId}, or cancel it: testsprite test cancel ${triggerResponse.runId}`,
|
|
4697
4715
|
requestId: 'local',
|
|
4698
4716
|
details: { runId: triggerResponse.runId, timeoutSeconds: opts.timeoutSeconds },
|
|
@@ -4724,7 +4742,7 @@ export async function runTestRun(opts, deps = {}) {
|
|
|
4724
4742
|
lines.push(`hint Cancel with: testsprite test cancel ${p.runId}`);
|
|
4725
4743
|
return lines.join('\n');
|
|
4726
4744
|
});
|
|
4727
|
-
stderrFn(`
|
|
4745
|
+
stderrFn(`Request timed out. ${stillRunningAndBillingSubject(triggerResponse.runId)} ` +
|
|
4728
4746
|
`Re-attach with: testsprite test wait ${triggerResponse.runId}, or cancel with: testsprite test cancel ${triggerResponse.runId}`);
|
|
4729
4747
|
throw err;
|
|
4730
4748
|
}
|
|
@@ -4818,28 +4836,11 @@ export async function runTestRun(opts, deps = {}) {
|
|
|
4818
4836
|
// Best-effort: a sink write throwing (e.g. EPIPE) must never skip the
|
|
4819
4837
|
// exit-code gate below or change the command's exit status.
|
|
4820
4838
|
try {
|
|
4821
|
-
|
|
4822
|
-
|
|
4823
|
-
|
|
4824
|
-
|
|
4825
|
-
|
|
4826
|
-
try {
|
|
4827
|
-
writeFileSync(opts.summaryFile, `${JSON.stringify(ciSummary, null, 2)}\n`, 'utf8');
|
|
4828
|
-
}
|
|
4829
|
-
catch {
|
|
4830
|
-
stderrFn(`[run] could not write --summary-file ${opts.summaryFile}; continuing`);
|
|
4831
|
-
}
|
|
4832
|
-
}
|
|
4833
|
-
if (ghEnabled) {
|
|
4834
|
-
const stdoutFn = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
|
|
4835
|
-
emitGithubOutputs(ciSummary, env, {
|
|
4836
|
-
stdout: stdoutFn,
|
|
4837
|
-
stderr: stderrFn,
|
|
4838
|
-
appendFile: (path, content) => appendFileSync(path, content, 'utf8'),
|
|
4839
|
-
annotations: opts.output === 'json' ? stderrFn : stdoutFn,
|
|
4840
|
-
}, { force: opts.ghOutput === true });
|
|
4841
|
-
}
|
|
4842
|
-
}
|
|
4839
|
+
emitCiArtifacts(summarizeSingleRun(finalRunWithUrl), opts, {
|
|
4840
|
+
env: deps.env ?? process.env,
|
|
4841
|
+
stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
|
|
4842
|
+
stderr: stderrFn,
|
|
4843
|
+
}, 'run');
|
|
4843
4844
|
}
|
|
4844
4845
|
catch (ciErr) {
|
|
4845
4846
|
stderrFn(`[run] CI output emission failed; continuing: ${ciErr.message}`);
|
|
@@ -5035,7 +5036,8 @@ export async function runTestWaitMany(opts, deps = {}) {
|
|
|
5035
5036
|
stderrFn(interruptDetachMessage(fanOutErr, unfinished));
|
|
5036
5037
|
}
|
|
5037
5038
|
else {
|
|
5038
|
-
stderrFn(`
|
|
5039
|
+
stderrFn(`Request timed out. ${stillRunningAndBillingSubject(unfinished)} ` +
|
|
5040
|
+
`Re-attach with: testsprite test wait ${unfinished.join(' ')}, or cancel with: testsprite test cancel ${unfinished.join(' ')}`);
|
|
5039
5041
|
}
|
|
5040
5042
|
}
|
|
5041
5043
|
}
|
|
@@ -5324,7 +5326,8 @@ export async function runTestWait(opts, deps = {}) {
|
|
|
5324
5326
|
throw ApiError.fromEnvelope({
|
|
5325
5327
|
error: {
|
|
5326
5328
|
code: 'UNSUPPORTED', // exit 7 per errors.md
|
|
5327
|
-
message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${opts.runId}
|
|
5329
|
+
message: `Timed out after ${opts.timeoutSeconds}s waiting for run ${opts.runId}. ` +
|
|
5330
|
+
stillRunningAndBillingSubject(opts.runId),
|
|
5328
5331
|
nextAction: `Resume polling: testsprite test wait ${opts.runId}, or cancel it: testsprite test cancel ${opts.runId}`,
|
|
5329
5332
|
requestId: 'local',
|
|
5330
5333
|
details: { runId: opts.runId, timeoutSeconds: opts.timeoutSeconds },
|
|
@@ -5346,7 +5349,7 @@ export async function runTestWait(opts, deps = {}) {
|
|
|
5346
5349
|
`hint Cancel with: testsprite test cancel ${p.runId}`,
|
|
5347
5350
|
].join('\n');
|
|
5348
5351
|
});
|
|
5349
|
-
stderrFn(`
|
|
5352
|
+
stderrFn(`Request timed out. ${stillRunningAndBillingSubject(opts.runId)} ` +
|
|
5350
5353
|
`Re-attach with: testsprite test wait ${opts.runId}, or cancel with: testsprite test cancel ${opts.runId}`);
|
|
5351
5354
|
throw err;
|
|
5352
5355
|
}
|
|
@@ -5409,15 +5412,57 @@ export async function runTestWait(opts, deps = {}) {
|
|
|
5409
5412
|
}
|
|
5410
5413
|
return finalRun;
|
|
5411
5414
|
}
|
|
5412
|
-
|
|
5415
|
+
/**
|
|
5416
|
+
* Best-effort `testId → test name` map for the JUnit report, so a CI test tab
|
|
5417
|
+
* shows names instead of UUIDs. One paginated `GET /tests?projectId=` sweep,
|
|
5418
|
+
* bounded by a 5 s deadline and swallowed on any error — a missing/partial map
|
|
5419
|
+
* just falls back to ids, never blocks or fails the report.
|
|
5420
|
+
*/
|
|
5421
|
+
async function buildTestNameMap(client, projectId) {
|
|
5422
|
+
const map = new Map();
|
|
5423
|
+
if (!projectId)
|
|
5424
|
+
return map;
|
|
5425
|
+
const ac = new AbortController();
|
|
5426
|
+
const timer = setTimeout(() => ac.abort(), DUP_NAME_ADVISORY_TIMEOUT_MS);
|
|
5427
|
+
try {
|
|
5428
|
+
let cursor;
|
|
5429
|
+
for (let pageN = 0; pageN < 20; pageN++) {
|
|
5430
|
+
const page = await client.get('/tests', {
|
|
5431
|
+
query: { projectId, pageSize: 100, ...(cursor ? { cursor } : {}) },
|
|
5432
|
+
signal: ac.signal,
|
|
5433
|
+
retryOnRateLimit: false,
|
|
5434
|
+
});
|
|
5435
|
+
for (const t of page.items ?? [])
|
|
5436
|
+
map.set(t.id, t.name);
|
|
5437
|
+
cursor = page.nextToken ?? undefined;
|
|
5438
|
+
if (!cursor)
|
|
5439
|
+
break;
|
|
5440
|
+
}
|
|
5441
|
+
}
|
|
5442
|
+
catch {
|
|
5443
|
+
// best-effort — a partial/empty map simply falls back to ids in the report.
|
|
5444
|
+
}
|
|
5445
|
+
finally {
|
|
5446
|
+
clearTimeout(timer);
|
|
5447
|
+
}
|
|
5448
|
+
return map;
|
|
5449
|
+
}
|
|
5450
|
+
async function writeBatchJUnitReportIfRequested(opts, results, nameByTestId) {
|
|
5413
5451
|
if (opts.report !== 'junit' || opts.reportFile === undefined)
|
|
5414
5452
|
return;
|
|
5415
5453
|
const projectId = resolveBatchReportProjectId(opts, results);
|
|
5416
5454
|
const suiteName = opts.reportSuiteName ?? `testsprite:${projectId}`;
|
|
5455
|
+
// Enrich each row with the human name (from the map) and the run duration
|
|
5456
|
+
// (from poll timing) — the two fields whose absence made the report unreadable.
|
|
5457
|
+
const enriched = results.map(r => ({
|
|
5458
|
+
...r,
|
|
5459
|
+
name: nameByTestId?.get(r.testId) ?? r.name,
|
|
5460
|
+
durationSeconds: r.durationSeconds ?? durationSecondsBetween(r.startedAt, r.finishedAt),
|
|
5461
|
+
}));
|
|
5417
5462
|
const xml = buildJUnitReport({
|
|
5418
5463
|
suiteName,
|
|
5419
5464
|
classname: projectId,
|
|
5420
|
-
results,
|
|
5465
|
+
results: enriched,
|
|
5421
5466
|
});
|
|
5422
5467
|
await writeJUnitReportFile(opts.reportFile, xml);
|
|
5423
5468
|
}
|
|
@@ -5540,14 +5585,16 @@ export async function runTestRunAll(opts, deps = {}) {
|
|
|
5540
5585
|
stderrFn(`[advisory] ${skippedIntegration.length} assembled integration test${skippedIntegration.length !== 1 ? 's' : ''} skipped — not runnable via the CLI wave path. Run them from the portal.`);
|
|
5541
5586
|
}
|
|
5542
5587
|
if (conflicts.length > 0) {
|
|
5543
|
-
|
|
5588
|
+
// Reason-aware advisory: a view-only / un-runnable / not-found case is not
|
|
5589
|
+
// "already in flight" — summarizeConflicts names the actual causes.
|
|
5590
|
+
stderrFn(`[advisory] ${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} not dispatched (${summarizeConflicts(conflicts)}), skipped: ${conflicts.map(c => c.testId).join(' ')}`);
|
|
5544
5591
|
}
|
|
5545
5592
|
if (deferred.length > 0) {
|
|
5546
5593
|
stderrFn(`Rate-deferred testIds (retry later): ${deferred.map(d => d.testId).join(' ')}`);
|
|
5547
5594
|
}
|
|
5548
5595
|
stderrFn(`Dispatched ${accepted.length} test${accepted.length !== 1 ? 's' : ''}` +
|
|
5549
5596
|
`${skippedFrontend.length > 0 ? ` (${skippedFrontend.length} FE skipped)` : ''}` +
|
|
5550
|
-
`${conflicts.length > 0 ? ` (${conflicts.length}
|
|
5597
|
+
`${conflicts.length > 0 ? ` (${conflicts.length} conflict${conflicts.length !== 1 ? 's' : ''})` : ''}` +
|
|
5551
5598
|
`${deferred.length > 0 ? ` (${deferred.length} rate-deferred)` : ''}.`);
|
|
5552
5599
|
if (!opts.wait) {
|
|
5553
5600
|
const printResp = {
|
|
@@ -5561,7 +5608,7 @@ export async function runTestRunAll(opts, deps = {}) {
|
|
|
5561
5608
|
const r = data;
|
|
5562
5609
|
const lines = [`accepted ${r.accepted.length}`];
|
|
5563
5610
|
if (r.conflicts.length > 0)
|
|
5564
|
-
lines.push(`conflicts ${r.conflicts.length} (
|
|
5611
|
+
lines.push(`conflicts ${r.conflicts.length} (${summarizeConflicts(r.conflicts)})`);
|
|
5565
5612
|
if (r.deferred.length > 0)
|
|
5566
5613
|
lines.push(`deferred ${r.deferred.length} (rate-limited — retry)`);
|
|
5567
5614
|
if (r.skippedFrontend.length > 0) {
|
|
@@ -5599,26 +5646,39 @@ export async function runTestRunAll(opts, deps = {}) {
|
|
|
5599
5646
|
// JSON merge reflect what was actually dispatched, not the stale initial resp.
|
|
5600
5647
|
return { ...batchResp, accepted, deferred, conflicts };
|
|
5601
5648
|
}
|
|
5602
|
-
// D3:
|
|
5603
|
-
//
|
|
5604
|
-
//
|
|
5605
|
-
//
|
|
5606
|
-
//
|
|
5607
|
-
// to the
|
|
5649
|
+
// D3: budget-driven deferred-retry loop (only under --wait).
|
|
5650
|
+
// Re-dispatches still-deferred tests until they all clear OR the --timeout
|
|
5651
|
+
// budget is exhausted — a busy pool (the in-flight concurrency cap folds
|
|
5652
|
+
// overflow into `deferred[]`) drains within the user's own timeout instead of
|
|
5653
|
+
// giving up after a fixed few tries and failing the run. Each attempt sleeps
|
|
5654
|
+
// 61s (clamped to the remaining budget); newly-accepted runs merge into
|
|
5655
|
+
// `accepted`; if still deferred when the budget runs out, fall through to the
|
|
5656
|
+
// existing exit-7 path. `maxDeferredAttempts` is a pure runaway backstop (the
|
|
5657
|
+
// deadline check below is the real stop), scaled to the timeout so it never
|
|
5658
|
+
// caps a legitimate long wait.
|
|
5608
5659
|
const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
|
|
5609
5660
|
const batchDeadlineMs = Date.now() + opts.timeoutSeconds * 1000;
|
|
5610
|
-
|
|
5661
|
+
// finding 1: reserve a poll window so the deferred-retry loop can't consume the
|
|
5662
|
+
// ENTIRE --timeout and leave the fan-out poll with nothing — which would report
|
|
5663
|
+
// already-finished runs as timeouts (exit 7) instead of their real verdicts
|
|
5664
|
+
// (a genuine failure is exit 1, not 7). One third of the budget, capped at 60s.
|
|
5665
|
+
const POLL_RESERVE_MS = Math.min(60_000, Math.floor((opts.timeoutSeconds * 1000) / 3));
|
|
5666
|
+
const maxDeferredAttempts = Math.max(MAX_DEFERRED_RETRIES, Math.ceil(opts.timeoutSeconds / 60) + 2);
|
|
5667
|
+
for (let attempt = 1; attempt <= maxDeferredAttempts && deferred.length > 0; attempt++) {
|
|
5611
5668
|
const remainingMs = batchDeadlineMs - Date.now();
|
|
5612
|
-
if (remainingMs <=
|
|
5613
|
-
stderrFn(`[deferred-retry]
|
|
5669
|
+
if (remainingMs <= POLL_RESERVE_MS) {
|
|
5670
|
+
stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
|
|
5614
5671
|
break;
|
|
5615
5672
|
}
|
|
5616
|
-
|
|
5617
|
-
|
|
5673
|
+
// §1: clamp to what's left ABOVE the reserve so the sleep itself can't run
|
|
5674
|
+
// the budget to zero (the loop only reaches here when remainingMs >
|
|
5675
|
+
// POLL_RESERVE_MS, so the difference is always positive).
|
|
5676
|
+
const sleepMs = Math.min(DEFERRED_RETRY_DEFAULT_SLEEP_MS, remainingMs - POLL_RESERVE_MS);
|
|
5677
|
+
stderrFn(`[deferred-retry] attempt ${attempt} — retrying ${deferred.length} deferred test${deferred.length !== 1 ? 's' : ''} in ${Math.round(sleepMs / 1000)}s`);
|
|
5618
5678
|
await sleepFn(sleepMs);
|
|
5619
5679
|
const remainingAfterSleep = batchDeadlineMs - Date.now();
|
|
5620
|
-
if (remainingAfterSleep <=
|
|
5621
|
-
stderrFn(`[deferred-retry]
|
|
5680
|
+
if (remainingAfterSleep <= POLL_RESERVE_MS) {
|
|
5681
|
+
stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
|
|
5622
5682
|
break;
|
|
5623
5683
|
}
|
|
5624
5684
|
const retryIds = deferred.map(d => d.testId);
|
|
@@ -5633,6 +5693,16 @@ export async function runTestRunAll(opts, deps = {}) {
|
|
|
5633
5693
|
const retryKey = `${retryBase}${retrySuffix}`;
|
|
5634
5694
|
let retryResp;
|
|
5635
5695
|
try {
|
|
5696
|
+
// The retry dispatch POST is deliberately NOT bound to the batch deadline
|
|
5697
|
+
// via an AbortSignal. It is a state-CREATING call (it seeds runs); if the
|
|
5698
|
+
// deadline fired mid-flight the abort would only cancel the CLIENT wait,
|
|
5699
|
+
// leaving the server having possibly created the runs while this loop
|
|
5700
|
+
// reports them as still-deferred — the user then retries with a fresh
|
|
5701
|
+
// idempotency key and DUPLICATES the execution + charge. The per-request
|
|
5702
|
+
// timeout (`--request-timeout`, default 120s) still bounds the call, and
|
|
5703
|
+
// the sleeps + fan-out poll below remain deadline-aware; only this single
|
|
5704
|
+
// dispatch may overrun the budget slightly, which is strictly safer than
|
|
5705
|
+
// an indeterminate aborted-but-maybe-dispatched batch.
|
|
5636
5706
|
retryResp = await client.triggerBatchRunFresh({
|
|
5637
5707
|
projectId,
|
|
5638
5708
|
testIds: retryIds,
|
|
@@ -5640,7 +5710,7 @@ export async function runTestRunAll(opts, deps = {}) {
|
|
|
5640
5710
|
}, { idempotencyKey: retryKey });
|
|
5641
5711
|
}
|
|
5642
5712
|
catch (err) {
|
|
5643
|
-
// If the retry itself errors, surface
|
|
5713
|
+
// If the retry itself errors, surface it and stop retrying.
|
|
5644
5714
|
stderrFn(`[deferred-retry] attempt ${attempt} failed with error: ${err instanceof Error ? err.message : String(err)}`);
|
|
5645
5715
|
break;
|
|
5646
5716
|
}
|
|
@@ -5664,11 +5734,53 @@ export async function runTestRunAll(opts, deps = {}) {
|
|
|
5664
5734
|
stderrFn(`[deferred-retry] attempt ${attempt}: all previously-deferred tests accepted.`);
|
|
5665
5735
|
}
|
|
5666
5736
|
}
|
|
5667
|
-
//
|
|
5668
|
-
//
|
|
5669
|
-
//
|
|
5670
|
-
//
|
|
5671
|
-
|
|
5737
|
+
// Gap B: an already-running case is not a dead end under --wait. A conflict
|
|
5738
|
+
// carrying `currentRunId` has an EXISTING run we can poll to a verdict
|
|
5739
|
+
// (auto-resume) — the "concurrent job already started this test" case should
|
|
5740
|
+
// wait for that run's result, not fail the batch. Conflicts without a
|
|
5741
|
+
// resolvable in-flight run stay hard (nothing to wait on).
|
|
5742
|
+
const resumableConflicts = conflicts.filter(c => c.currentRunId);
|
|
5743
|
+
const hardConflicts = conflicts.filter(c => !c.currentRunId);
|
|
5744
|
+
// Only hard conflicts remain "conflicts" for the final accounting/exit; the
|
|
5745
|
+
// resumable ones become polled results below.
|
|
5746
|
+
conflicts = hardConflicts;
|
|
5747
|
+
// finding 2: resolve each in-flight run's createdAt to floor the BE wait
|
|
5748
|
+
// fallback's "not before" filter. An epoch sentinel let the fallback accept
|
|
5749
|
+
// ANY terminal result for the test — including the PREVIOUS run's — whenever
|
|
5750
|
+
// the row lacks `runIdIfAvailable` (the orphaned-row case the fallback exists
|
|
5751
|
+
// for, and the EXPECTED path for MCP-backend-triggered runs whose TestRun rows
|
|
5752
|
+
// never leave `queued`). Flooring to the run's own createdAt stops an
|
|
5753
|
+
// auto-resume from resolving to a stale prior verdict (a false green). The
|
|
5754
|
+
// fetch also yields source/createdFrom so we can name who started the run.
|
|
5755
|
+
// §5: resolve the in-flight runs' createdAt in PARALLEL, bounded by a signal
|
|
5756
|
+
// capped at the remaining batch budget. This runs in exactly the busy-pool /
|
|
5757
|
+
// many-in-flight-conflicts scenario finding 1 is about, so a serial N round-trip
|
|
5758
|
+
// fetch (with no deadline bound) would eat the budget finding 1's fix protects.
|
|
5759
|
+
const resolveSignal = AbortSignal.timeout(Math.max(1, batchDeadlineMs - Date.now()));
|
|
5760
|
+
const resumableEntries = await Promise.all(resumableConflicts.map(async (c) => {
|
|
5761
|
+
const inFlightRunId = c.currentRunId;
|
|
5762
|
+
// Conservative default if the run can't be read: floor at NOW (never the
|
|
5763
|
+
// epoch) so the fallback still can't accept an older run's result.
|
|
5764
|
+
let notBefore = new Date().toISOString();
|
|
5765
|
+
let startedBy;
|
|
5766
|
+
try {
|
|
5767
|
+
const inFlight = await client.getRun(inFlightRunId, { signal: resolveSignal });
|
|
5768
|
+
if (inFlight.createdAt)
|
|
5769
|
+
notBefore = inFlight.createdAt;
|
|
5770
|
+
startedBy = inFlight.source || inFlight.createdFrom || undefined;
|
|
5771
|
+
}
|
|
5772
|
+
catch {
|
|
5773
|
+
// keep the conservative now() floor (fetch failed or the signal aborted)
|
|
5774
|
+
}
|
|
5775
|
+
stderrFn(`[auto-resume] ${c.testId} — polling in-flight run ${inFlightRunId}${startedBy ? ` (started by ${startedBy})` : ''} to a verdict instead of failing`);
|
|
5776
|
+
return { testId: c.testId, runId: inFlightRunId, enqueuedAt: notBefore };
|
|
5777
|
+
}));
|
|
5778
|
+
// --wait: fan-out poll each accepted run by its runId, PLUS each auto-resumed
|
|
5779
|
+
// in-flight run. Every accepted entry carries a real runId (the backend routes
|
|
5780
|
+
// slot-claim failures to conflicts[]); the resumed entries reuse the existing
|
|
5781
|
+
// run's id with a real createdAt floor. Polling all of them is the only way
|
|
5782
|
+
// `--wait` reports a faithful (not false-green) verdict.
|
|
5783
|
+
const pollable = [...accepted, ...resumableEntries];
|
|
5672
5784
|
if (pollable.length === 0) {
|
|
5673
5785
|
// Build final response with potentially-updated accepted/deferred from D3 retry loop.
|
|
5674
5786
|
const finalResp = {
|
|
@@ -5679,6 +5791,15 @@ export async function runTestRunAll(opts, deps = {}) {
|
|
|
5679
5791
|
skippedIntegration,
|
|
5680
5792
|
};
|
|
5681
5793
|
out.print(finalResp);
|
|
5794
|
+
// Nothing was dispatched, but a --wait CI run still needs the exit-6/7 to be
|
|
5795
|
+
// visible: emit annotations + summary before the throw below (conflicts /
|
|
5796
|
+
// deferred fold into the summary as non-passed rows; skipped* are not folded).
|
|
5797
|
+
// Without this an all-in-flight or all-deferred batch fails CI silently.
|
|
5798
|
+
emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(finalResp)), opts, {
|
|
5799
|
+
env: deps.env ?? process.env,
|
|
5800
|
+
stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
|
|
5801
|
+
stderr: stderrFn,
|
|
5802
|
+
}, 'run');
|
|
5682
5803
|
// Nothing to poll: surface deferred (rate-limit → exit 7) or all-conflict (exit 6),
|
|
5683
5804
|
// mirroring the non-wait path so `--wait` never silently exits 0 on a no-op batch.
|
|
5684
5805
|
if (deferred.length > 0) {
|
|
@@ -5711,6 +5832,37 @@ export async function runTestRunAll(opts, deps = {}) {
|
|
|
5711
5832
|
const runId = entry.runId;
|
|
5712
5833
|
const remainingMs = batchDeadlineMs - Date.now();
|
|
5713
5834
|
if (remainingMs <= 0) {
|
|
5835
|
+
// §1/§4: the retry loop reserves POLL_RESERVE_MS, but a slow fan-out can
|
|
5836
|
+
// still land here past the deadline. Do ONE bounded poll (1s) THROUGH the
|
|
5837
|
+
// backend wait-fallback before declaring timeout — a run that already
|
|
5838
|
+
// reached a verdict resolves for ~one request instead of a false timeout
|
|
5839
|
+
// (exit 7 when the platform already produced its result; a failure is exit
|
|
5840
|
+
// 1). Going through pollRunUntilTerminal + resolveAlternate — not a bare
|
|
5841
|
+
// getRun — also covers the orphaned-row class finding 2 is about: a backend
|
|
5842
|
+
// TestRun row stuck in `queued` whose verdict only the fallback resolves.
|
|
5843
|
+
const lastResortAlternate = makeBackendWaitFallback({
|
|
5844
|
+
client,
|
|
5845
|
+
resolveTestId: () => entry.testId,
|
|
5846
|
+
resolveNotBefore: () => entry.enqueuedAt,
|
|
5847
|
+
onResolved: () => undefined,
|
|
5848
|
+
});
|
|
5849
|
+
try {
|
|
5850
|
+
const finalRun = await pollRunUntilTerminal(client, runId, {
|
|
5851
|
+
timeoutSeconds: 1,
|
|
5852
|
+
sleep: deps.sleep,
|
|
5853
|
+
shutdown: shutdownOf(deps),
|
|
5854
|
+
resolveAlternate: lastResortAlternate,
|
|
5855
|
+
});
|
|
5856
|
+
return {
|
|
5857
|
+
testId: entry.testId,
|
|
5858
|
+
runId,
|
|
5859
|
+
projectId: finalRun.projectId,
|
|
5860
|
+
status: finalRun.status,
|
|
5861
|
+
};
|
|
5862
|
+
}
|
|
5863
|
+
catch {
|
|
5864
|
+
// fall through to the timeout result below
|
|
5865
|
+
}
|
|
5714
5866
|
return {
|
|
5715
5867
|
testId: entry.testId,
|
|
5716
5868
|
runId,
|
|
@@ -5747,6 +5899,8 @@ export async function runTestRunAll(opts, deps = {}) {
|
|
|
5747
5899
|
runId,
|
|
5748
5900
|
projectId: finalRun.projectId,
|
|
5749
5901
|
status: finalRun.status,
|
|
5902
|
+
startedAt: finalRun.startedAt,
|
|
5903
|
+
finishedAt: finalRun.finishedAt,
|
|
5750
5904
|
};
|
|
5751
5905
|
}
|
|
5752
5906
|
catch (err) {
|
|
@@ -5860,74 +6014,53 @@ export async function runTestRunAll(opts, deps = {}) {
|
|
|
5860
6014
|
total: pollable.length,
|
|
5861
6015
|
},
|
|
5862
6016
|
};
|
|
5863
|
-
|
|
6017
|
+
const freshNameMap = opts.report === 'junit' && opts.reportFile !== undefined
|
|
6018
|
+
? await buildTestNameMap(client, opts.projectId)
|
|
6019
|
+
: undefined;
|
|
6020
|
+
await writeBatchJUnitReportIfRequested(opts, freshRunResults, freshNameMap);
|
|
5864
6021
|
out.print(jsonPayload);
|
|
5865
6022
|
// CI-native output layer (issue #99): emitted before the gate throws below so
|
|
5866
6023
|
// the artifacts land even when the batch exits non-zero. The summary file is a
|
|
5867
6024
|
// machine artifact written regardless of --output mode; stdout stays owned by
|
|
5868
6025
|
// the envelope above (plus Actions workflow commands, which Actions parses).
|
|
5869
|
-
{
|
|
5870
|
-
|
|
5871
|
-
|
|
5872
|
-
|
|
5873
|
-
|
|
5874
|
-
if (opts.summaryFile !== undefined) {
|
|
5875
|
-
try {
|
|
5876
|
-
writeFileSync(opts.summaryFile, `${JSON.stringify(ciSummary, null, 2)}\n`, 'utf8');
|
|
5877
|
-
}
|
|
5878
|
-
catch {
|
|
5879
|
-
stderrFn(`[run] could not write --summary-file ${opts.summaryFile}; continuing`);
|
|
5880
|
-
}
|
|
5881
|
-
}
|
|
5882
|
-
if (ghEnabled) {
|
|
5883
|
-
const stdoutFn = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
|
|
5884
|
-
emitGithubOutputs(ciSummary, env, {
|
|
5885
|
-
stdout: stdoutFn,
|
|
5886
|
-
stderr: stderrFn,
|
|
5887
|
-
appendFile: (path, content) => appendFileSync(path, content, 'utf8'),
|
|
5888
|
-
// Under --output json the envelope above owns stdout; workflow
|
|
5889
|
-
// commands go to stderr instead (the Actions runner parses both
|
|
5890
|
-
// streams), keeping the documented machine output parseable.
|
|
5891
|
-
annotations: opts.output === 'json' ? stderrFn : stdoutFn,
|
|
5892
|
-
}, { force: opts.ghOutput === true });
|
|
5893
|
-
}
|
|
5894
|
-
}
|
|
5895
|
-
}
|
|
6026
|
+
emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(jsonPayload)), opts, {
|
|
6027
|
+
env: deps.env ?? process.env,
|
|
6028
|
+
stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
|
|
6029
|
+
stderr: stderrFn,
|
|
6030
|
+
}, 'run');
|
|
5896
6031
|
// Rate-deferred tests were never dispatched → the batch is incomplete (exit 7),
|
|
5897
6032
|
// mirroring `test rerun --all`. Checked before the failed-run throw so the
|
|
5898
6033
|
// operator learns to retry the deferred set.
|
|
5899
6034
|
if (deferred.length > 0) {
|
|
5900
6035
|
throw new CLIError(`Batch run incomplete: ${deferred.length} test${deferred.length !== 1 ? 's' : ''} rate-deferred (per-key run budget) — retry these individually after ~60s: ${deferred.map(d => d.testId).join(' ')}`, 7);
|
|
5901
6036
|
}
|
|
5902
|
-
|
|
5903
|
-
|
|
5904
|
-
|
|
5905
|
-
|
|
5906
|
-
|
|
6037
|
+
// Shared exit-code precedence (auth 3 → typed operational ApiError → timeout 7
|
|
6038
|
+
// → generic fail 1) so `test run` and `testlist run` can't drift. This
|
|
6039
|
+
// supersedes the previous "fold every non-auth poll error into exit 1"
|
|
6040
|
+
// behaviour: a NOT_FOUND/RATE_LIMITED/… poll now propagates its real code.
|
|
6041
|
+
const failure = resolveWaitFailure(freshRunResults, { timeoutSeconds: opts.timeoutSeconds });
|
|
6042
|
+
if (failure)
|
|
6043
|
+
throw failure;
|
|
6044
|
+
// Hard conflicts (a run already in flight for the test that we could NOT
|
|
6045
|
+
// auto-resume — no `currentRunId` to poll) mean those tests never ran. In a
|
|
6046
|
+
// MIXED batch, the accepted/resumed runs above already made `pollable`
|
|
6047
|
+
// non-empty, so the all-conflict early-exit-6 branch didn't fire — without
|
|
6048
|
+
// this gate a passing resumable run would mask an unresolved hard conflict and
|
|
6049
|
+
// exit 0. Checked AFTER the failed gate (a real failure is the more actionable
|
|
6050
|
+
// headline; a batch with both still exits 1), matching the exit-6 the
|
|
6051
|
+
// all-conflict path returns. `conflicts` here holds only the hard ones —
|
|
6052
|
+
// resumable conflicts were split into the poll set above.
|
|
6053
|
+
if (conflicts.length > 0) {
|
|
5907
6054
|
throw ApiError.fromEnvelope({
|
|
5908
6055
|
error: {
|
|
5909
|
-
code: '
|
|
5910
|
-
message: `${
|
|
5911
|
-
nextAction:
|
|
5912
|
-
...timedOutRunIds.map(rid => `Resume: testsprite test wait ${rid}`),
|
|
5913
|
-
...timedOutRunIds.map(rid => `Cancel: testsprite test cancel ${rid}`),
|
|
5914
|
-
].join('\n'),
|
|
6056
|
+
code: 'CONFLICT',
|
|
6057
|
+
message: `${conflicts.length} test${conflicts.length !== 1 ? 's' : ''} already in flight and could not be resumed — not run.`,
|
|
6058
|
+
nextAction: `Wait for the in-flight run(s) to finish, then retry: ${conflicts.map(c => c.testId).join(' ')}`,
|
|
5915
6059
|
requestId: 'local',
|
|
5916
|
-
details: {
|
|
6060
|
+
details: { conflicts: conflicts.map(c => c.testId) },
|
|
5917
6061
|
},
|
|
5918
6062
|
});
|
|
5919
6063
|
}
|
|
5920
|
-
if (failed > 0) {
|
|
5921
|
-
// An auth failure on any member is a batch-wide condition (the credential is
|
|
5922
|
-
// bad, not the test) — propagate exit 3 so the operator fixes auth rather
|
|
5923
|
-
// than chasing a "test failed" (exit 1). Other operational codes stay folded
|
|
5924
|
-
// into the generic batch-failure exit 1; their per-member envelope is in JSON.
|
|
5925
|
-
const authErr = freshRunResults.find(r => r.error?.exitCode === 3);
|
|
5926
|
-
if (authErr) {
|
|
5927
|
-
throw new CLIError(`${failed} run${failed !== 1 ? 's' : ''} failed — auth error (${authErr.error?.code}): ${authErr.error?.message}`, 3);
|
|
5928
|
-
}
|
|
5929
|
-
throw new CLIError(`${failed} run${failed !== 1 ? 's' : ''} failed.`, 1);
|
|
5930
|
-
}
|
|
5931
6064
|
// [P2] Return object reconstructed from post-retry mutable state (accepted,
|
|
5932
6065
|
// deferred, conflicts) so the caller always sees what was actually dispatched,
|
|
5933
6066
|
// not the stale initial batchResp. accepted here still holds the original
|
|
@@ -6359,7 +6492,8 @@ export async function runTestRerun(opts, deps = {}) {
|
|
|
6359
6492
|
const cancelHints = closureMembers
|
|
6360
6493
|
.map(m => `testsprite test cancel ${m.runId}`)
|
|
6361
6494
|
.join('\n');
|
|
6362
|
-
stderrFn(`
|
|
6495
|
+
stderrFn(`Request timed out. ${stillRunningAndBillingSubject(closureMembers.map(m => m.runId))} ` +
|
|
6496
|
+
`Re-attach with:\n${reattachHints}\n` +
|
|
6363
6497
|
`Or cancel with:\n${cancelHints}`);
|
|
6364
6498
|
throw fanOutErr;
|
|
6365
6499
|
}
|
|
@@ -6462,6 +6596,15 @@ export async function runTestRerun(opts, deps = {}) {
|
|
|
6462
6596
|
// never confirmed would let --wait exit 0. Observed-failed members are not
|
|
6463
6597
|
// included; that's the future --fail-on-closure decision.
|
|
6464
6598
|
const unobservedMembers = closureFailures.filter(f => f.unobserved);
|
|
6599
|
+
// §5 (unify with the batch fan-outs): an auth failure on an unobserved
|
|
6600
|
+
// closure member is batch-wide (a bad credential, not a bad test) and
|
|
6601
|
+
// non-retriable, so it must exit 3 — not be masked as the generic
|
|
6602
|
+
// unobserved-timeout 7. A poll-errored member's `status` holds the error
|
|
6603
|
+
// code; a timed-out member's is `'timeout'` (never an auth code).
|
|
6604
|
+
const authMember = unobservedMembers.find(m => isAuthCode(m.status));
|
|
6605
|
+
if (authMember) {
|
|
6606
|
+
throw new CLIError(`Closure member ${authMember.runId} hit an auth error (${authMember.status}) — the credential is bad, not the test.`, 3);
|
|
6607
|
+
}
|
|
6465
6608
|
if (unobservedMembers.length > 0) {
|
|
6466
6609
|
const unobservedIds = unobservedMembers.map(f => f.runId);
|
|
6467
6610
|
const resumeHints = unobservedIds.map(runId => `testsprite test wait ${runId}`).join('\n') +
|
|
@@ -6511,10 +6654,23 @@ export async function runTestRerun(opts, deps = {}) {
|
|
|
6511
6654
|
catch (err) {
|
|
6512
6655
|
if (err instanceof TimeoutError) {
|
|
6513
6656
|
ticker.finalize(`Run ${rerunResp.runId} — timed out after ${opts.timeoutSeconds}s`);
|
|
6657
|
+
// Mirror the RequestTimeoutError path: emit a partial run to stdout so
|
|
6658
|
+
// JSON consumers and AI agents can grab the runId and chain into
|
|
6659
|
+
// `testsprite test wait <runId>` without parsing the stderr error envelope.
|
|
6660
|
+
const timeoutPartial = { runId: rerunResp.runId, status: 'running' };
|
|
6661
|
+
out.print(timeoutPartial, data => {
|
|
6662
|
+
const p = data;
|
|
6663
|
+
return [
|
|
6664
|
+
`runId ${p.runId}`,
|
|
6665
|
+
`status ${p.status} (timed out after ${opts.timeoutSeconds}s)`,
|
|
6666
|
+
`hint Re-attach with: testsprite test wait ${p.runId}`,
|
|
6667
|
+
].join('\n');
|
|
6668
|
+
});
|
|
6514
6669
|
throw ApiError.fromEnvelope({
|
|
6515
6670
|
error: {
|
|
6516
6671
|
code: 'UNSUPPORTED',
|
|
6517
|
-
message: `Timed out after ${opts.timeoutSeconds}s waiting for rerun ${rerunResp.runId}
|
|
6672
|
+
message: `Timed out after ${opts.timeoutSeconds}s waiting for rerun ${rerunResp.runId}. ` +
|
|
6673
|
+
stillRunningAndBillingSubject(rerunResp.runId),
|
|
6518
6674
|
nextAction: `Resume polling: testsprite test wait ${rerunResp.runId}, or cancel it: testsprite test cancel ${rerunResp.runId}`,
|
|
6519
6675
|
requestId: 'local',
|
|
6520
6676
|
details: { runId: rerunResp.runId, timeoutSeconds: opts.timeoutSeconds },
|
|
@@ -6535,7 +6691,7 @@ export async function runTestRerun(opts, deps = {}) {
|
|
|
6535
6691
|
`hint Cancel with: testsprite test cancel ${p.runId}`,
|
|
6536
6692
|
].join('\n');
|
|
6537
6693
|
});
|
|
6538
|
-
stderrFn(`
|
|
6694
|
+
stderrFn(`Request timed out. ${stillRunningAndBillingSubject(rerunResp.runId)} ` +
|
|
6539
6695
|
`Re-attach with: testsprite test wait ${rerunResp.runId}, or cancel with: testsprite test cancel ${rerunResp.runId}`);
|
|
6540
6696
|
throw err;
|
|
6541
6697
|
}
|
|
@@ -6791,27 +6947,38 @@ export async function runTestRerun(opts, deps = {}) {
|
|
|
6791
6947
|
const deferredIds = deferred.map(d => d.testId).join(' ');
|
|
6792
6948
|
stderrFn(`nextAction: testsprite test rerun ${deferredIds}`);
|
|
6793
6949
|
}
|
|
6794
|
-
// D3:
|
|
6795
|
-
//
|
|
6796
|
-
//
|
|
6797
|
-
//
|
|
6798
|
-
//
|
|
6799
|
-
//
|
|
6950
|
+
// D3: budget-driven deferred-retry loop for rerun --all (only under --wait).
|
|
6951
|
+
// Re-dispatches still-deferred tests until they all clear OR the --timeout
|
|
6952
|
+
// budget is exhausted — a busy pool drains within the user's own timeout
|
|
6953
|
+
// instead of giving up after a fixed few tries and failing the run. Each
|
|
6954
|
+
// attempt sleeps 61s (clamped to the remaining budget); newly-accepted runs
|
|
6955
|
+
// merge into `accepted`; if still deferred when the budget runs out, fall
|
|
6956
|
+
// through to the existing exit-7 path. `maxDeferredAttempts` is a pure runaway
|
|
6957
|
+
// backstop (the deadline check below is the real stop), scaled to the timeout.
|
|
6800
6958
|
const sleepFn = deps.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
|
|
6801
6959
|
const batchDeadlineMs = Date.now() + opts.timeoutSeconds * 1000;
|
|
6960
|
+
// finding 1: reserve a poll window so the deferred-retry loop can't consume the
|
|
6961
|
+
// ENTIRE --timeout and leave the fan-out poll with nothing — which would report
|
|
6962
|
+
// already-finished runs as timeouts (exit 7) instead of their real verdicts
|
|
6963
|
+
// (a genuine failure is exit 1, not 7). One third of the budget, capped at 60s.
|
|
6964
|
+
const POLL_RESERVE_MS = Math.min(60_000, Math.floor((opts.timeoutSeconds * 1000) / 3));
|
|
6965
|
+
const maxDeferredAttempts = Math.max(MAX_DEFERRED_RETRIES, Math.ceil(opts.timeoutSeconds / 60) + 2);
|
|
6802
6966
|
if (opts.wait) {
|
|
6803
|
-
for (let attempt = 1; attempt <=
|
|
6967
|
+
for (let attempt = 1; attempt <= maxDeferredAttempts && deferred.length > 0; attempt++) {
|
|
6804
6968
|
const remainingMs = batchDeadlineMs - Date.now();
|
|
6805
|
-
if (remainingMs <=
|
|
6806
|
-
stderrFn(`[deferred-retry]
|
|
6969
|
+
if (remainingMs <= POLL_RESERVE_MS) {
|
|
6970
|
+
stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
|
|
6807
6971
|
break;
|
|
6808
6972
|
}
|
|
6809
|
-
|
|
6810
|
-
|
|
6973
|
+
// §1: clamp to what's left ABOVE the reserve so the sleep itself can't run
|
|
6974
|
+
// the budget to zero (the loop only reaches here when remainingMs >
|
|
6975
|
+
// POLL_RESERVE_MS, so the difference is always positive).
|
|
6976
|
+
const sleepMs = Math.min(DEFERRED_RETRY_DEFAULT_SLEEP_MS, remainingMs - POLL_RESERVE_MS);
|
|
6977
|
+
stderrFn(`[deferred-retry] attempt ${attempt} — retrying ${deferred.length} deferred test${deferred.length !== 1 ? 's' : ''} in ${Math.round(sleepMs / 1000)}s`);
|
|
6811
6978
|
await sleepFn(sleepMs);
|
|
6812
6979
|
const remainingAfterSleep = batchDeadlineMs - Date.now();
|
|
6813
|
-
if (remainingAfterSleep <=
|
|
6814
|
-
stderrFn(`[deferred-retry]
|
|
6980
|
+
if (remainingAfterSleep <= POLL_RESERVE_MS) {
|
|
6981
|
+
stderrFn(`[deferred-retry] reserving the remaining budget to poll dispatched runs — ${deferred.length} test${deferred.length !== 1 ? 's' : ''} still deferred.`);
|
|
6815
6982
|
break;
|
|
6816
6983
|
}
|
|
6817
6984
|
// Chunk the retry ids to stay within MAX_BATCH_RERUN_IDS cap.
|
|
@@ -6839,6 +7006,13 @@ export async function runTestRerun(opts, deps = {}) {
|
|
|
6839
7006
|
? idempotencyKey.slice(0, 256 - retrySuffix.length)
|
|
6840
7007
|
: idempotencyKey;
|
|
6841
7008
|
const retryKey = `${retryBase}${retrySuffix}`;
|
|
7009
|
+
// The retry chunk POST is deliberately NOT bound to the batch
|
|
7010
|
+
// deadline via an AbortSignal — same reasoning as the fresh-run retry
|
|
7011
|
+
// above: it seeds runs, so a mid-flight abort would leave the server
|
|
7012
|
+
// possibly having dispatched while this loop reports the chunk as
|
|
7013
|
+
// still-deferred, inviting a duplicate rerun on the user's next
|
|
7014
|
+
// invocation. The per-request timeout still bounds it; the sleeps +
|
|
7015
|
+
// poll stay deadline-aware.
|
|
6842
7016
|
const retryChunkResp = await client.triggerBatchRerun({
|
|
6843
7017
|
source: 'cli',
|
|
6844
7018
|
testIds: chunk,
|
|
@@ -6935,6 +7109,16 @@ export async function runTestRerun(opts, deps = {}) {
|
|
|
6935
7109
|
if (accepted.length === 0) {
|
|
6936
7110
|
// [P2] Build output from post-retry mutable state including merged notFound.
|
|
6937
7111
|
out.print({ ...batchResp, accepted, deferred, conflicts, notFound, advisories });
|
|
7112
|
+
// Nothing dispatched, but a --wait CI run still needs the exit-6/7 visible:
|
|
7113
|
+
// emit annotations + summary before the throw below (conflicts / deferred /
|
|
7114
|
+
// notFound fold in as non-passed rows). Without this an all-conflict or
|
|
7115
|
+
// all-deferred rerun fails CI silently. (Default notFound note is correct
|
|
7116
|
+
// here — a rerun not-found id genuinely has no run to replay.)
|
|
7117
|
+
emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify({ accepted: [], deferred, conflicts, notFound })), opts, {
|
|
7118
|
+
env: deps.env ?? process.env,
|
|
7119
|
+
stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
|
|
7120
|
+
stderr: stderrFn,
|
|
7121
|
+
}, 'rerun');
|
|
6938
7122
|
if (deferred.length > 0) {
|
|
6939
7123
|
throw new CLIError(`Batch rerun: no tests were accepted (${deferred.length} deferred). ` +
|
|
6940
7124
|
`Retry with: testsprite test rerun ${deferred.map(d => d.testId).join(' ')}`, 7);
|
|
@@ -7121,36 +7305,29 @@ export async function runTestRerun(opts, deps = {}) {
|
|
|
7121
7305
|
total: accepted.length,
|
|
7122
7306
|
},
|
|
7123
7307
|
};
|
|
7124
|
-
|
|
7308
|
+
const rerunNameMap = opts.report === 'junit' && opts.reportFile !== undefined
|
|
7309
|
+
? await buildTestNameMap(client, opts.projectId)
|
|
7310
|
+
: undefined;
|
|
7311
|
+
await writeBatchJUnitReportIfRequested(opts, rerunResults, rerunNameMap);
|
|
7125
7312
|
out.print(jsonPayload);
|
|
7126
7313
|
// CI-native output layer (issue #99): batch-rerun parity with `run --all`.
|
|
7127
7314
|
// Emitted before the exit-code gates below so the summary file / annotations
|
|
7128
7315
|
// land even when the batch exits non-zero. Summary-file is a machine artifact
|
|
7129
7316
|
// written regardless of --output mode; under --output json the envelope above
|
|
7130
7317
|
// owns stdout, so ::error:: workflow commands go to stderr instead.
|
|
7131
|
-
{
|
|
7132
|
-
|
|
7133
|
-
|
|
7134
|
-
|
|
7135
|
-
|
|
7136
|
-
|
|
7137
|
-
|
|
7138
|
-
|
|
7139
|
-
|
|
7140
|
-
|
|
7141
|
-
|
|
7142
|
-
|
|
7143
|
-
|
|
7144
|
-
if (ghEnabled) {
|
|
7145
|
-
const stdoutFn = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
|
|
7146
|
-
emitGithubOutputs(ciSummary, env, {
|
|
7147
|
-
stdout: stdoutFn,
|
|
7148
|
-
stderr: stderrFn,
|
|
7149
|
-
appendFile: (path, content) => appendFileSync(path, content, 'utf8'),
|
|
7150
|
-
annotations: opts.output === 'json' ? stderrFn : stdoutFn,
|
|
7151
|
-
}, { force: opts.ghOutput === true });
|
|
7152
|
-
}
|
|
7153
|
-
}
|
|
7318
|
+
emitCiArtifacts(summarizeAcceptedPayload(JSON.stringify(jsonPayload)), opts, {
|
|
7319
|
+
env: deps.env ?? process.env,
|
|
7320
|
+
stdout: deps.stdout ?? ((line) => process.stdout.write(`${line}\n`)),
|
|
7321
|
+
stderr: stderrFn,
|
|
7322
|
+
}, 'rerun');
|
|
7323
|
+
// §5 (unify rerun with run --all / testlist run): auth is batch-wide — a bad
|
|
7324
|
+
// credential, not a bad test — and non-retriable, so it must win even over a
|
|
7325
|
+
// concurrent deferred/timeout. Run the shared helper's auth check BEFORE the
|
|
7326
|
+
// combined gate below, which would otherwise mask it as exit 7.
|
|
7327
|
+
if (rerunResults.some(r => r.error?.exitCode === 3)) {
|
|
7328
|
+
const authFailure = resolveWaitFailure(rerunResults, { timeoutSeconds: opts.timeoutSeconds });
|
|
7329
|
+
if (authFailure)
|
|
7330
|
+
throw authFailure;
|
|
7154
7331
|
}
|
|
7155
7332
|
// Determine exit code: timeout (deferred or any timeout) → 7; any fail → 1; all pass → 0
|
|
7156
7333
|
if (deferred.length > 0 || timedOut > 0) {
|
|
@@ -7180,17 +7357,14 @@ export async function runTestRerun(opts, deps = {}) {
|
|
|
7180
7357
|
},
|
|
7181
7358
|
});
|
|
7182
7359
|
}
|
|
7183
|
-
|
|
7184
|
-
|
|
7185
|
-
|
|
7186
|
-
|
|
7187
|
-
|
|
7188
|
-
|
|
7189
|
-
|
|
7190
|
-
|
|
7191
|
-
}
|
|
7192
|
-
throw new CLIError(`${failed} rerun${failed !== 1 ? 's' : ''} failed.`, 1);
|
|
7193
|
-
}
|
|
7360
|
+
// Shared exit-code precedence for the failure tail. The combined
|
|
7361
|
+
// deferred/timeout gate above already fired for those, so only auth (3) →
|
|
7362
|
+
// typed operational ApiError → generic fail (1) remain — a NOT_FOUND /
|
|
7363
|
+
// RATE_LIMITED / … poll error now propagates its real code instead of folding
|
|
7364
|
+
// into exit 1 (matches `test run --all` / `testlist run`).
|
|
7365
|
+
const failure = resolveWaitFailure(rerunResults, { timeoutSeconds: opts.timeoutSeconds });
|
|
7366
|
+
if (failure)
|
|
7367
|
+
throw failure;
|
|
7194
7368
|
// [P2] Return post-retry state including merged notFound so callers see the
|
|
7195
7369
|
// final accounting (accepted = original BatchRerunAccepted[] dispatch list
|
|
7196
7370
|
// as required by the BatchRerunResponse type; rerunResults is the polled
|
|
@@ -7372,6 +7546,18 @@ function renderArtifactGetWrittenText(data) {
|
|
|
7372
7546
|
`files: ${data.files}`,
|
|
7373
7547
|
].join('\n');
|
|
7374
7548
|
}
|
|
7549
|
+
/**
|
|
7550
|
+
* Shared `--skip-preflight` help text across the three commands
|
|
7551
|
+
* that trigger a run with a `--target-url` override (`create`,
|
|
7552
|
+
* `create-batch`, `run`). States the honest limitation up front: this CLI
|
|
7553
|
+
* probes from wherever it runs, not from the Lambda that executes the
|
|
7554
|
+
* test, so the probe is a heuristic, not a guarantee — hence the full
|
|
7555
|
+
* opt-out.
|
|
7556
|
+
*/
|
|
7557
|
+
const SKIP_PREFLIGHT_HELP = 'skip the pre-charge --target-url reachability probe. The probe runs from this machine, not ' +
|
|
7558
|
+
'from the Lambda that executes the test, so it can occasionally be wrong (e.g. an IP allowlist ' +
|
|
7559
|
+
'that permits the Lambda but not this machine); use this flag when you know better. Zero network ' +
|
|
7560
|
+
'calls when set.';
|
|
7375
7561
|
export function createTestCommand(deps = {}) {
|
|
7376
7562
|
const test = new Command('test').description('Inspect TestSprite tests');
|
|
7377
7563
|
test
|
|
@@ -7439,7 +7625,10 @@ export function createTestCommand(deps = {}) {
|
|
|
7439
7625
|
.option('--run', 'after create, trigger the test. Combine with --wait to block until terminal.', false)
|
|
7440
7626
|
.option('--wait', 'with --run, poll until terminal status', false)
|
|
7441
7627
|
.option('--timeout <s>', 'with --run --wait, max seconds to wait')
|
|
7442
|
-
.option('--target-url <url>', 'with --run, override the project default env URL'
|
|
7628
|
+
.option('--target-url <url>', 'with --run, override the project default env URL. Before triggering, a reachability ' +
|
|
7629
|
+
'preflight refuses obviously-dead targets (DNS failure, connection refused, a 502/503/504 ' +
|
|
7630
|
+
'gateway error) so a doomed run never gets billed — see --skip-preflight.')
|
|
7631
|
+
.option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
|
|
7443
7632
|
.option('--idempotency-key <token>', 'opaque idempotency token (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
|
|
7444
7633
|
.option('--produces <var>', 'BE only: variable name this test captures (repeatable). Drives dependency-aware wave ordering on `test rerun` and `test run --all`.', (val, prev) => [...(prev ?? []), val], [])
|
|
7445
7634
|
.option('--needs <var>', 'BE only: variable name this test consumes (repeatable). Use to declare upstream producer dependencies.', (val, prev) => [...(prev ?? []), val], [])
|
|
@@ -7504,6 +7693,7 @@ export function createTestCommand(deps = {}) {
|
|
|
7504
7693
|
// B2(c): capture before parseTimeoutFlag converts undefined → default.
|
|
7505
7694
|
timeoutIsDefault: cmdOpts.timeout === undefined,
|
|
7506
7695
|
targetUrl: cmdOpts.targetUrl,
|
|
7696
|
+
skipPreflight: cmdOpts.skipPreflight === true,
|
|
7507
7697
|
idempotencyKey: cmdOpts.idempotencyKey,
|
|
7508
7698
|
ignoredFlags: ignored,
|
|
7509
7699
|
}, deps);
|
|
@@ -7525,6 +7715,7 @@ export function createTestCommand(deps = {}) {
|
|
|
7525
7715
|
// B2(c): capture before parseTimeoutFlag converts undefined → default.
|
|
7526
7716
|
timeoutIsDefault: cmdOpts.timeout === undefined,
|
|
7527
7717
|
targetUrl: cmdOpts.targetUrl,
|
|
7718
|
+
skipPreflight: cmdOpts.skipPreflight === true,
|
|
7528
7719
|
// M4 piece-2: BE dependency authoring flags.
|
|
7529
7720
|
// Commander variadic collectors initialise to [] — treat empty array as undefined
|
|
7530
7721
|
// so we don't send an empty array on the wire when no flags were passed.
|
|
@@ -7542,7 +7733,10 @@ export function createTestCommand(deps = {}) {
|
|
|
7542
7733
|
.option('--max-concurrency <n>', 'with --run, max in-flight triggers at once (1-100, default: 50). The server caps run-triggers at 60/min/key; the CLI throttles to 50/min and auto-retries RATE_LIMITED responses client-side — raising this value does not bypass the server cap.')
|
|
7543
7734
|
.option('--wait', 'with --run, poll each run until terminal status', false)
|
|
7544
7735
|
.option('--timeout <s>', 'with --run --wait, per-run max seconds to wait (1-3600, default 600)')
|
|
7545
|
-
.option('--target-url <url>', 'with --run, override the project default env URL for each run'
|
|
7736
|
+
.option('--target-url <url>', 'with --run, override the project default env URL for each run. Before the fan-out, a ' +
|
|
7737
|
+
'reachability preflight refuses an obviously-dead target ONCE for the whole batch (DNS ' +
|
|
7738
|
+
'failure, connection refused, a 502/503/504 gateway error) — see --skip-preflight.')
|
|
7739
|
+
.option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
|
|
7546
7740
|
.option('--idempotency-key <token>', 'opaque idempotency token for the batch create (1-256 ASCII chars). Defaults to a UUIDv4 minted per invocation; pin one yourself for safe retries.')
|
|
7547
7741
|
.addHelpText('after', GLOBAL_OPTS_HINT)
|
|
7548
7742
|
.action(async (cmdOpts, command) => {
|
|
@@ -7555,6 +7749,7 @@ export function createTestCommand(deps = {}) {
|
|
|
7555
7749
|
wait: cmdOpts.wait === true,
|
|
7556
7750
|
timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
|
|
7557
7751
|
targetUrl: cmdOpts.targetUrl,
|
|
7752
|
+
skipPreflight: cmdOpts.skipPreflight === true,
|
|
7558
7753
|
idempotencyKey: cmdOpts.idempotencyKey,
|
|
7559
7754
|
}, deps);
|
|
7560
7755
|
});
|
|
@@ -7763,7 +7958,15 @@ export function createTestCommand(deps = {}) {
|
|
|
7763
7958
|
'\nOn failure/blocked/cancelled, run: testsprite test artifact get <run-id>\n' +
|
|
7764
7959
|
'\nCtrl-C during --wait detaches only (the run keeps executing and billing);\n' +
|
|
7765
7960
|
'stop it for real with: testsprite test cancel <run-id>')
|
|
7766
|
-
.option('--target-url <url>', 'override the project default env URL for this run (http/https only, no localhost/private
|
|
7961
|
+
.option('--target-url <url>', 'override the project default env URL for this run (http/https only, no localhost/private ' +
|
|
7962
|
+
'IPs). Before triggering, a reachability preflight refuses an obviously-dead target (DNS ' +
|
|
7963
|
+
'failure, connection refused, a 502/503/504 gateway error) so a doomed run never gets ' +
|
|
7964
|
+
'billed. This CLI probes from wherever it runs, not from the Lambda that executes the ' +
|
|
7965
|
+
'test, so it is a heuristic, not a guarantee — see --skip-preflight. Note: for a backend ' +
|
|
7966
|
+
'test, --target-url itself is inert (its base URL is baked into its code) — but this bare ' +
|
|
7967
|
+
"`run` command has no way to know a test's type before triggering it, so the preflight " +
|
|
7968
|
+
'still runs and can still refuse; use --skip-preflight if that surprises you.')
|
|
7969
|
+
.option('--skip-preflight', SKIP_PREFLIGHT_HELP, false)
|
|
7767
7970
|
.option('--wait', 'poll until terminal status or --timeout elapses', false)
|
|
7768
7971
|
.option('--timeout <s>', `with --wait, max seconds to wait (1–3600, default ${DEFAULT_RUN_TIMEOUT_SECONDS})`)
|
|
7769
7972
|
.option('--idempotency-key <key>', 'opaque key for safe retries (1–256 chars). Printed to stderr at --debug if auto-generated.')
|
|
@@ -7857,6 +8060,7 @@ export function createTestCommand(deps = {}) {
|
|
|
7857
8060
|
...resolveCommonOptions(command),
|
|
7858
8061
|
testId: testIdArg,
|
|
7859
8062
|
targetUrl: cmdOpts.targetUrl,
|
|
8063
|
+
skipPreflight: cmdOpts.skipPreflight === true,
|
|
7860
8064
|
wait: cmdOpts.wait === true,
|
|
7861
8065
|
timeoutSeconds: parseTimeoutFlag(cmdOpts.timeout, 'timeout'),
|
|
7862
8066
|
// B2(c): tell runTestRun whether --timeout was explicitly provided.
|