# Recording and replaying provider calls

1. **get_api_provider** the one point every model call passes
2. **RecordingProvider** writes each event to the file, then yields it unchanged; delegates to the vendor provider
3. **ReplayProvider** reads the file instead; no vendor provider, HTTP client or credentials

Vendor modules know about neither. `call_index` counts every API's calls in one order, because all wrappers share one sink and one `ReplayProvider`.

## Scope

| Boundary | Rule |
| --- | --- |
| Covers | LLM provider request and event stream, across APIs, in one file |
| Still runs for real | Agent loop, Runtime retries, tools, Session, DAG |
| Does not | Restore a Session, replay tool side effects, roll back files or define task steps; record tools, MCP, browser or arbitrary HTTP |
| Never | Fuzzy match models or prompts, fall back to live, upload or commit files, switch at runtime |
| Strict offline | Holds at the provider layer only. Tools keep their permissions; use the sandbox or network policy for a fully offline process. |
| Web UI | None; CLI and settings |
| Format | JSONL is not a stable public interchange format |
| Content | Credential redaction is not anonymization: prompts, replies, tool results, file excerpts and personal data remain |

## Commands and settings

| Command | Does | Exit |
| --- | --- | --- |
| `openprogram recordings status [--json]` | Mode, file, source, availability, restart needed; reads no content | 0 valid, 1 invalid |
| `record [--name NAME]` | Creates a 0600 header-only file, then writes `mode=record` and selector atomically; on failure removes the file and keeps settings. Unnamed: UTC timestamp plus random suffix | 0 only when both succeed |
| `replay <selector>` | Strictly parses first, then writes `mode=replay` and selector | 1 invalid, settings unchanged |
| `off` | Mode only; the selector stays | 0 |
| `list [--json]` | ID, created, version, counts, integrity, bytes, active; newest first. Corrupt files show `invalid` | 2 arguments, 1 operational |
| `show <selector> [--json] [--content]` | Header, statistics, each call's model and status. `--content` prints the redacted JSONL, with a risk notice on stderr | same |
| `delete <id> [--yes]` | One managed ID. TTY: type the full ID; no TTY and no `--yes`: exit 2. Rejects active, external, directories, symlinks | same |
| `prune --older-than-days N [--dry-run] [--yes]` | By file mtime. Skips active, invalid symlinks, locked files; continues past failures | same |

| Setting | Values | Rule |
| --- | --- | --- |
| `record_replay.mode` | `off`, `record`, `replay`; default `off` | Applies next start |
| `record_replay.file` | managed ID or path; default empty | Empty only when off. Record accepts IDs only; replay needs a strictly readable file |

Settings are read once, when the runtime leaves NEW. A missing subtree means off; no environment variable turns it on and nothing picks the latest recording. A selector without a separator is a managed ID in `get_recordings_dir()`. Replay and show may read explicit paths; delete and prune stay inside the managed root.

## Runtime lifecycle

| Interface | Does | Never |
| --- | --- | --- |
| `import openprogram.models.providers` | Defines and exports APIs | Registers vendors, reads settings, opens files, installs a transform |
| `register_builtins()` | Thread-safe, publishes API providers in one batch, loads auth adapters | Touches record or replay |
| `initialize_provider_runtime()` | Serializes registration, settings snapshot, wrapper construction, transform publication | Resolves credentials, builds vendor clients, uses the network |
| `get_api_provider(api)` | Ensures READY, returns the final provider | Returns the original when FAILED |
| `create_runtime(...)` | Ensures READY. Replay builds a base Runtime from explicit or non-credential defaults (`AGENTIC_PROVIDER`, `AGENTIC_MODEL`, `default_provider`, `default_model`); none selected is a replay error | In replay, detects CLIs or the AuthStore, builds a subscription runtime |
| `openprogram recordings ...` | Reads files, updates next-start settings | Initializes the runtime, so `status` and `off` still work when replay is broken |

| State or failure | Result | Recovery |
| --- | --- | --- |
| NEW → INITIALIZING | One thread initializes; others wait on one `threading.Condition` | – |
| READY | Settings never reread | Restart for changes |
| Built-in registration fails | FAILED; each caller gets a fresh `ProviderRuntimeInitializationError` with the same stage, type and redacted message | Restart; management commands work |
| Record or replay activation fails: unknown mode, empty file, external record path, missing or corrupt replay file | READY with `snapshot.mode == "blocked"`; `_BlockedRecordReplayProvider` raises one diagnostic on every call, with no credentials or network | `recordings status`, `recordings off` |
| `KeyboardInterrupt`, `SystemExit` during initialization | FAILED as `initialization_interrupted`; initializer re-raises the original | Restart |

Web and worker initialize before starting threads, so a bad replay is reported in single-threaded startup. Wrappers are built and validated before the transform is published.

**The transform**

```
configure_provider_transform(transform)
  once per process; same value no-op, conflict RuntimeError
  keeps the original, never double-wraps, replaces all entries atomically
  later register_api_provider(api, original) stores transform(api, original)

record:  transform(api, original) -> RecordingProvider(original, shared_sink)
replay:  transform(api, original) -> shared_replay
```

In replay, `original` only confirms the API is registered. `stream.py` gets the provider first and skips credentials when `requires_credentials` is false. Direct constructors remain for tests: `RecordingProvider(real_provider, path)`, `ReplayProvider(path)`. Calls that bypass `get_api_provider()` must return to it; no vendor-specific cases.

## File format

```
{"type":"header","format_version":2,"recording_id":"…","created_at":"…","redaction_version":1}
{"type":"request","call_index":0,"model":{…},"context":{…},"options":{…}}
{"type":"event","call_index":0,"event_index":0,"event":{…}}
{"type":"call_end","call_index":0,"event_count":1,"outcome":"complete"}
```

| Rule | Detail |
| --- | --- |
| Version | `RECORDING_FORMAT_VERSION` is 2. Replay accepts 1 and 2, refuses others. Version 1 cannot replay a structured `response_format`; request-local option fields it stored as null are dropped. |
| Bump when | Required request, event or `call_end` fields or their meaning change. Optional header fields do not bump it; readers ignore unknown ones. |
| `call_end.outcome` | `complete`, `error`, `cancelled` or `abandoned`; missing means complete |
| Old files | Headers with only type and version stay valid; metadata comes from stat and content. Later formats get their own parser; files are never rewritten in place. |

**Strict reader**

| Level | Refused unless |
| --- | --- |
| File | First non-empty line is the only header; every line a JSON object; known version; only the four line types; not empty or truncated |
| Call | Each request has a unique `call_index` consecutive from 0; events reference an open call; `event_index` consecutive from 0; exactly one `call_end` |
| Completion | `event_count` matches; no events after `call_end`; unknown event types fail at construction, not midway |
| Request | Incoming is redacted the same way, compared model, context, options; calls beyond the recording are refused |

Errors are `RecordingFileError(path, line, call_index, reason)`. `list`, `show` and activation share this parser.

**Concurrent writes**

1. `RecordingSink` serializes and appends each line under a process-local `threading.RLock`.
2. Each append opens with `O_WRONLY | O_CREAT | O_APPEND`, mode 0600, and takes an exclusive `flock` across processes.
3. The header and next `call_index` are allocated under the file lock: one past the highest request index. The sink remembers how far it has read, so each call reads only the lines appended since, by any process; a file shorter than that is read again from the start.
4. A complete UTF-8 line plus newline goes out in an `os.write` loop.
5. `fsync` runs after `call_end` only; a crash leaves an incomplete call the strict parser detects.
6. Events may interleave; `call_index` and `event_index` group them.

Recording guarantees file integrity, not scheduling. Tests that need determinism issue provider calls serially.

## Permissions and redaction

| Subject | Rule |
| --- | --- |
| Managed root | `get_state_dir() / "recordings"`, tightened to 0700 |
| Record target | Managed IDs only. 0600, `O_EXCL` for a new file, `O_NOFOLLOW` where supported, else directory-fd open and `lstat`/`fstat` comparison. Never truncates; name conflicts fail. |
| Replay | Managed files may be tightened to 0600. External files must already be regular and 0600; they are refused, not chmod-ed. |
| Lock files | 0600 |
| list, show, delete, prune | `lstat` rejects symlinks; delete and prune touch regular `.jsonl` files only, without recursion |
| Redaction | `remove_secret_values()` runs before serialization, no off switch; value becomes `[secret removed]` |
| By field name | `SECRET_FIELD_NAMES`, case-insensitive, nested: `authorization`, `proxy-authorization`, `api_key`, `apikey`, `api-key`, `x-api-key`, `x-goog-api-key`, `token`, `access_token`, `refresh_token`, `id_token`, `cookie`, `set-cookie`, `secret`, `client_secret`, `password`, `session_key`; plus names ending in `-` or `_` then token, key, secret or password. `token_count` stays. |
| By value | Bearer, Basic, Bot, token and Key schemes; `sk-…`; URL userinfo; `api_key`, `apikey`, `access_token`, `token` query values |
| Not used | High-entropy rules: they would change ordinary prompts and break matching |
| Matching | Replay redacts the incoming request first; record and replay use the same `redaction_version` |

## Differences and failures

```
replay mismatch at call 1, field context.messages[2].content[0].text:
recorded 'echo:hi', incoming 'echo:bye'
```

`find_first_difference()` walks dicts by sorted key and lists by index, so a pair always reports the same path. `NON_DETERMINISTIC_FIELD_NAMES` (`timestamp`, `first_token_ms`, `first_text_ms`) are skipped.

| Phase | Condition | Result |
| --- | --- | --- |
| Creation | Existing name, symlink, unwritable directory, permissions | `RecordingFileError`; nothing overwritten |
| Writing | Lock failure, full disk, serialization | Stops the provider call, keeps what was written |
| Live provider | Failure, cancellation, early close | In `finally`: writes `call_end` with outcome, closes the source, keeps the original exception |
| Parsing | Bad JSON, version, order, count or event type | `RecordingFileError` |
| Matching | Incoming differs | `ReplayMismatch` with `call_index`, `field_path`, `recorded`, `incoming`, and `event_index` when position diverges; does not consume the call |
| Exhaustion | More calls than recorded | `ReplayMismatch(field_path="call_index")` |
| Interrupted recorded call | Matches and is consumed once | Reports the recorded interruption |
| Under-use | Recorded calls left | `assert_consumed()`; no product entry calls it |
| Prune | Some deletions fail | Reports each, continues, exits 1 |

**Acceptance matrix**

| Dimension | Case | Assertion |
| --- | --- | --- |
| Import | Subprocess imports only the package | No config read, recording open, vendor import or registry change |
| Initialization | No settings, off, record, replay; many threads | Once only; one initializer; no deadlock |
| Failure atomicity | Exceptions in each stage | No original provider, credential lookup or partial transform |
| Entry points | Web, worker, stream, library, auth loading | READY before use; auth registers without replay |
| Registry | Before and after wrapping, two APIs | Existing and later entries wrapped; conflicts refused |
| Concurrency | Two threads, two or three processes | One header, valid JSON, consecutive indices, right counts |
| Errors | Exception, cancel, `aclose()`, sync failure | Control flow kept, source closed, outcome written |
| Activation failure | Missing or corrupt file, unknown mode | READY, blocked, no credentials or network; recoverable |
| Replay counting | Mismatch, then corrected | Same recorded call compared again |
| Permissions, paths | Broad modes, `../`, symlinks, external deletion | 0700/0600; escapes refused |
| Redaction | Case, nesting, suffixes, schemes, URLs | Credential bytes absent; `token_count` stays |
| Strict offline | Success, mismatch, exhaustion, corrupt | No socket, HTTP client or credential sentinel fired |
| Runtime factory | Explicit, defaults, none; plain, subscription | Replay uses `model_namespace`; no dedicated Runtime |
| CLI | All verbs, concurrent writes | Atomic; restart notice; profile isolated; no initialization |
| Recovery | `status`, `off` with broken files | Real subprocess; diagnostic stable |
| Loop | Multi-turn tool loop record then replay | Same events, tool execution, final message |

Tests: `tests/component/providers/registry/test_provider_initialization.py`, `test_record_replay.py`, `test_record_replay_registry.py`, `test_record_replay_cli.py`.

**Files and alternatives**

| File | Holds |
| --- | --- |
| `models/providers/recording/recording.py` | Format, `RecordingSink`, redaction, management, activation |
| `models/providers/recording/replay.py` | Strict parser, `ReplayProvider`, differences |
| `models/providers/catalog/initialization.py` | Lifecycle state and failures |
| `models/providers/catalog/register.py` | `register_builtins()` |
| `models/providers/catalog/api_registry.py` | Lookup, transform |
| `models/providers/catalog/registry.py`, `runtime/agent/runtime/factory.py` | `model_namespace`, replay runtime |
| `models/auth/credential_provider.py` | Explicit `register_builtins()` |
| `interfaces/server/server.py`, `operations/worker/runner.py` | Startup initialization |

Rejected: per-vendor recorders, raw HTTP capture and test mocks standing in for product entry points. They duplicate code, expose unredacted wire data or miss worker configuration. `references/pi-ai` has one registry dispatch point and no recording; the dispatch point is adopted.

## Implementation status

| Status | Items |
| --- | --- |
| Implemented | Strict versioned recording and replay, shared transform, next-start settings, recordings CLI, explicit lifecycle, blocked-provider recovery |
| Not built | Web UI, process-wide HTTP recording, tool or MCP recording, fuzzy matching, Windows-specific validation, reproducible concurrent scheduling |
