OpenProgram Docs

Recording and replaying provider calls

Record get_api_provider RecordingProvider vendor provider network writes each event to recording.jsonl first Replay get_api_provider ReplayProvider recording.jsonl no vendor provider, HTTP client or credentials
  1. get_api_providerthe one point every model call passes
  2. RecordingProviderwrites each event to the file, then yields it unchanged; delegates to the vendor provider
  3. ReplayProviderreads 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

BoundaryRule
CoversLLM provider request and event stream, across APIs, in one file
Still runs for realAgent loop, Runtime retries, tools, Session, DAG
Does notRestore a Session, replay tool side effects, roll back files or define task steps; record tools, MCP, browser or arbitrary HTTP
NeverFuzzy match models or prompts, fall back to live, upload or commit files, switch at runtime
Strict offlineHolds at the provider layer only. Tools keep their permissions; use the sandbox or network policy for a fully offline process.
Web UINone; CLI and settings
FormatJSONL is not a stable public interchange format
ContentCredential redaction is not anonymization: prompts, replies, tool results, file excerpts and personal data remain

Commands and settings

CommandDoesExit
openprogram recordings status [--json]Mode, file, source, availability, restart needed; reads no content0 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 suffix0 only when both succeed
replay <selector>Strictly parses first, then writes mode=replay and selector1 invalid, settings unchanged
offMode only; the selector stays0
list [--json]ID, created, version, counts, integrity, bytes, active; newest first. Corrupt files show invalid2 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 stderrsame
delete <id> [--yes]One managed ID. TTY: type the full ID; no TTY and no --yes: exit 2. Rejects active, external, directories, symlinkssame
prune --older-than-days N [--dry-run] [--yes]By file mtime. Skips active, invalid symlinks, locked files; continues past failuressame
SettingValuesRule
record_replay.modeoff, record, replay; default offApplies next start
record_replay.filemanaged ID or path; default emptyEmpty 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

InterfaceDoesNever
import openprogram.models.providersDefines and exports APIsRegisters vendors, reads settings, opens files, installs a transform
register_builtins()Thread-safe, publishes API providers in one batch, loads auth adaptersTouches record or replay
initialize_provider_runtime()Serializes registration, settings snapshot, wrapper construction, transform publicationResolves credentials, builds vendor clients, uses the network
get_api_provider(api)Ensures READY, returns the final providerReturns 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 errorIn replay, detects CLIs or the AuthStore, builds a subscription runtime
openprogram recordings ...Reads files, updates next-start settingsInitializes the runtime, so status and off still work when replay is broken
State or failureResultRecovery
NEW → INITIALIZINGOne thread initializes; others wait on one threading.Condition–
READYSettings never rereadRestart for changes
Built-in registration failsFAILED; each caller gets a fresh ProviderRuntimeInitializationError with the same stage, type and redacted messageRestart; management commands work
Record or replay activation fails: unknown mode, empty file, external record path, missing or corrupt replay fileREADY with snapshot.mode == "blocked"; _BlockedRecordReplayProvider raises one diagnostic on every call, with no credentials or networkrecordings status, recordings off
KeyboardInterrupt, SystemExit during initializationFAILED as initialization_interrupted; initializer re-raises the originalRestart

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"}
RuleDetail
VersionRECORDING_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 whenRequired request, event or call_end fields or their meaning change. Optional header fields do not bump it; readers ignore unknown ones.
call_end.outcomecomplete, error, cancelled or abandoned; missing means complete
Old filesHeaders 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
LevelRefused unless
FileFirst non-empty line is the only header; every line a JSON object; known version; only the four line types; not empty or truncated
CallEach request has a unique call_index consecutive from 0; events reference an open call; event_index consecutive from 0; exactly one call_end
Completionevent_count matches; no events after call_end; unknown event types fail at construction, not midway
RequestIncoming 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

SubjectRule
Managed rootget_state_dir() / "recordings", tightened to 0700
Record targetManaged 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.
ReplayManaged files may be tightened to 0600. External files must already be regular and 0600; they are refused, not chmod-ed.
Lock files0600
list, show, delete, prunelstat rejects symlinks; delete and prune touch regular .jsonl files only, without recursion
Redactionremove_secret_values() runs before serialization, no off switch; value becomes [secret removed]
By field nameSECRET_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 valueBearer, Basic, Bot, token and Key schemes; sk-…; URL userinfo; api_key, apikey, access_token, token query values
Not usedHigh-entropy rules: they would change ordinary prompts and break matching
MatchingReplay 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.

PhaseConditionResult
CreationExisting name, symlink, unwritable directory, permissionsRecordingFileError; nothing overwritten
WritingLock failure, full disk, serializationStops the provider call, keeps what was written
Live providerFailure, cancellation, early closeIn finally: writes call_end with outcome, closes the source, keeps the original exception
ParsingBad JSON, version, order, count or event typeRecordingFileError
MatchingIncoming differsReplayMismatch with call_index, field_path, recorded, incoming, and event_index when position diverges; does not consume the call
ExhaustionMore calls than recordedReplayMismatch(field_path="call_index")
Interrupted recorded callMatches and is consumed onceReports the recorded interruption
Under-useRecorded calls leftassert_consumed(); no product entry calls it
PruneSome deletions failReports each, continues, exits 1
Acceptance matrix
DimensionCaseAssertion
ImportSubprocess imports only the packageNo config read, recording open, vendor import or registry change
InitializationNo settings, off, record, replay; many threadsOnce only; one initializer; no deadlock
Failure atomicityExceptions in each stageNo original provider, credential lookup or partial transform
Entry pointsWeb, worker, stream, library, auth loadingREADY before use; auth registers without replay
RegistryBefore and after wrapping, two APIsExisting and later entries wrapped; conflicts refused
ConcurrencyTwo threads, two or three processesOne header, valid JSON, consecutive indices, right counts
ErrorsException, cancel, aclose(), sync failureControl flow kept, source closed, outcome written
Activation failureMissing or corrupt file, unknown modeREADY, blocked, no credentials or network; recoverable
Replay countingMismatch, then correctedSame recorded call compared again
Permissions, pathsBroad modes, ../, symlinks, external deletion0700/0600; escapes refused
RedactionCase, nesting, suffixes, schemes, URLsCredential bytes absent; token_count stays
Strict offlineSuccess, mismatch, exhaustion, corruptNo socket, HTTP client or credential sentinel fired
Runtime factoryExplicit, defaults, none; plain, subscriptionReplay uses model_namespace; no dedicated Runtime
CLIAll verbs, concurrent writesAtomic; restart notice; profile isolated; no initialization
Recoverystatus, off with broken filesReal subprocess; diagnostic stable
LoopMulti-turn tool loop record then replaySame 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
FileHolds
models/providers/recording/recording.pyFormat, RecordingSink, redaction, management, activation
models/providers/recording/replay.pyStrict parser, ReplayProvider, differences
models/providers/catalog/initialization.pyLifecycle state and failures
models/providers/catalog/register.pyregister_builtins()
models/providers/catalog/api_registry.pyLookup, transform
models/providers/catalog/registry.py, runtime/agent/runtime/factory.pymodel_namespace, replay runtime
models/auth/credential_provider.pyExplicit register_builtins()
interfaces/server/server.py, operations/worker/runner.pyStartup 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

StatusItems
ImplementedStrict versioned recording and replay, shared transform, next-start settings, recordings CLI, explicit lifecycle, blocked-provider recovery
Not builtWeb UI, process-wide HTTP recording, tool or MCP recording, fuzzy matching, Windows-specific validation, reproducible concurrent scheduling
Last updated · 2026-11-25