Skip to content

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. app.add_middleware(DejaMiddleware, ...) passes it for you.

required
directory str

Folder for the .deja files, created when the first one is written.

'deja-recordings'
on_dump Callable[[str, str], object] | None

Called as on_dump(path, reason) after each recording is written; use it to log or alert.

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]

fnmatch patterns of state not to track, matched against its name (store.cache) or its class (myapp.models.Account).

()
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 DEJA_GROUP environment variable.

None
worker str | None

This process's name within group. Defaults to pid<process id>.

None
Example
app = FastAPI()
app.add_middleware(deja.DejaMiddleware, directory="deja-recordings")

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 files.

'deja-recordings'
on_dump Callable[[str, str], object] | None

Called as on_dump(path, reason) after each recording is written.

None
track bool

Track the shared in-memory state the handlers can reach (see the Shared state guide).

True
track_skip Iterable[str]

fnmatch patterns of state not to track.

()
track_only Iterable[str] | None

If given, track only state matching these patterns.

None

Returns:

Type Description
Callable

An aiohttp middleware to put in web.Application(middlewares=[...]).

Example
from deja.aiohttp_web import deja_middleware

app = web.Application(middlewares=[deja_middleware(directory="deja-recordings")])
web.run_app(app, loop=deja.recording_loop())

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 ("orders"). Replay looks up the handler by this name.

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 (bytes, tuples and sets are fine).

None
directory str

Folder for the .deja files.

'deja-recordings'
on_dump Callable[[str, str], object] | None

Called as on_dump(path, reason) after a recording is written.

None

Yields:

Type Description
AsyncIterator[Job]

The job, with name, payload and result. Set job.result to what the job produced, so replay can compare it.

Example
async for msg in consumer:
    async with deja.scope("orders", msg.value) as job:
        job.result = await handle_order(msg.value)

handlers = {"orders": handle_order}   # deja replay rec.deja --app myworker:handlers

deja.flag

flag(reason: str = '') -> None

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 "flag: <reason>" and the report shows it.

''
Example
if account.balance < 0:
    deja.flag("balance went negative")

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 deja.Recorder to use, for a bigger buffer or other redacted headers. Defaults to a new one with default settings.

None

Returns:

Type Description
AbstractEventLoop

The new event loop. loop.deja is its recorder.

Example
asyncio.run(main(), loop_factory=deja.recording_loop)
# uvicorn app:app --loop deja.loop:recording_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 "<redacted>", case-insensitive. This replaces the default list, so include authorization, cookie and x-api-key when adding more.

('authorization', 'cookie', 'x-api-key')
Example
import functools
loop_factory = functools.partial(deja.recording_loop, deja.Recorder(max_events=1_000_000))
asyncio.run(main(), loop_factory=loop_factory)

mark

mark(label: str = '') -> tuple

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(path, since=marker).

dump

dump(path: str, rid: int | None = None, since: tuple | None = None, **extra: Any) -> str

Write a recording now, without waiting for a request to fail.

Parameters:

Name Type Description Default
path str

The .deja file to write.

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 mark) on. Takes precedence over rid.

None
**extra Any

Extra fields for the recording's header, such as reason="...".

{}

With neither rid nor since, the whole buffer is saved.

Returns:

Type Description
str

path.

Shared state and report hints

deja.track

track(obj: Any, name: str | None = None, key: str | None = None) -> Any

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 ("carts", "wallet"). Defaults to the type's name.

None
key str | None

For a set or list of records, the field that identifies an item, so the report names items by it (key="username" reports users[username=ada]).

None

Returns:

Type Description
Any

The object to use from now on: a tracked copy for containers, obj itself for other objects.

Raises:

Type Description
TypeError

If obj is neither a supported container nor an object with a __dict__.

Example
self.carts = deja.track({}, "carts")      # carts[42] = c  -> write carts[42]
deja.track(self.wallet, "wallet")         # wallet.balance -> read wallet.balance

deja.touch

touch(resource: str, kind: str = 'read', value: Any = None) -> None

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 ("cart:42", "inventory[sku-1]").

required
kind str

"read" or "write".

'read'
value Any

The value read or written, shown in the report. Optional.

None

Raises:

Type Description
ValueError

If kind is neither "read" nor "write".

Example
total = cache.get(f"cart:{cart_id}")
deja.touch(f"cart:{cart_id}", "read", total)

deja.labels

labels(mapping: dict) -> None

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 ("POST /purchase"), an outside call ("POST payments/charge") or a piece of state ("gallery_wallet.balance").

required
Example
deja.labels({
    "POST /purchase": "Purchase",
    "POST payments/charge": "Charge card",
    "gallery_wallet.balance": "Wallet balance",
})

deja.calls

calls(mapping: dict) -> None

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

"METHOD host/path" pattern (fnmatch wildcards) to "read", "write" or "ignore" (leave the call out of the analysis).

required

Raises:

Type Description
ValueError

If a value isn't "read", "write" or "ignore".

Example
deja.calls({
    "POST pricing.internal/quote": "read",      # a POST that only computes a price
    "GET payments.example/*/capture": "write",  # a GET that changes something
    "GET metrics.internal/*": "ignore",         # not part of the story
})

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 .deja file (or an already loaded Schedule).

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 deja.DejaMiddleware does, with the rules saved in the recording. Replay needs it to put worker threads' accesses in the recorded order.

True
on_step Callable[[Any], object] | None

Called as on_step(info) before each recorded step, with a StepInfo. See Stepper.

None

Returns:

Type Description
ReplayResult
Example
from deja.replay import replay

result = replay("recordings/wallet.deja", create_app)
assert result.followed and result.same_responses, result.summary()

deja.replay.ReplayResult

ReplayResult(schedule, loop, harness, divergence)

What a replay did, compared with the recording.

Attributes:

Name Type Description
recorded

Request id to the recorded (status, body).

replayed

Request id to the (status, body) the app answered in replay.

divergence

None, or a description of where the replay could not follow the recording (which task was due to run, and what ran instead).

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

followed: bool

Whether the replay took every recorded step, in order, and every call had a recorded answer.

same_responses property

same_responses: bool

Whether every request answered exactly as recorded (status and body).

summary

summary() -> str

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 at, then pause.

None
task str | None

Run without pausing until task task ("q1") is about to run, then pause.

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

StepInfo(loop, index, path, task)

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 ("q1" is request 1's task, "q1.2" its third child).

task

The asyncio.Task about to run.

frame property

frame

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 .deja file with the race.

required
app_factory Callable[[], Any]

Builds the changed app, as for replay.

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 Verdict; verdict.fixed is the answer and verdict.summary() explains it.

deja.verify.Verdict

Verdict(recording, results, story)

The outcome of verify.

Attributes:

Name Type Description
recording

Path of the recording.

results

One ReplayResult per replay.

story

The race in plain words, from the recording's analysis.

reproduced property

reproduced: int

Replays that went exactly as recorded (the race happened again).

fixed property

fixed: bool

Whether no replay reproduced the race.

how

how(r) -> str

Why replay r did or didn't reproduce the race, in one sentence.

summary

summary() -> str

FIXED or STILL THERE, the race, and what happened in the last replay.

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 .deja file.

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

export_test(recording: str, app_spec: str, out: str) -> str

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 .deja file with the race.

required
app_spec str

The app as "module:attribute", the same form as --app.

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 .deja file (or a loaded Schedule).

required
app_factory Callable[[], Any]

Builds the app, as for replay.

required
tries int

Random interleavings to run.

50
seed int

Seed of the first one; run i uses seed + i, so a race found can be run again.

1
deadline_s float

Seconds without progress before a run gives up.

10.0

Returns:

Type Description
dict

{"requests", "serial", "races", "tries"}. Each race has the seed that produced it and the

dict

run: its responses, order of steps, error and approximate flag. Pass the result to

dict

summary for plain text.

deja.explore.summary

summary(result) -> str

The result of explore as plain text, as deja explore prints it.

deja.shrink.shrink

shrink(recording: str, app_factory: Callable[[], Any], out: str, deadline_s: float = 10.0) -> dict

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 .deja file with the race.

required
app_factory Callable[[], Any]

Builds the app, as for replay.

required
out str

Path of the smaller .deja file to write.

required
deadline_s float

Seconds without progress before a replay gives up.

10.0

Returns:

Type Description
dict

{"kept": [...], "removed": [...], "events": (before, after)}: request ids ("q3") kept and removed,

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(paths: Iterable[str], out: str) -> str

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 .deja files in one <group>/<id>/ folder, one per worker.

required
out str

Path of the merged .deja file to write.

required

Returns:

Type Description
str

out.

deja.report.write_report

write_report(recording: str, out: str | None = None, replay: Any = None) -> str

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 .deja file.

required
out str | None

Path of the .html file. Defaults to the recording's path with .html.

None
replay Any

A ReplayResult to show the replay verdict, or None.

None

Returns:

Type Description
str

The path written.

deja.analysis.analyze

analyze(header: dict, events: list) -> dict

Find the races in a recording and explain them.

Parameters:

Name Type Description Default
header dict

The recording's header, from read.

required
events list

Its events.

required

Returns:

Type Description
dict

A dict. The main keys: "story" (the race in plain words), "conflicts" (each with pattern,

dict

resource, the two requests a and b, and confidence: "certain" or "possible"),

dict

"moments" (the steps that matter, in order) and "requests".

deja.fileformat.read

read(path: str) -> tuple[dict, list]

Read a recording, upgrading an older format to the current one.

Parameters:

Name Type Description Default
path str

The .deja file.

required

Returns:

Type Description
tuple[dict, list]

(header, events), with each event as a tuple and bytes restored.

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(path: str, header: dict, events: list) -> None

Write a recording: gzipped JSON Lines, the header first and then one event per line.

Parameters:

Name Type Description Default
path str

The .deja file to write.

required
header dict

The header object; it must carry "format": "deja/1".

required
events list

The events, as tuples.

required

deja.fileformat.FormatError

Bases: ValueError

A recording this version of Déjà can't read.