diff --git a/README.md b/README.md index 96bbf8e..e909943 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,14 @@ node dist/bin.js run --model --prompt "Explain webhooks" --max-tokens That command explicitly makes a potentially billable request. The library equivalent is `runStreamCheck({ apiKey, model, prompt, signal, onText })`. `npm run example:live -- ` runs the live TypeScript example. Automated verification never runs either live entry point. +From a source checkout, explicitly verify interruption handling with three bounded live requests: + +```sh +npm run test:live:interruptions -- --live --env-file=.env +``` + +Omit `--env-file` when `OPENROUTER_API_KEY` is already in the environment. This manual command uses `openai/gpt-4.1-nano`, up to 128 output tokens and a 30-second deadline per request, with no retries. After decoded text arrives, it separately cancels, injects a transport read error, and stalls local delivery until the deadline. It checks exact text preservation and the shared CLI exit mapping, then writes evidence under ignored `.work/live-interruptions/`. It exits 0 only when every case passes; it does not run the production CLI subprocess or physical Ctrl+C. The command refuses to run when `CI` is set and is excluded from `npm run check` and the CI workflow. [Manual interruption runbook](docs/testing-runbook.md#manual-live-interruption-checks). + ## Results and completion | Outcome | Meaning | Default CLI exit | @@ -156,4 +164,6 @@ The full check covers types, library/CLI tests, release checks, and a consumer o CI runs **Windows/Ubuntu × Node 22.12.0/24**. [View actual runs](https://github.com/dannymitchelldev/streamcheck/actions/workflows/ci.yml?query=branch%3Amain); release notes link the exact validated commit. macOS, live provider behavior, and physical console Ctrl+C are not established by this matrix. +A separate [live OpenRouter smoke check](docs/verification/live-provider-2026-11-12.json) passed on 2026-11-12 with `openai/gpt-4.1-nano`, StreamCheck v0.1.1, and Windows / Node 24.18.0: HTTP 200, exact marker text, normal stop, and CLI exit 0. [Three live-stream fault checks](docs/verification/live-interruptions-2026-11-12.json) also passed on that model/platform: caller cancellation, locally injected transport failure, and a locally stalled deadline all retained their exact received text. The latter checks use the library and shared CLI exit mapper; production-bin subprocess behavior, physical console Ctrl+C, naturally occurring upstream errors, and sustained reliability remain separate verification boundaries. [Reproduction steps](docs/testing-runbook.md#manual-live-interruption-checks). + Built with Codex from a reviewed contract, with a separate AI implementation review and reproduced corrections. Human implementation review is not claimed. The [engineering record](docs/engineering-log.md) separates those stages; the [testing runbook](docs/testing-runbook.md) documents reproducible verification. [Contributions](CONTRIBUTING.md) are welcome under [MIT](LICENSE). diff --git a/docs/engineering-log.md b/docs/engineering-log.md index e1f8232..3ef1709 100644 --- a/docs/engineering-log.md +++ b/docs/engineering-log.md @@ -30,7 +30,8 @@ AI-assisted implementation from an explicitly reviewed, bounded design. Product | Packed package / fresh consumer | Passed locally, including offline cache-only installation | | Typed examples | Both compile; offline example executed; live example not executed | | Windows/Ubuntu, Node 22.12.0/24 GitHub Actions | [Current workflow results](https://github.com/dannymitchelldev/streamcheck/actions/workflows/ci.yml?query=branch%3Amain); release notes identify the validated commit | -| Live OpenRouter integration | Not run; offline SDK fixtures only | +| Live OpenRouter integration | One bounded v0.1.1 CLI smoke passed on 2026-11-12: Windows / Node 24.18.0 / `openai/gpt-4.1-nano`; [receipt](verification/live-provider-2026-11-12.json) | +| Live text with injected local faults | Three manual library cases passed on 2026-11-12: caller abort, transport read failure, and stalled deadline; [receipt](verification/live-interruptions-2026-11-12.json) | | SIGINT handling | Portable subprocess event harness passed; physical Windows console Ctrl+C unverified | ## Reviews @@ -49,7 +50,7 @@ The two initially Minor findings were treated as contract-impacting for this dia ## Remaining verification boundaries -The original local evidence covered Windows / Node 24.18.0. The release workflow records the additional platform/runtime evidence at its actual commit. Live provider behavior, macOS, physical console Ctrl+C, and human implementation review remain unverified. The intentionally accepted SDK trailing-frame blind spot remains documented. +The original local evidence covered Windows / Node 24.18.0. The release workflow records the additional platform/runtime evidence at its actual commit. Later live checks verified one successful completion and three locally induced fault paths on the recorded model/platform. Naturally occurring upstream provider failures, macOS, physical console Ctrl+C, and human implementation review remain unverified. The intentionally accepted SDK trailing-frame blind spot remains documented. ## Publication checks @@ -72,4 +73,28 @@ CLI test subprocesses now preload a provider-fetch guard. The patch changes no l Independent patch review caught a gap in Headers-only validation: SOH, vertical tab, and DEL are accepted by Headers but rejected by the Node transport. Four additional library/CLI cases were observed failing before adding Node's HTTP field-value validation after header normalization. A separate control preserves the SDK's existing trailing-whitespace normalization. The reviewer also caught a missing fetch guard on the SIGINT subprocess; it now uses the same preload as the other CLI tests. -All 14 targeted regression/control checks passed after these corrections. Final local `npm run check` passed type checks, build, **108/108 tests**, and the fresh packed-consumer check on Windows / Node 24.18.0. Independent AI patch re-review confirmed both review findings resolved, with no remaining runtime findings; additional offline probes covered malformed headers, normalization, genuine connection failure, callback races, and built-CLI JSON/exit codes. Release notes identify the final exact-commit CI run and archive verification. Human implementation review, live providers, macOS, and physical console Ctrl+C remain unverified. +All 14 targeted regression/control checks passed after these corrections. Final local `npm run check` passed type checks, build, **108/108 tests**, and the fresh packed-consumer check on Windows / Node 24.18.0. Independent AI patch re-review confirmed both review findings resolved, with no remaining runtime findings; additional offline probes covered malformed headers, normalization, genuine connection failure, callback races, and built-CLI JSON/exit codes. Release notes identify the final exact-commit CI run and archive verification. Human implementation review, live providers, macOS, and physical console Ctrl+C were outside that patch validation. The live smoke below is separate evidence. + +## v0.1.1 live provider smoke + +On 2026-11-12, the built CLI at `d9795dfb0cdc0fda6c37f887c49bb264d6179286` made one live OpenRouter invocation using `openai/gpt-4.1-nano`, a public marker prompt, 32 maximum output tokens, and a 30,000 ms deadline. The SDK retry strategy remained `none`; no transport fixture or automatic rerun was used. The offline check passed before the invocation on the same runtime source: types, build, **108/108 tests**, and the packed consumer. + +The live CLI exited 0, emitted one schema-version-1 JSON result and no stderr, observed HTTP 200, and returned exactly `STREAMCHECK_OK` with `finishReason: stop`, `partialOutput: false`, no warnings, and no error diagnostic. First text arrived at **670.113 ms**; accepted completion was at **842.169 ms**. All 15 evidence assertions passed. These are observations from one request, not a latency benchmark. + +The [receipt](verification/live-provider-2026-11-12.json) records the source commit, runtime, SDK, request bounds, result, output checksum, and assertions without credentials or account metadata. The [runbook](testing-runbook.md#live-openrouter-smoke-check) describes reproduction. This verifies successful live completion for that model/platform combination; live interruption/rate-limit/cancellation handling, sustained reliability, upstream provider identity, and billed cost were not measured. SDK-observed completion retains the documented trailing-frame limitation. + +## Manual interruption harness + +The source-checkout command `npm run test:live:interruptions -- --live` exercises caller cancellation, transport read failure, and a stalled deadline after SDK-decoded nonempty text. It uses the existing transport seam and unchanged native response bytes; production source, public API, dependencies, and CI workflow are unchanged. The script requires explicit live opt-in, rejects CI, permits one native request per case, runs cases sequentially, and saves incremental nonsecret receipts. Per-case CLI codes come from the shared production mapper; the production CLI binary and physical console Ctrl+C are outside this harness. + +Eight initial offline harness cases failed before implementation, then passed through the real built runner and pinned SDK with synthetic transport only. A Windows preload-path failure was corrected by using file URLs. Independent read-only AI review examined request gates, buffered SSE events, text preservation, pending reads, fragmented UTF-8, cleanup, and evidence scope. It found one minor classification issue: already-buffered completion could make a stall experiment report failed rather than inconclusive. A new regression was observed failing before the correction and passing afterward; the reviewer confirmed the finding resolved with no additional correctness findings. The actual completion result and failed assertions remain visible, and inconclusive evidence never passes the overall command. + +The final offline check passed type checks, build, **117/117 tests**, and the packed-package consumer. The implementation was committed as `9490d5311ccf2abb442f39516ca9169109dd1ec8` before live execution. A subsequent explicit invocation made exactly three live requests on Windows / Node 24.18.0 / SDK 1.5.91 / `openai/gpt-4.1-nano`; all **33 live evidence assertions passed**, and the manual command exited 0. + +| Local fault | Actual result | Retained text | Elapsed | Shared CLI mapping | +| --- | --- | --- | ---: | ---: | +| Caller abort after text | `cancelled`, reason `caller` | `Sure` | 789.170 ms | 130 | +| Transport read error after text | `interrupted`, `network` / `stream` | `I` | 690.057 ms | 3 | +| Stalled local body until deadline | `interrupted`, `timeout` / `stream` | `I` | 30,003.504 ms | 124 | + +Each case observed HTTP 200, retained exactly the text delivered through callbacks, set `partialOutput: true`, and completed upstream reader cancellation. The [receipt](verification/live-interruptions-2026-11-12.json) records actual results, failed-or-passed checks, injection timing, source/runtime checksums, and request bounds. The nominal deadline can be observed slightly late because timer execution is scheduled by the event loop. These results establish live client behavior under deliberate local faults; they do not establish a natural upstream error, physical console Ctrl+C, production-bin subprocess behavior, billing cessation, or long-term reliability. diff --git a/docs/testing-runbook.md b/docs/testing-runbook.md index fbde17a..e592cc4 100644 --- a/docs/testing-runbook.md +++ b/docs/testing-runbook.md @@ -58,6 +58,7 @@ Tests release timers/readers/listeners. The package-consumer check removes only - When changing argument parsing, cover missing option values before standalone --json, literal --prompt=--json, and the -- terminator. Strict and permissive Node argument parsing interpret missing values differently. - SDK fixtures must not let another choice's finish certify choice zero. Unexpected/duplicate choice entries are protocol failures; already retained text must survive. - A cold npm cache exposed an old ENOTCACHED failure: npm ci cached package files without all registry manifests needed by a separate --offline install. Consumer dependency installation now permits npm access. Runtime provider access remains blocked, and installed CLI resolution remains offline. +- Cancellation fixtures must match native fetch signal precedence: `init?.signal ?? request.signal`. SDK 1.5.91 supplies a strongly retained signal through `RequestInit`; observing only the request's weakly linked signal can hang after Node garbage collection. This reproduced an intermittent 10-second compatibility-test timeout without any provider traffic; the fixture now observes the effective signal. ## Release artifact verification @@ -152,6 +153,130 @@ No service, credentials, or persistent output is created. Generated build and ch - Use a combined text/finish frame. A later finish frame does not reproduce the callback metadata defect. - Keep finish metadata separate from accepting normal completion: later observable failures while draining must still win. +## Live OpenRouter smoke check + +Last verified: 2026-11-12. StreamCheck v0.1.1 at `d9795dfb0cdc0fda6c37f887c49bb264d6179286`, Windows / Node 24.18.0 / SDK 1.5.91. One `openai/gpt-4.1-nano` invocation passed all 15 evidence assertions: exit 0, observed HTTP 200, exact `STREAMCHECK_OK` text, `stop`, no warnings, and no stderr. First text arrived at 670.113 ms; accepted completion was at 842.169 ms. Limits were 32 output tokens / 30,000 ms, without SDK retries. [Machine-readable receipt](verification/live-provider-2026-11-12.json). + +The offline `npm run check` also passed on this source commit before the live invocation: type checks, build, 108 tests, and the packed-package consumer. Documentation-only changes record the live result; no runtime code or dependency changed. + +### Purpose + +Verify one real text-stream completion through the built CLI and pinned SDK. This is a separate, explicitly invoked check; automated tests continue to use fixtures. + +### Setup / Seed Data + +- Install the locked dependencies and build with `npm run build`. +- Supply `OPENROUTER_API_KEY` through the process environment. An ignored `.env` file can instead be loaded with Node's `--env-file=.env` option before `dist/bin.js`; the CLI does not load dotenv files itself. +- Confirm the selected model is available in the current [OpenRouter model catalog](https://openrouter.ai/api/v1/models). The small smoke prompt contains no private data. + +### Safe Actions + +Offline build/check commands and the public model-catalog GET do not create a generation. Inspect credential presence without printing its value. + +### Destructive / Mutating Actions + +The live command sends a potentially billable generation request. Run it once, with 32 maximum output tokens and a 30-second deadline. StreamCheck disables SDK retries; do not automatically rerun a failed or interrupted generation. Local cancellation does not establish that provider processing or billing stopped. + +### Steps + +1. Run the offline verification first. +2. Confirm the credential is available without logging it or putting it in command-line arguments. +3. Run the command below once and retain its JSON, stderr, and process exit status in an ignored `.work` directory. +4. Check that stdout contains exactly one JSON result, exit status is 0, `schemaVersion` is 1, `source` is `live`, `model` matches the request, `outcome` is `success`, `httpStatus` is 200, and `partialOutput` is false. +5. Check the received text against the requested marker, `finishReason` is `stop`, warnings are empty, and finite timings satisfy `0 <= firstTokenMs <= elapsedMs <= 30000`. +6. Record the commit, runtime, model, request limits, result, and verification date. Keep credentials, account metadata, and private prompts out of shared evidence. + +### Verification Commands + +```sh +npm run check +node dist/bin.js run --model openai/gpt-4.1-nano --prompt "Return exactly STREAMCHECK_OK and nothing else." --max-tokens 32 --timeout 30000 --json +``` + +For an ignored `.env` file, use `node --env-file=.env dist/bin.js run` with the same options. Do not run both variants: each creates a separate generation. + +Expected: exit 0 and one live success result with the marker text, observed HTTP 200, a normal stop, no warnings, and populated timing fields. A different marker is a model-response mismatch; inspect the saved result rather than silently making another request. + +### Cleanup + +Keep nonsecret evidence needed for review. Credential files and raw scratch output stay ignored; do not commit or publish API keys. The CLI installs no service and persists no output itself. + +### Troubleshooting Notes + +- Missing or malformed credentials are setup diagnostics and do not verify provider connectivity. HTTP 401, 402, and 429 require inspecting credential validity, available credit, or rate limits respectively. +- Record failed/interrupted outcomes as observed. A timeout, transport failure, or protocol rejection is not a passing provider check. +- One successful generation establishes the observed model/platform combination at that time. Provider interruption recovery, rate limits, physical console Ctrl+C, other operating systems, and sustained reliability require separate evidence. +- Completion remains SDK-observed. The SDK's documented trailing-frame limitation still applies. + +## Manual live interruption checks + +Offline harness verified 2026-11-12: all 9 targeted tests passed, followed by `npm run check` with type checks, build, **117 tests**, and the packed-package consumer on Windows / Node 24.18.0. Independent review confirmed the buffered-completion classification correction. Live results are recorded separately from this synthetic verification. + +Live verified 2026-11-12 at clean implementation commit `9490d5311ccf2abb442f39516ca9169109dd1ec8`, Windows / Node 24.18.0 / SDK 1.5.91 / `openai/gpt-4.1-nano`. Exactly three requests passed all **33 assertions**, with HTTP 200 and exact callback-text preservation in every case. Cancellation retained `Sure` at 789.170 ms; transport failure retained `I` at 690.057 ms; the stalled deadline retained `I` at 30,003.504 ms. The whole command exited 0. Per-case shared CLI mappings were 130, 3, and 124; no production CLI subprocess was executed. [Machine-readable receipt](verification/live-interruptions-2026-11-12.json). + +### Purpose + +Verify three interruption paths after receiving genuine live text: caller cancellation, a locally injected transport read error, and a locally stalled body that reaches the existing overall deadline. These are deliberate local faults, not naturally occurring upstream provider errors. + +### Setup / Seed Data + +- Use a source checkout with locked dependencies installed. The npm command builds the current runtime before execution; the manual script is not included in the release archive. +- Supply `OPENROUTER_API_KEY` in the environment or pass an ignored credential file with `--env-file=path`. Credential values never belong in shell arguments. +- The command requires `--live` and refuses execution whenever `CI` is nonempty, including when an environment file sets it. `--help` is safe in CI. +- Requests use `openai/gpt-4.1-nano`, a fixed public number-list prompt, at most 128 output tokens, and a 30,000 ms deadline per case. Confirm the model remains available before running. + +### Safe Actions + +`npm run test:live:interruptions -- --help` and the regular `npm run check` do not contact a provider. Normal tests exercise the manual harness through in-process synthetic HTTP/SSE responses, the real built runner, and the pinned SDK. The manual live entry point is absent from normal CI. + +### Destructive / Mutating Actions + +An explicit live invocation sends exactly one generation request per case, sequentially, without automatic retries. The fetch wrapper refuses a second attempted request within a case before it reaches native fetch. A local reader cancellation is attempted after each fault; this does not establish that provider processing or billing stopped. Each invocation creates its own ignored evidence directory. + +### Steps + +1. Run the offline check and review the current source commit. +2. Supply the credential without printing it. Use the command below once; each invocation can create three billable generations. +3. Wait for `cancel`, `transport`, and `deadline` results. The stall case normally uses nearly its entire 30-second deadline. Do not automatically repeat failures or inconclusive cases. +4. Inspect the saved receipt. Every case must show one request, observed HTTP 200, injection after decoded nonempty text, exact equality between received callback text and result text, `partialOutput: true`, finite ordered timing values, the expected terminal outcome/diagnostic, and upstream reader cancellation. +5. Confirm the per-case mapped CLI codes below. The harness calls the production mapper; these are not production CLI subprocess exit observations. The overall manual command exits 0 only if all cases pass, 1 for failed/inconclusive evidence, and 2 for setup/harness failure. +6. Retain the receipt with its source commit, tracked-diff checksum, harness and built-file checksums, runtime, request bounds, and fault labels. Shared evidence must omit credentials and account metadata. + +| Case | Expected outcome | Diagnostic | Mapped CLI exit | +| --- | --- | --- | ---: | +| `cancel` | `cancelled` | `reason: caller` | 130 | +| `transport` | `interrupted` | `network`, phase `stream` | 3 | +| `deadline` | `interrupted` | `timeout`, phase `stream` | 124 | + +### Verification Commands + +```sh +npm run check +npm run test:live:interruptions -- --live --env-file=.env +``` + +For an already configured process environment, omit `--env-file=.env`. These are alternatives, not two live steps. To verify only the harness offline: + +```sh +npm run build +npm exec --offline -- vitest run tests/live-interruptions.test.ts +``` + +Expected live output contains `cancel: PASSED`, `transport: PASSED`, `deadline: PASSED`, and the receipt path under `.work/live-interruptions/`. The production CLI and library contracts are unchanged. + +### Cleanup + +The harness cancels/releases its upstream reader and removes its abort listener. The core runner owns deadline, SDK reader, and caller listener cleanup. No background service is installed. Keep the required evidence; scratch output and credential files remain ignored. + +### Troubleshooting Notes + +- A response that ends before fault injection, HTTP 200 without text, or an already-buffered normal completion that wins over a local transport/stall fault is inconclusive and never a passing interruption. The actual result is preserved. Pre-stream authentication/provider failures are recorded without retries. +- Triggering from decoded text avoids relying on a guessed first-token delay. Raw response bytes are passed unchanged to the SDK; the harness does not implement another SSE parser. +- The stall case cancels its upstream reader immediately but deliberately holds local delivery open until the runner's deadline. This tests local timeout handling, not an upstream provider's timeout. +- A normal `length` finish is success with a warning, not an interruption test. An observed finish reason can remain present on an interrupted result because it is provisional until SDK exhaustion. +- Physical console Ctrl+C, production-bin execution, natural upstream errors, billing cessation, and other models/platforms remain separate evidence boundaries. +- On Windows, Node `--import` preload paths must be file URLs; offline subprocess tests use `pathToFileURL` rather than raw drive-letter paths. + ## Recording Last verified: 2026-11-11. diff --git a/docs/verification/live-interruptions-2026-11-12.json b/docs/verification/live-interruptions-2026-11-12.json new file mode 100644 index 0000000..78a047d --- /dev/null +++ b/docs/verification/live-interruptions-2026-11-12.json @@ -0,0 +1,167 @@ +{ + "evidenceVersion": 1, + "kind": "live-stream-with-locally-injected-faults", + "startedAtUtc": "2026-11-12T21:29:10.685Z", + "completedAtUtc": "2026-11-12T21:29:42.252Z", + "commit": "9490d5311ccf2abb442f39516ca9169109dd1ec8", + "trackedDiffSha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "runtime": { + "nodeVersion": "v24.18.0", + "platform": "win32", + "harnessSha256": "441cbec5c1d8b0ddd10378696370139633f280124733e65ffce958b1582e6cde", + "packageVersion": "0.1.1", + "sdkVersion": "1.5.91", + "builtFileSha256": { + "runner": "802273c617cc8b053dd6ed2a9927abd9acde3a34447ca5a765f7525bf5f253e8", + "sdk": "a9d59dc3c75c888fe00374302d852bda3018ab6b631e8aacb9f612879e5d62f4", + "cli": "3afe3c1a6abadf52baa59585bce0241d215eed079095e9551e047e8b0200d63c", + "index": "bfc875bde9a787871b614d76f972b8be7468d075c19ddaac1dc936bd250bcfc2" + } + }, + "request": { + "model": "openai/gpt-4.1-nano", + "prompt": "Write the numbers from 1 to 1000, one number per line. Continue until the output limit.", + "maxTokens": 128, + "timeoutMs": 30000, + "automaticRetries": false + }, + "cliExitEvidence": "Shared production exit mapper only; production CLI subprocess and physical Ctrl+C are not exercised.", + "scope": "Genuine live text with deliberate local faults; not natural upstream provider failures or proof that billing stopped.", + "cases": [ + { + "scenario": "cancel", + "faultOrigin": "local-test-harness", + "verdict": "passed", + "injection": { + "fired": true, + "textLengthAtTrigger": 4, + "elapsedMs": 789.2359000000001 + }, + "requestCount": 1, + "upstreamReaderCancelled": true, + "receivedText": "Sure", + "textCallbacks": 1, + "cliExitCode": 130, + "result": { + "schemaVersion": 1, + "source": "live", + "model": "openai/gpt-4.1-nano", + "text": "Sure", + "partialOutput": true, + "firstTokenMs": 788.9300000000001, + "elapsedMs": 789.1703, + "httpStatus": 200, + "finishReason": null, + "warnings": [], + "outcome": "cancelled", + "reason": "caller" + }, + "checks": { + "oneRequest": true, + "observedHttp200": true, + "faultAfterText": true, + "exactTextPreserved": true, + "partialOutput": true, + "expectedOutcome": true, + "expectedDiagnostic": true, + "expectedCliExitMapping": true, + "timing": true, + "upstreamReaderCancelled": true, + "callerSignal": true + } + }, + { + "scenario": "transport", + "faultOrigin": "local-test-harness", + "verdict": "passed", + "injection": { + "fired": true, + "textLengthAtTrigger": 1, + "elapsedMs": 689.6415999999999 + }, + "requestCount": 1, + "upstreamReaderCancelled": true, + "receivedText": "I", + "textCallbacks": 1, + "cliExitCode": 3, + "result": { + "schemaVersion": 1, + "source": "live", + "model": "openai/gpt-4.1-nano", + "text": "I", + "partialOutput": true, + "firstTokenMs": 689.6205, + "elapsedMs": 690.0569, + "httpStatus": 200, + "finishReason": null, + "warnings": [], + "outcome": "interrupted", + "error": { + "kind": "network", + "phase": "stream", + "message": "Stream connection interrupted" + } + }, + "checks": { + "oneRequest": true, + "observedHttp200": true, + "faultAfterText": true, + "exactTextPreserved": true, + "partialOutput": true, + "expectedOutcome": true, + "expectedDiagnostic": true, + "expectedCliExitMapping": true, + "timing": true, + "upstreamReaderCancelled": true, + "callerSignal": true + } + }, + { + "scenario": "deadline", + "faultOrigin": "local-test-harness", + "verdict": "passed", + "injection": { + "fired": true, + "textLengthAtTrigger": 1, + "elapsedMs": 674.0177999999996 + }, + "requestCount": 1, + "upstreamReaderCancelled": true, + "receivedText": "I", + "textCallbacks": 1, + "cliExitCode": 124, + "result": { + "schemaVersion": 1, + "source": "live", + "model": "openai/gpt-4.1-nano", + "text": "I", + "partialOutput": true, + "firstTokenMs": 674.0031999999997, + "elapsedMs": 30003.504, + "httpStatus": 200, + "finishReason": null, + "warnings": [], + "outcome": "interrupted", + "error": { + "kind": "timeout", + "phase": "stream", + "message": "Overall streaming deadline exceeded" + } + }, + "checks": { + "oneRequest": true, + "observedHttp200": true, + "faultAfterText": true, + "exactTextPreserved": true, + "partialOutput": true, + "expectedOutcome": true, + "expectedDiagnostic": true, + "expectedCliExitMapping": true, + "timing": true, + "upstreamReaderCancelled": true, + "callerSignal": true + } + } + ], + "verdict": "passed" +} diff --git a/docs/verification/live-provider-2026-11-12.json b/docs/verification/live-provider-2026-11-12.json new file mode 100644 index 0000000..7a6f075 --- /dev/null +++ b/docs/verification/live-provider-2026-11-12.json @@ -0,0 +1,67 @@ +{ + "evidenceVersion": 1, + "description": "One bounded live CLI completion through OpenRouter, without injected transport or automatic SDK retries.", + "request": { + "requestedAtUtc": "2026-11-12T20:57:07.3897157+00:00", + "completedAtUtc": "2026-11-12T20:57:10.3355073+00:00", + "commit": "d9795dfb0cdc0fda6c37f887c49bb264d6179286", + "packageVersion": "0.1.1", + "sdkVersion": "1.5.91", + "platform": "win32", + "nodeVersion": "v24.18.0", + "model": "openai/gpt-4.1-nano", + "prompt": "Return exactly STREAMCHECK_OK and nothing else.", + "maxTokens": 32, + "timeoutMs": 30000, + "cliInvocations": 1, + "exitCode": 0 + }, + "result": { + "schemaVersion": 1, + "source": "live", + "model": "openai/gpt-4.1-nano", + "text": "STREAMCHECK_OK", + "partialOutput": false, + "firstTokenMs": 670.1125999999999, + "elapsedMs": 842.1691000000001, + "httpStatus": 200, + "finishReason": "stop", + "warnings": [], + "outcome": "success" + }, + "verification": { + "verifiedAtUtc": "2026-11-12T20:57:38.677Z", + "passed": true, + "checks": [ + "CLI exit 0", + "Exactly one JSON result", + "No stderr output", + "Schema version 1", + "Live source", + "Requested model", + "Successful outcome", + "Observed HTTP 200", + "Exact marker text", + "Normal stop", + "No partial output", + "No warnings", + "No error diagnostic", + "Finite first-token and elapsed timings within deadline", + "One bounded CLI invocation" + ], + "stdoutSha256": "6fc90b206e32c08208c21bbcea22d52ab3d599b1bbe224a8afa69b4119c7deb1", + "stderrBytes": 0 + }, + "scope": { + "established": [ + "Built v0.1.1 CLI, pinned SDK, and live OpenRouter integration on the recorded platform/model", + "Observed HTTP status, exact text, normal finish, timing, JSON output, and exit status" + ], + "notEstablished": [ + "Live provider interruption, rate-limit, or cancellation behavior", + "Other models, operating systems, or sustained reliability", + "Complete transport beyond SDK-observed completion", + "Billed cost or specific upstream provider identity" + ] + } +} diff --git a/package.json b/package.json index e765e6d..b2e5bea 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "test": "vitest run", "test:sdk": "vitest run tests/sdk-boundary.test.ts", "test:package": "node scripts/package-smoke.mjs", + "test:live:interruptions": "npm run build && node scripts/live-interruptions.mjs", "check": "npm run typecheck && npm test && npm run test:package", "demo": "node dist/bin.js demo interrupted", "record:demo": "npm run build && node scripts/record-demo.mjs", diff --git a/scripts/live-interruptions.mjs b/scripts/live-interruptions.mjs new file mode 100644 index 0000000..f96e3f7 --- /dev/null +++ b/scripts/live-interruptions.mjs @@ -0,0 +1,210 @@ +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { loadEnvFile } from 'node:process'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { parseArgs } from 'node:util'; +import { exitCodeFor } from '../dist/cli.js'; +import { runWithTransport } from '../dist/runner.js'; + +const root = fileURLToPath(new URL('..', import.meta.url)); +const model = 'openai/gpt-4.1-nano'; +const prompt = 'Write the numbers from 1 to 1000, one number per line. Continue until the output limit.'; +const maxTokens = 128; +const timeoutMs = 30_000; +const expected = { + cancel: { outcome: 'cancelled', kind: null, exit: 130 }, + transport: { outcome: 'interrupted', kind: 'network', exit: 3 }, + deadline: { outcome: 'interrupted', kind: 'timeout', exit: 124 }, +}; + +/** A test-only response wrapper, forwarding native bytes without parsing SSE. */ +export async function runInterruptionCase(scenario, options) { + if (!Object.hasOwn(expected, scenario)) throw new Error('Unknown interruption scenario'); + const nativeFetch = options.fetcher ?? globalThis.fetch; + const caller = new AbortController(); + const injection = { fired: false, textLengthAtTrigger: 0, elapsedMs: null }; + const started = performance.now(); + let receivedText = ''; + let textCallbacks = 0; + let requestCount = 0; + let observedStatus = null; + let reader; + let body; + let closed = false; + let frozen = false; + let cancelPromise; + let upstreamReaderCancelled = false; + let detach = () => {}; + + const cancelUpstream = () => { + if (reader && !cancelPromise) { + cancelPromise = reader.cancel().then(() => { upstreamReaderCancelled = true; }, () => {}) + .finally(() => { reader.releaseLock(); }); + } + return cancelPromise; + }; + const failBody = error => { + if (!closed && body) { closed = true; body.error(error); } + detach(); + void cancelUpstream(); + }; + const fetcher = async (input, init) => { + // A second attempted request is stopped before native fetch, even if a + // future SDK configuration accidentally re-enables retries. + requestCount++; + if (requestCount !== 1 || !(input instanceof Request) || input.method !== 'POST' || input.url !== 'https://openrouter.ai/api/v1/chat/completions') { + throw new TypeError('Unexpected manual-check request'); + } + const response = await nativeFetch(input, init); + observedStatus = response.status; + if (!response.ok || !response.body || !response.headers.get('content-type')?.toLowerCase().includes('text/event-stream')) return response; + reader = response.body.getReader(); + const onAbort = () => failBody(new DOMException('Manual check transport aborted', 'AbortError')); + const wrapped = new ReadableStream({ + start(controller) { body = controller; }, + async pull(controller) { + if (frozen || closed) return; + try { + const next = await reader.read(); + if (frozen || closed) return; + if (next.done) { closed = true; detach(); controller.close(); } + else controller.enqueue(next.value); + } catch (error) { failBody(error); } + }, + cancel() { closed = true; detach(); return cancelUpstream(); }, + }, { highWaterMark: 0 }); + input.signal.addEventListener('abort', onAbort, { once: true }); + detach = () => input.signal.removeEventListener('abort', onAbort); + if (input.signal.aborted) onAbort(); + return new Response(wrapped, { status: response.status, statusText: response.statusText, headers: response.headers }); + }; + + let result; + try { + result = await runWithTransport({ + apiKey: options.apiKey, model: options.model ?? model, prompt, + maxTokens, timeoutMs: options.timeoutMs ?? timeoutMs, signal: caller.signal, + onText(delta) { + receivedText += delta; + textCallbacks++; + if (injection.fired || textCallbacks !== 1) return; + // No fault can be claimed after the wrapped body has already ended. + if (scenario !== 'cancel' && (closed || !body)) return; + injection.fired = true; + injection.textLengthAtTrigger = receivedText.length; + injection.elapsedMs = performance.now() - started; + if (scenario === 'cancel') caller.abort(); + else { + frozen = true; + if (scenario === 'transport') failBody(new TypeError('Locally injected transport read failure')); + // For deadline, stop upstream work now, but hold the local body open + // until the runner's existing overall deadline aborts its transport. + else void cancelUpstream(); + } + }, + }, fetcher); + } finally { + detach(); + await cancelUpstream(); + } + const want = expected[scenario]; + const cliExitCode = exitCodeFor(result); + const checks = { + oneRequest: requestCount === 1, + observedHttp200: observedStatus === 200 && result.httpStatus === 200, + faultAfterText: injection.fired && injection.textLengthAtTrigger > 0, + exactTextPreserved: receivedText.length > 0 && result.text === receivedText, + partialOutput: result.partialOutput === true, + expectedOutcome: result.outcome === want.outcome, + expectedDiagnostic: want.kind === null ? result.reason === 'caller' && !result.error : result.error?.kind === want.kind && result.error.phase === 'stream', + expectedCliExitMapping: cliExitCode === want.exit, + timing: Number.isFinite(result.firstTokenMs) && result.firstTokenMs >= 0 && Number.isFinite(result.elapsedMs) && result.elapsedMs >= result.firstTokenMs, + upstreamReaderCancelled, + callerSignal: caller.signal.aborted === (scenario === 'cancel'), + }; + // The SDK can already hold a complete terminal event when local delivery is + // frozen. Preserve that success, but never count it as an interruption pass. + const completionWon = scenario !== 'cancel' && result.outcome === 'success'; + const inconclusive = observedStatus === 200 && (!injection.fired || completionWon); + const verdict = Object.values(checks).every(Boolean) ? 'passed' : inconclusive ? 'inconclusive' : 'failed'; + return { + scenario, faultOrigin: 'local-test-harness', verdict, injection, + requestCount, upstreamReaderCancelled, receivedText, textCallbacks, + cliExitCode, result, checks, + }; +} + +export async function main(args = process.argv.slice(2)) { + let values; + try { + ({ values } = parseArgs({ args, options: { + live: { type: 'boolean' }, help: { type: 'boolean' }, 'env-file': { type: 'string' }, + }, strict: true, allowPositionals: false })); + } catch { throw new Error('Invalid options; use --help'); } + if (values.help) { + console.log('Usage: npm run test:live:interruptions -- --live [--env-file=path]\nRuns three potentially billable requests, sequentially, outside CI.\nThe command exits 0 only when all cases pass; per-case CLI codes are mapped, not subprocess exits.'); + return 0; + } + if (!values.live) throw new Error('Explicit --live is required; no requests sent'); + if (process.env.CI) throw new Error('Live interruption checks are disabled when CI is set; no requests sent'); + if (values['env-file']) { + try { loadEnvFile(values['env-file']); } + catch { throw new Error('Could not load the requested environment file; no requests sent'); } + } + if (process.env.CI) throw new Error('Live interruption checks are disabled when CI is set; no requests sent'); + const apiKey = process.env.OPENROUTER_API_KEY; + if (!apiKey?.trim()) throw new Error('OPENROUTER_API_KEY is required; no requests sent'); + + const hash = value => createHash('sha256').update(value).digest('hex'); + const git = args => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); + const report = { + evidenceVersion: 1, kind: 'live-stream-with-locally-injected-faults', + startedAtUtc: new Date().toISOString(), completedAtUtc: null, + commit: git(['rev-parse', 'HEAD']), trackedDiffSha256: hash(git(['diff', 'HEAD'])), + runtime: { + nodeVersion: process.version, platform: process.platform, + harnessSha256: hash(readFileSync(fileURLToPath(import.meta.url))), + packageVersion: JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).version, + sdkVersion: JSON.parse(readFileSync(join(root, 'node_modules/@openrouter/sdk/package.json'), 'utf8')).version, + builtFileSha256: Object.fromEntries(['runner', 'sdk', 'cli', 'index'].map(name => [name, hash(readFileSync(join(root, `dist/${name}.js`)))])), + }, + request: { model, prompt, maxTokens, timeoutMs, automaticRetries: false }, + cliExitEvidence: 'Shared production exit mapper only; production CLI subprocess and physical Ctrl+C are not exercised.', + scope: 'Genuine live text with deliberate local faults; not natural upstream provider failures or proof that billing stopped.', + cases: [], verdict: 'incomplete', + }; + const base = join(root, '.work/live-interruptions'); + mkdirSync(base, { recursive: true }); + const directory = mkdtempSync(join(base, new Date().toISOString().replace(/[:.]/g, '-') + '-')); + const target = join(directory, 'receipt.json'); + const save = () => { + const content = JSON.stringify(report, null, 2) + '\n'; + if (content.includes(apiKey)) throw new Error('Credential-disclosure guard failed; output withheld'); + writeFileSync(target, content); + }; + save(); + console.log('Running three bounded live interruption checks (128 output tokens / 30000 ms per request).'); + for (const scenario of Object.keys(expected)) { + const item = await runInterruptionCase(scenario, { apiKey }); + report.cases.push(item); + save(); + console.log(`${scenario}: ${item.verdict.toUpperCase()} (outcome=${item.result.outcome}, mapped CLI exit=${item.cliExitCode})`); + } + report.completedAtUtc = new Date().toISOString(); + report.verdict = report.cases.every(item => item.verdict === 'passed') ? 'passed' : 'failed'; + save(); + console.log(`Evidence: ${target}`); + return report.verdict === 'passed' ? 0 : 1; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + try { process.exitCode = await main(); } + catch (error) { + // Setup messages are authored above; raw SDK/transport errors never escape. + const safe = error instanceof Error && /^(Invalid options|Explicit --live|Live interruption checks|Could not load|OPENROUTER_API_KEY|Credential-disclosure)/.test(error.message); + console.error(safe ? error.message : 'Manual interruption check failed; raw exception withheld. Inspect any saved receipt.'); + process.exitCode = 2; + } +} diff --git a/tests/live-interruptions.test.ts b/tests/live-interruptions.test.ts new file mode 100644 index 0000000..9626892 --- /dev/null +++ b/tests/live-interruptions.test.ts @@ -0,0 +1,119 @@ +import { spawnSync } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { expect, it } from 'vitest'; +import { chunk } from './helpers.js'; + +const script = fileURLToPath(new URL('../scripts/live-interruptions.mjs', import.meta.url)); +const guard = fileURLToPath(new URL('./offline-cli.mjs', import.meta.url)); +const root = fileURLToPath(new URL('..', import.meta.url)); + +async function harness() { + expect(existsSync(script), 'The manual interruption harness must exist').toBe(true); + return import(pathToFileURL(script).href); +} + +// Only the provider transport is synthetic. The harness, built runner, pinned +// SDK parser, native streams, abort handling, and exit mapping are real. +function fixture(mode: 'stalled' | 'complete' | 'buffered' | 'empty' | 'auth' = 'stalled') { + let requests = 0; + let cancellations = 0; + const fetcher = async (input: RequestInfo | URL) => { + requests++; + expect(input).toBeInstanceOf(Request); + expect((input as Request).url).toBe('https://openrouter.ai/api/v1/chat/completions'); + expect((input as Request).method).toBe('POST'); + if (mode === 'auth') return new Response('{}', { status: 401, headers: { 'content-type': 'application/json' } }); + const event = mode === 'empty' ? '' : mode === 'buffered' + ? `data: ${JSON.stringify(chunk('First'))}\n\ndata: ${JSON.stringify(chunk(' second', 'stop'))}\n\ndata: [DONE]\n\n` + : `data: ${JSON.stringify(chunk('Live 🌍 café', mode === 'complete' ? 'stop' : null))}\n\n`; + return new Response(new ReadableStream({ + start(controller) { + if (event) controller.enqueue(new TextEncoder().encode(event)); + if (mode !== 'stalled') controller.close(); + }, + cancel() { cancellations++; }, + }), { headers: { 'content-type': 'text/event-stream' } }); + }; + return { fetcher, get requests() { return requests; }, get cancellations() { return cancellations; } }; +} + +it.each([ + ['cancel', 'cancelled', null, 130], + ['transport', 'interrupted', 'network', 3], + ['deadline', 'interrupted', 'timeout', 124], +] as const)('verifies %s after real SDK-decoded text and releases the upstream reader', async (scenario, outcome, kind, exit) => { + const { runInterruptionCase } = await harness(); + const source = fixture(); + const report = await runInterruptionCase(scenario, { + apiKey: 'synthetic-manual-key', model: 'example/model', timeoutMs: 100, + fetcher: source.fetcher, + }); + expect(report.verdict).toBe('passed'); + expect(report.result).toMatchObject({ outcome, text: 'Live 🌍 café', partialOutput: true, httpStatus: 200 }); + if (kind) expect(report.result.error).toMatchObject({ kind, phase: 'stream' }); + else expect(report.result.reason).toBe('caller'); + expect(report.cliExitCode).toBe(exit); + expect(report.receivedText).toBe('Live 🌍 café'); + expect(report.injection.fired).toBe(true); + expect(report.injection.textLengthAtTrigger).toBe('Live 🌍 café'.length); + expect(report.upstreamReaderCancelled).toBe(true); + expect(source.requests).toBe(1); + expect(source.cancellations).toBe(1); +}); + +it('reports an empty completed stream as inconclusive instead of a passing fault check', async () => { + const { runInterruptionCase } = await harness(); + const source = fixture('empty'); + const report = await runInterruptionCase('transport', { + apiKey: 'synthetic-manual-key', model: 'example/model', timeoutMs: 100, + fetcher: source.fetcher, + }); + expect(report.verdict).toBe('inconclusive'); + expect(report.injection.fired).toBe(false); + expect(report.result.text).toBe(''); + expect(source.requests).toBe(1); +}); + +it('records a pre-stream authentication failure without injecting or retrying', async () => { + const { runInterruptionCase } = await harness(); + const source = fixture('auth'); + const report = await runInterruptionCase('cancel', { + apiKey: 'synthetic-manual-key', model: 'example/model', timeoutMs: 100, + fetcher: source.fetcher, + }); + expect(report.verdict).toBe('failed'); + expect(report.result).toMatchObject({ outcome: 'failed', httpStatus: 401, error: { kind: 'http' } }); + expect(report.injection.fired).toBe(false); + expect(source.requests).toBe(1); +}); + +it('marks a deadline experiment inconclusive when already-buffered completion wins', async () => { + const { runInterruptionCase } = await harness(); + const source = fixture('buffered'); + const report = await runInterruptionCase('deadline', { + apiKey: 'synthetic-manual-key', model: 'example/model', timeoutMs: 100, + fetcher: source.fetcher, + }); + expect(report.result).toMatchObject({ outcome: 'success', text: 'First second', finishReason: 'stop' }); + expect(report.injection.fired).toBe(true); + expect(report.verdict).toBe('inconclusive'); + expect(report.checks.expectedOutcome).toBe(false); + expect(source.requests).toBe(1); +}); + +it.each([ + { args: [], ci: '', status: 2, message: '--live' }, + { args: ['--live'], ci: 'true', status: 2, message: 'CI' }, + { args: ['--help'], ci: 'true', status: 0, message: 'Usage:' }, +])('keeps the manual command network-free for $args / CI=$ci', async ({ args, ci, status, message }) => { + await harness(); + const result = spawnSync(process.execPath, ['--import', pathToFileURL(guard).href, script, ...args], { + cwd: root, encoding: 'utf8', windowsHide: true, timeout: 10_000, + env: { ...process.env, CI: ci, OPENROUTER_API_KEY: 'synthetic-manual-key' }, + }); + expect(result.status, result.stderr).toBe(status); + expect(result.stdout + result.stderr).toContain(message); + expect(result.stdout + result.stderr).not.toContain('Provider network forbidden'); + expect(result.stdout + result.stderr).not.toContain('synthetic-manual-key'); +}); diff --git a/tests/sdk-boundary.test.ts b/tests/sdk-boundary.test.ts index 1a2f215..50852a2 100644 --- a/tests/sdk-boundary.test.ts +++ b/tests/sdk-boundary.test.ts @@ -45,8 +45,10 @@ describe('pinned official SDK compatibility gate', () => { it('passes cancellation to an in-flight fetch', async () => { const abort = new AbortController(); let received: AbortSignal | undefined; - const sdk = createSdk('synthetic-key', async input => { - const signal = (input as Request).signal; + const sdk = createSdk('synthetic-key', async (input, init) => { + // Match native fetch: RequestInit.signal overrides Request.signal. The + // pinned SDK uses that override to retain cancellation across Node GC. + const signal = init?.signal ?? (input as Request).signal; received = signal; return new Promise((_resolve, reject) => signal.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')), { once: true })); });