Python API¶
The names most apps need are importable from deja. The tools for working with recordings live in their own
modules: deja.replay, deja.verify, deja.explore, deja.shrink, deja.stepper, deja.group, deja.report,
deja.analysis and deja.fileformat.
Déjà is pre-1.0: names documented on this page are the public API, and anything else may change between minor versions.
Recording¶
deja.DejaMiddleware
¶
DejaMiddleware(app: Callable[..., Any], directory: str = 'deja-recordings', on_dump: Callable[[str, str], object] | None = None, track: bool = True, track_skip: Iterable[str] = (), track_only: Iterable[str] | None = None, background: bool = True, group: str | None = None, worker: str | None = None)
ASGI middleware that records every request and saves a recording when one goes wrong.
Works with any ASGI app: FastAPI, Starlette, Litestar, Quart, Django (ASGI). Serve the app on the recording
loop (uvicorn app:app --loop deja.loop:recording_loop); on any other loop the middleware passes requests
through and warns once.
Each HTTP request is recorded with its method, path, headers (sensitive ones redacted, see
deja.Recorder) and body, and each WebSocket connection with every message in and out. A recording of
the request's causal window (it, and the requests that overlapped it) is written when the response is a 5xx,
an exception escapes the app, a WebSocket connection closes with code 1011, or app code calls
deja.flag.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
Callable[..., Any]
|
The ASGI app to wrap. |
required |
directory
|
str
|
Folder for the |
'deja-recordings'
|
on_dump
|
Callable[[str, str], object] | None
|
Called as |
None
|
track
|
bool
|
Find the shared in-memory state the routes' code can reach and track it, so the report sees races on it and replay can order worker threads (see the Shared state guide). |
True
|
track_skip
|
Iterable[str]
|
|
()
|
track_only
|
Iterable[str] | None
|
If given, track only state matching these patterns. |
None
|
background
|
bool
|
Record the background tasks the app starts during startup (lifespan) and order them like requests. |
True
|
group
|
str | None
|
A folder shared by several worker processes of the same app, so a race across workers ends up in
one recording (see the Several workers guide). Defaults to the |
None
|
worker
|
str | None
|
This process's name within |
None
|
deja.aiohttp_web.deja_middleware
¶
deja_middleware(directory: str = 'deja-recordings', on_dump: Callable[[str, str], object] | None = None, track: bool = True, track_skip: Iterable[str] = (), track_only: Iterable[str] | None = None) -> Callable
Middleware for aiohttp web servers, which aren't ASGI.
The aiohttp counterpart of deja.DejaMiddleware.
It records each request (method, path, headers, body) and its response, and saves a recording on a 5xx, an
exception or deja.flag. Run the app on the recording loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str
|
Folder for the |
'deja-recordings'
|
on_dump
|
Callable[[str, str], object] | None
|
Called as |
None
|
track
|
bool
|
Track the shared in-memory state the handlers can reach (see the Shared state guide). |
True
|
track_skip
|
Iterable[str]
|
|
()
|
track_only
|
Iterable[str] | None
|
If given, track only state matching these patterns. |
None
|
Returns:
| Type | Description |
|---|---|
Callable
|
An aiohttp middleware to put in |
deja.scope
async
¶
scope(name: str, payload: Any = None, directory: str = 'deja-recordings', on_dump: Callable[[str, str], object] | None = None) -> AsyncIterator[Job]
Record a block of work that isn't a web request as one request.
Use it in queue consumers, scheduled jobs and message handlers. The block is recorded like a request: its
payload, its result and the order of its steps against everything else being recorded. A recording is saved
when an exception leaves the block or code inside it calls deja.flag; the exception is re-raised.
Outside a recording loop the block just runs.
To replay, pass --app a mapping (or a factory returning one) from scope name to an async handler. Each
recorded job is replayed as await handler(payload) and its return value compared with job.result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The kind of job ( |
required |
payload
|
Any
|
The job's input. It is stored in the recording and passed to the handler in replay, so it must
be JSON-serialisable ( |
None
|
directory
|
str
|
Folder for the |
'deja-recordings'
|
on_dump
|
Callable[[str, str], object] | None
|
Called as |
None
|
Yields:
| Type | Description |
|---|---|
AsyncIterator[Job]
|
The job, with |
deja.flag
¶
Save a recording of the current request, although it didn't fail.
Call it where the app notices something wrong that isn't an error: a negative balance, a seat sold twice. The
recording is written when the request ends; on a WebSocket connection, as soon as the app waits for the next
message. Inside a deja.scope block it saves that job. Outside a recording loop it does nothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reason
|
str
|
A few words on what went wrong. The recording's header stores it as |
''
|
deja.recording_loop
¶
recording_loop(recorder: Recorder | None = None) -> AbstractEventLoop
Create an event loop that records the order in which tasks run.
It is the platform's default loop type (selector loop on Linux and macOS, proactor loop on Windows) with
recording added. Recording starts when a request enters request scope (deja.DejaMiddleware,
deja.scope); other code runs as usual.
On a Python version Déjà hasn't been verified against, it warns and returns a plain loop, so the app runs unrecorded rather than recorded wrongly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recorder
|
Recorder | None
|
The |
None
|
Returns:
| Type | Description |
|---|---|
AbstractEventLoop
|
The new event loop. |
deja.Recorder
¶
Recorder(max_events: int = DEFAULT_MAX_EVENTS, redact_headers: Iterable[str] = ('authorization', 'cookie', 'x-api-key'))
The rolling record of everything a recording loop saw: task steps, requests and the answers to their calls.
Events go into a fixed-size ring buffer, so memory stays bounded however long the app runs. When a request
fails, the window of events around it is written to a .deja file. Create one yourself only to change the
settings below, and pass it to deja.recording_loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_events
|
int
|
Size of the ring buffer, in events. The default (200,000) holds about 15,000 to 20,000 requests of history for a typical API in tens of MB. A request whose start has already left the buffer when a recording is saved is left out of the replay; raise this for long WebSocket connections. |
DEFAULT_MAX_EVENTS
|
redact_headers
|
Iterable[str]
|
Request headers whose values are recorded as |
('authorization', 'cookie', 'x-api-key')
|
Example
mark
¶
Put a marker in the buffer, to save everything from this point on with dump.
Useful in tests and scripts that drive the app themselves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Text stored with the marker. |
''
|
Returns:
| Type | Description |
|---|---|
tuple
|
The marker, to pass to |
dump
¶
Write a recording now, without waiting for a request to fail.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The |
required |
rid
|
int | None
|
Save the causal window of this request (what the middleware saves when it fails). |
None
|
since
|
tuple | None
|
Save everything from this marker (from |
None
|
**extra
|
Any
|
Extra fields for the recording's header, such as |
{}
|
With neither rid nor since, the whole buffer is saved.
Returns:
| Type | Description |
|---|---|
str
|
|
Shared state and report hints¶
deja.track
¶
Make reads and writes of obj visible to the report.
Most apps never call this: deja.DejaMiddleware tracks the state its routes can reach on its own.
Use it for state the middleware can't find (see the Shared state guide).
A dict, defaultdict, OrderedDict, Counter, list, set or deque is copied into a
tracked container of the same type: use the returned object and drop the original. Any other object with a
__dict__ is tracked in place (its class is swapped for a reporting subclass) and returned. Tracking an
already tracked object returns it unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
The container or object to track. |
required |
name
|
str | None
|
Its name in the report ( |
None
|
key
|
str | None
|
For a set or list of records, the field that identifies an item, so the report names items by it
( |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The object to use from now on: a tracked copy for containers, |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
deja.touch
¶
Report an access to shared state that Déjà can't see by itself.
Use it for state held by a library object or reached with computed names. The report treats the access like
any other read or write, so two requests touching the same resource can show up as a race. In a worker
thread during replay, it also waits until the recording says it's this access's turn. Outside a recorded
request it costs one check.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resource
|
str
|
Name of the thing accessed, the same string for every access to it ( |
required |
kind
|
str
|
|
'read'
|
value
|
Any
|
The value read or written, shown in the report. Optional. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
deja.labels
¶
Give requests, calls and state readable names in reports.
Labels only change what the report says; recording and replay ignore them. Call it once, at import or startup. Later calls add to (and override) earlier ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
dict
|
Raw name to label. Keys are what the report would otherwise show: a route ( |
required |
deja.calls
¶
Say what an outside HTTP call does to shared state, when its method doesn't.
The report treats each outside call as a read or a write of the remote resource, so that two requests calling the same endpoint can show up as a race. By default GET and HEAD read and every other method writes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
dict
|
|
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a value isn't |
Replay¶
deja.replay.replay
¶
replay(recording: str | Schedule, app_factory: Callable[[], Any], deadline_s: float = 10.0, track: bool = True, on_step: Callable[[Any], object] | None = None) -> ReplayResult
Replay a recording against a fresh copy of the app, in the recorded interleaving.
The recorded requests are sent again (no client needed) and only allowed to run in the recorded order, on a virtual clock. Database, HTTP and other recorded calls get their recorded answers, so no service has to be running. If the app can't take a recorded step, the replay stops and the result says where.
The kind of app decides how requests are sent: an ASGI app gets ASGI calls, an aiohttp Application is
served on a local port, and a dict of handlers replays deja.scope jobs. A recording merged from
several workers gets one app per worker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recording
|
str | Schedule
|
Path of a |
required |
app_factory
|
Callable[[], Any]
|
Called with no arguments to build the app, once per replay (once per worker for a merged recording). Build it as in production: same configuration, same feature flags. |
required |
deadline_s
|
float
|
Seconds of real time without progress before the replay gives up and reports where it stuck. |
10.0
|
track
|
bool
|
Track the app's shared in-memory state as |
True
|
on_step
|
Callable[[Any], object] | None
|
None
|
Returns:
| Type | Description |
|---|---|
ReplayResult
|
The |
deja.replay.ReplayResult
¶
What a replay did, compared with the recording.
Attributes:
| Name | Type | Description |
|---|---|---|
recorded |
Request id to the recorded |
|
replayed |
Request id to the |
|
divergence |
|
|
steps_expected |
Recorded steps in request scope. |
|
steps_followed |
Steps the replay took in the recorded order. |
|
io_misses |
Calls the app made in replay that the recording has no answer for (it took another path). |
|
code_changed |
Modules whose source differs from the recorded fingerprints. |
followed
property
¶
Whether the replay took every recorded step, in order, and every call had a recorded answer.
same_responses
property
¶
Whether every request answered exactly as recorded (status and body).
summary
¶
A plain-text account of the replay: steps followed, responses compared, and anything to watch for.
deja.stepper.Stepper
¶
Stepper(at: int | None = None, task: str | None = None, ask: Callable[[str], str] = input, say: Callable[[str], object] = print)
The interactive pause behind deja step; pass one to replay as on_step.
With neither at nor task it pauses before every step. At a pause it reads commands (n, c,
s PATH, w, l, p EXPR, t, pdb, q; see deja step in the CLI reference).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
at
|
int | None
|
Run without pausing until step |
None
|
task
|
str | None
|
Run without pausing until task |
None
|
ask
|
Callable[[str], str]
|
Reads a command; called with the prompt. Replace it to script a session. |
input
|
say
|
Callable[[str], object]
|
Prints output; called with one string. |
print
|
deja.stepper.StepInfo
¶
The step a replay is about to take, passed to on_step callbacks.
Attributes:
| Name | Type | Description |
|---|---|---|
loop |
The replay loop. |
|
index |
Number of the step in the recording, from 0. The same number is the same moment in every replay. |
|
path |
The task about to run ( |
|
task |
The |
frame
property
¶
The innermost frame of the app's code where the task will resume (or the innermost frame at all).
Checking a fix¶
deja.verify.verify
¶
verify(recording: str, app_factory: Callable[[], Any], times: int = 5, deadline_s: float = 10.0) -> Verdict
Check whether a change to the code stops a recorded race.
The recording is replayed against the app times times. The race is still there when a replay follows the
recorded interleaving and the requests answer as they did when the bug happened. A fix shows up either as a
replay that can't take the recorded steps (a lock or transaction now orders the requests) or as one that takes
them and answers differently (a check now catches the conflict).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recording
|
str
|
Path of the |
required |
app_factory
|
Callable[[], Any]
|
Builds the changed app, as for |
required |
times
|
int
|
Replays to run. |
5
|
deadline_s
|
float
|
Seconds without progress before a replay gives up. |
10.0
|
Returns:
| Type | Description |
|---|---|
Verdict
|
A |
deja.verify.Verdict
¶
The outcome of verify.
Attributes:
| Name | Type | Description |
|---|---|---|
recording |
Path of the recording. |
|
results |
One |
|
story |
The race in plain words, from the recording's analysis. |
reproduced
property
¶
Replays that went exactly as recorded (the race happened again).
deja.verify.diff
¶
diff(recording: str, old_factory: Callable[[], Any], new_factory: Callable[[], Any], deadline_s: float = 10.0) -> str
Replay one recording against two versions of the app and say how they differ.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recording
|
str
|
Path of the |
required |
old_factory
|
Callable[[], Any]
|
Builds the first version of the app. |
required |
new_factory
|
Callable[[], Any]
|
Builds the second version. |
required |
deadline_s
|
float
|
Seconds without progress before a replay gives up. |
10.0
|
Returns:
| Type | Description |
|---|---|
str
|
A plain-text comparison: steps each version followed, each request's recorded, old and new answer, calls |
str
|
without a recorded answer, and the modules whose code differs between them. |
deja.verify.export_test
¶
Write a pytest regression test for the recorded race.
The test replays the recording and fails while the race reproduces; once a fix stops it, the test passes.
Keep it in the test suite to catch the race coming back. The recording is copied into a recordings/
folder next to the test file, which the test reads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recording
|
str
|
Path of the |
required |
app_spec
|
str
|
The app as |
required |
out
|
str
|
Path of the test file to write. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The path of the test file. |
Exploring and shrinking¶
deja.explore.explore
¶
explore(recording: str | Schedule, app_factory: Callable[[], Any], tries: int = 50, seed: int = 1, deadline_s: float = 10.0) -> dict
Replay a recording's requests in orderings that didn't happen, to find races that haven't happened yet.
First every serial order (each request alone, start to finish; for more than five requests, first-to-last
and last-to-first), then tries seeded random interleavings. An interleaving whose answers no serial order
gives is a race.
Database and HTTP answers still come from the recording, so an ordering in which the app would have read different rows isn't modelled; runs that made calls the recording has no answer for are marked approximate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recording
|
str | Schedule
|
Path of a |
required |
app_factory
|
Callable[[], Any]
|
Builds the app, as for |
required |
tries
|
int
|
Random interleavings to run. |
50
|
seed
|
int
|
Seed of the first one; run |
1
|
deadline_s
|
float
|
Seconds without progress before a run gives up. |
10.0
|
Returns:
| Type | Description |
|---|---|
dict
|
|
dict
|
|
dict
|
|
deja.shrink.shrink
¶
Cut a recording down to the requests its race needs.
The two requests of the first conflict are kept. Déjà tries removing all the others at once, then (if the race no longer replays) one at a time, keeping a removal only if the smaller recording still replays and the kept requests still answer as recorded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recording
|
str
|
Path of the |
required |
app_factory
|
Callable[[], Any]
|
Builds the app, as for |
required |
out
|
str
|
Path of the smaller |
required |
deadline_s
|
float
|
Seconds without progress before a replay gives up. |
10.0
|
Returns:
| Type | Description |
|---|---|
dict
|
|
dict
|
and the event counts of the two recordings. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the recording has no race to shrink to. |
Recordings¶
deja.group.merge
¶
Merge the recordings that several workers saved for one race into one recording.
Each worker's events are interleaved by the time they happened (all processes on one machine share a clock),
and each worker's request and task ids are renamed so they don't clash: worker k's request r becomes
r + k * 100000.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
Iterable[str]
|
The |
required |
out
|
str
|
Path of the merged |
required |
Returns:
| Type | Description |
|---|---|
str
|
|
deja.report.write_report
¶
Write the HTML report of a recording: the race in plain words, the requests and a timeline.
The page is one file with the recording's analysis embedded, and loads nothing from the network. It holds what the recording holds, so share it as carefully (see Security in the docs).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recording
|
str
|
Path of the |
required |
out
|
str | None
|
Path of the |
None
|
replay
|
Any
|
A |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The path written. |
deja.analysis.analyze
¶
Find the races in a recording and explain them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
header
|
dict
|
The recording's header, from |
required |
events
|
list
|
Its events. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
A dict. The main keys: |
dict
|
|
dict
|
|
deja.fileformat.read
¶
Read a recording, upgrading an older format to the current one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The |
required |
Returns:
| Type | Description |
|---|---|
tuple[dict, list]
|
|
Raises:
| Type | Description |
|---|---|
FormatError
|
If the file isn't a Déjà recording, or was written by a newer Déjà. |
deja.fileformat.write
¶
Write a recording: gzipped JSON Lines, the header first and then one event per line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The |
required |
header
|
dict
|
The header object; it must carry |
required |
events
|
list
|
The events, as tuples. |
required |
deja.fileformat.FormatError
¶
Bases: ValueError
A recording this version of Déjà can't read.