Skip to content

Demo Utilities

vultron.demo.utils provides the shared context managers, HTTP client, and setup/teardown helpers used by all demo scripts (DC-02-001).

Key Components

  • demo_step / demo_check / demo_gate — context managers for structured demo logging. demo_gate also skips the steps nested inside it when its precondition fails, so a dependent step must sit inside the gate body rather than after it.
  • check_tree — recording_checks() and CheckRecorder, which record each of those three blocks as one node of a run's check tree, with its kind, label, outcome and the cast members whose containers it read (DEMOCI-11-056, DEMOCI-11-057). The capture is off by default, so a demo run outside a recorder behaves exactly as before. It is imported from vultron.demo.utils.check_tree rather than from the package, so it does not appear in the module reference below.
  • DataLayerClient — HTTP client for the Vultron DataLayer REST API
  • demo_environment — context manager that sets up and tears down a clean DataLayer state around each demo run
  • setup_clean_environment — resets the DataLayer and returns the three default demo actors (Reporter, Vendor, Coordinator)
  • check_server_availability — polls the health endpoint until the API server is ready

Module Reference

vultron.demo.utils

Shared utilities for Vultron demo scripts.

Provides context managers, HTTP client helpers, and common setup/teardown functions used across all demo scripts (DC-02-001).

DataLayerClient

Bases: BaseModel

HTTP client for the Vultron DataLayer REST API.

Wraps httpx with convenience methods for GET, PUT, POST, and DELETE calls to the DataLayer endpoint, with automatic JSON parsing and error logging.

base_url addresses a container; actor_id names which of the actors that container hosts a DataLayer read is about. Both are needed under ADR-0073: a container may host more than one actor (a CaseActor co-hosted in a single-container exchange demo, say), so /datalayer/{case_id} alone no longer says whose replica to read. Use :meth:dl_path to build inspection paths rather than hand-writing /datalayer/....

call(method, path, **kwargs)

Make an HTTP request to the DataLayer API.

Parameters:

Name Type Description Default
method HTTPMethod

HTTP method (GET, PUT, POST, DELETE).

required
path str

API path relative to base_url.

required
**kwargs Any

Additional keyword arguments forwarded to httpx.request.

{}

Returns:

Type Description
Any

Parsed JSON response body. Most endpoints return a dict, but

Any

list endpoints (e.g. the case-ledger endpoint) return a list.

Any

An empty body, such as the inbox's 202 (IE-08-001), returns {}.

Raises:

Type Description
HTTPStatusError

When the response status is not OK.

delete(path, **kwargs)

Send an HTTP DELETE request.

dl_path(key='', actor_id=None)

Return the actor-scoped DataLayer inspection path for key.

Parameters:

Name Type Description Default
key str

Path suffix after /datalayer/ — an object id, a VulnerabilityCases/ style collection, or "" for the whole-store view.

''
actor_id str | None

Override the client's own actor_id. Needed when a container hosts more than one actor and the read is about a non-primary one — typically a self-hosted CaseActor.

None

Returns:

Type Description
str

/actors/{segment}/datalayer/{key}, where segment is the

str

actor's final URI path segment. The server recomputes the canonical

str

URI from its own base URL (ADR-0073), which is why the short segment

str

is what travels — the same convention already used for inbox and

str

trigger paths.

Raises:

Type Description
ValueError

When no actor is available. Failing here is deliberate: defaulting to some actor would silently report another replica's state and could let an ADR-0058 causal gate pass on the wrong actor's committed state.

get(path, **kwargs)

Send an HTTP GET request.

get_list(path, **kwargs)

Send an HTTP GET request that expects a JSON array response.

Parameters:

Name Type Description Default
path str

API path relative to base_url.

required
**kwargs Any

Additional keyword arguments forwarded to httpx.request.

{}

Returns:

Type Description
list[Any]

Parsed JSON response body as a list.

Raises:

Type Description
ValueError

When the response body is not a JSON array.

HTTPStatusError

When the response status is not OK.

post(path, **kwargs)

Send an HTTP POST request.

put(path, **kwargs)

Send an HTTP PUT request.

assert_demo_success()

Raise DemoFailureError if any demo step or check failures were recorded.

Call at the end of each scenario entry point. Raises with the full list of accumulated failure messages so that docker compose --exit-code-from can surface the non-zero exit to CI. See DEMOCI-01-001, DEMOCI-01-003.

bound_case_actor_client(base_url)

Return a client for the CaseActor container at base_url, bound to it.

The binding is what makes dl_path reads address the CaseActor's own store (ADR-0073); a scenario's entry point knows only the container's URL before any actor exists, so it binds from that (#1876).

case_actor_id_for_report(report_id)

Return the CaseActor URI a report's CaseProposal will be sent to.

The same identity for every report, because a CaseActor is a container, not a per-case object (#1872). report_id is retained so call sites still read as "the CaseActor for this report" and so the signature survives if the mapping ever stops being constant.

Raises:

Type Description
DemoCaseActorUnconfiguredError

No CaseActor service URL is configured (:func:configured_case_actor_id).

case_actor_id_on(base_url)

Return the canonical CaseActor URI hosted by the node at base_url.

Demo inspection clients need this to bind DataLayerClient.actor_id: the dedicated case-actor container hosts an actor whose store is the one a /datalayer/ read has to name (ADR-0073), and the container's base URL is the only thing a demo entry point knows before any actor exists.

Parameters:

Name Type Description Default
base_url str

Base URL of the container hosting the CaseActor, e.g. http://case-actor:7999/api/v2.

required

Returns:

Type Description
str

{base_url}/actors/case-actor.

case_references_report(case, report_id)

Return whether case lists the report report_id.

The single membership test behind every "which case did this report produce?" lookup, so a store holding several cases is never read as "the case".

check_server_availability(client, max_retries=30, retry_delay=1.0)

Poll the API health endpoint until the server is ready or retries are exhausted.

Parameters:

Name Type Description Default
client DataLayerClient

DataLayerClient whose base_url is used to build the health URL.

required
max_retries int

Maximum number of polling attempts (default: 30).

30
retry_delay float

Seconds to wait between attempts (default: 1.0).

1.0

Returns:

Type Description
bool

True if the server responds with HTTP 200; False otherwise.

configured_case_actor_id()

Return the configured CaseActor identity, or raise when none is set.

The identity comes from ActorConfig.case_actor_service_url (VULTRON_ACTOR__CASE_ACTOR_SERVICE_URL) only, never from this node's own server.base_url (CP-08-001, CP-08-009). A single-container topology configures the variable to its own API base, as docker/docker-compose.yml does.

Raises:

Type Description
DemoCaseActorUnconfiguredError

No CaseActor service URL is configured, so there is no CaseActor to propose a case to.

demo_check(description)

Context manager for declaring side-effect checks in demo logs.

Logs 📋 at INFO on entry, ✅ at INFO on clean exit, ❌ at ERROR on exception. On exception the failure is appended to the module-level _demo_failures accumulator and execution continues (no re-raise). Call assert_demo_success() at the end of the scenario to surface accumulated failures. See DEMOCI-01-003, DEMOCI-01-004.

demo_environment(client)

Context manager providing an isolated, clean DataLayer environment.

Sets up a clean environment on entry and tears it down on exit, even when the demo raises an exception (DC-03-001, DC-03-005).

Yields:

Type Description
Generator[tuple[as_Actor, as_Actor, as_Actor]]

Tuple of (reporter, vendor, coordinator) actors.

demo_failures()

The failures demo_step, demo_check and demo_gate recorded.

A read-only view, for the one caller that must know whether the run has already failed before it does work that depends on an act that may not have happened: a step mark whose role is read from the case cannot be checked when the act that granted the role failed (:func:~vultron.demo.helpers.story.run_story). It is not a way to branch on failure elsewhere — a demo helper records and skips through demo_gate, which keeps the first failure as the headline (DEMOCI-01-003).

demo_gate(description)

Context manager for causal preconditions in demo scripts.

Place the precondition check and the steps that depend on it inside this block. If the precondition raises, Python immediately exits the with body — the remaining dependent steps are skipped. The failure is recorded in the accumulator exactly as demo_check does (DEMOCI-01-003 is preserved), and the exception is suppressed so that execution continues after the block.

Scoping model — nested block:

Put the gating assertion at the top of the body, followed directly by the dependent steps:

with demo_gate("vendor has reached RM.VALID"):
    assert vendor_rm_state == "VALID"    # precondition: raises on fail
    with demo_step("5. Engage case"):    # skipped when gate fails
        engage_case(...)
    with demo_step("6. Do next thing"):  # also skipped when gate fails
        do_next(...)
# code here always runs — gate accumulates and suppresses the failure

Use demo_check for a standalone verification assertion that should not block subsequent steps. Use demo_gate when continuing after a failed precondition would produce meaningless secondary failures that bury the real cause.

See DEMOCI-01-007, EDF-06-005, ADR-0058.

demo_step(description)

Context manager for declaring workflow steps in demo logs.

Logs 🚥 at INFO on entry, 🟢 at INFO on clean exit, 🔴 at ERROR on exception. On exception the failure is appended to the module-level _demo_failures accumulator and execution continues (no re-raise). Call assert_demo_success() at the end of the scenario to surface accumulated failures. See DEMOCI-01-003, DEMOCI-01-004.

discover_actors(client)

Retrieve the Reporter, Vendor, and Coordinator actors from the DataLayer.

Returns:

Type Description
tuple[as_Actor, as_Actor, as_Actor]

A tuple of (reporter, vendor, coordinator) actor objects.

Raises:

Type Description
ValueError

If any of the three expected actors are not found.

get_offer_from_datalayer(client, vendor_id, offer_id)

Retrieve an Offer the vendor received, from its DataLayer store.

The Offer is read from the vendor's archive record for it (:func:require_received_activity): the vendor holds nothing under the sender's id (DL-06-006).

Parameters:

Name Type Description Default
client DataLayerClient

DataLayerClient instance.

required
vendor_id str

ID of the vendor actor that received the offer. Names the store to read, so the lookup does not depend on client's own binding.

required
offer_id str

ID of the offer to retrieve.

required

Returns:

Type Description
as_Offer

The retrieved offer as :class:as_Offer.

Raises:

Type Description
AssertionError

If the vendor holds no received Offer offer_id.

init_actor_ios(actors)

No-op retained for backward compatibility.

Inbox and outbox queues are now managed by the per-actor DataLayer (ADR-0012 ACT-2). No explicit initialization is required.

log_case_state(client, case_id, label, actor_id=None)

Fetch and log the current state of a case.

Parameters:

Name Type Description Default
client DataLayerClient

DataLayerClient for the container to read from.

required
case_id str

Id of the case to read.

required
label str

Short description of the point in the flow, for the log line.

required
actor_id str | None

Whose replica to read. Defaults to client's own actor. Participants hold their own replicas of a case (PCR), so the state logged is always some named actor's view of it, never "the" state.

None

logfmt(obj)

Format object for logging. Handles both Pydantic models and strings.

not_received_error(client, activity_id, actor_id=None, what='activity')

The failure for an actor that holds no received what activity_id.

post_to_inbox_and_wait(client, actor_id, activity, wait_seconds=None)

Deliver activity to actor_id's inbox through its sender's outbox.

An exchange demo builds the activity a peer would send. It is handed to the sender's own outbox on the same server (POST /actors/{sender}/outbox/), which checks the activity's actor is the sender, seals and signs it as its owner (SIG-05-004, SIG-01-001) and delivers it to the recipients its addressing names. Demo code never signs as an actor. The demo still stands in for the sender's adapter in one respect: it states the ledger position and sender number a peer in step with the receiver would state, which the outbox keeps (SYNC-18-001, SYNC-21-001).

An activity that names no recipient is addressed to actor_id; one whose addressing leaves actor_id out is refused before anything is sent. The wait is a gate, not a sleep (EDF-06): it polls the receiver until its record of the activity reaches an outcome -- archived, refused to a receipt stub, or held for a replay.

Parameters:

Name Type Description Default
client DataLayerClient

DataLayerClient instance.

required
actor_id str

ID of the receiving actor.

required
activity as_Activity

ActivityStreams activity its sender sends.

required
wait_seconds float | None

Most seconds to wait for the receiver's outcome; defaults to DELIVERY_OUTCOME_TIMEOUT.

None

Raises:

Type Description
ValueError

activity names no sender, or is addressed to others but not to actor_id.

AssertionError

The receiver reached no outcome in time.

post_to_trigger(client, actor_id, behavior, body, path_prefix='trigger')

POST to a trigger endpoint and return the response body. proactively (e.g. validate-report, engage-case) rather than reacting to an inbound activity.

Parameters:

Name Type Description Default
client DataLayerClient

DataLayerClient instance.

required
actor_id str

Full URI of the actor initiating the behavior.

required
behavior str

Kebab-case behavior name (e.g. "validate-report").

required
body dict

Request body dict (e.g. {"offer_id": "..."}).

required
path_prefix str

URL segment before the behavior name. Use "trigger" (default) for standard trigger endpoints and "demo" for demo-only endpoints such as add-note-to-case and sync-log-entry.

'trigger'

Returns:

Type Description
dict

Response dict from the trigger endpoint.

The (client, actor_id) pairing is no longer checked here: demo callers reach this through :class:vultron.demo.actor_session.ActorSession, which verifies that the client's container hosts the actor once at construction (DEMOMA-26-008). post_to_trigger MUST NOT be called directly outside this module and actor_session (DEMOMA-26-001).

postfmt(obj)

Serialize a Pydantic model (or plain object) to a JSON-encodable dict for POST bodies.

read_received_activities(client, activity_type, actor_id=None)

Every activity_type activity the actor received, as archived.

Read from the actor's ReceivedActivityRecord rows only, as :func:read_received_activity reads one.

Parameters:

Name Type Description Default
client DataLayerClient

DataLayerClient for the receiving actor's container.

required
activity_type str

The wire type of the activities wanted, e.g. "Accept".

required
actor_id str | None

Whose store to read. Defaults to client's own actor.

None

Raises:

Type Description
AssertionError

when a record found wraps no activity.

read_received_activity(client, activity_id, actor_id=None)

The activity activity_id as the receiving actor archived it, or None.

Reads the actor's ReceivedActivityRecord rows only and looks the record up by the key the receiver derives from the sender's id (:meth:ReceivedActivityRecord.build_id). A row stored under the sender's id is never read: a receiver holds no received activity under the sender's id (DL-06-006).

Unlike the core :func:~vultron.core.use_cases._helpers.read_received_activity, which falls back to the record holding an activity the inbox deferred and raises when nothing is held, this reads the archive only and returns None.

Parameters:

Name Type Description Default
client DataLayerClient

DataLayerClient for the receiving actor's container.

required
activity_id str

The sender's id for the activity.

required
actor_id str | None

Whose store to read. Defaults to client's own actor.

None

Raises:

Type Description
AssertionError

when the record found wraps no activity.

read_received_record(client, activity_id, actor_id=None)

The receiver's ReceivedActivityRecord for activity_id, as served.

The whole record, not only the activity it holds: its stage and the verified_proofs the inbox recorded on receipt (SIG-03-004). Looked up by the key the receiver derives from the sender's id (:meth:ReceivedActivityRecord.build_id, DL-06-006); None when the receiver holds no record of it.

Parameters:

Name Type Description Default
client DataLayerClient

DataLayerClient for the receiving actor's container.

required
activity_id str

The sender's id for the activity.

required
actor_id str | None

Whose store to read. Defaults to client's own actor.

None

read_stored_of_types(client, types, actor_id=None)

The actor's stored objects of types, keyed by id, as the store serves them.

One read of the type-filtered store route: a poll never dumps the whole store, whose rehydration slowed the container being polled as it grew (#4600). A reply that is not a mapping reads as holding nothing.

Parameters:

Name Type Description Default
client DataLayerClient

DataLayerClient for the actor's container.

required
types Sequence[str]

The stored types to read.

required
actor_id str | None

Whose store to read. Defaults to client's own actor.

None

received_activity_in(record)

The activity a served ReceivedActivityRecord record archives.

The record keeps the body that arrived, as JSON text (CLP-10-036, ADR-0149), so the activity is that body decoded: its sender's own wire form.

Raises:

Type Description
AssertionError

when the record holds no JSON object body.

received_activity_or_none(record)

The activity a served record holds, or None for a receipt stub.

A refused message leaves a stub with no body (CLP-10-018), so there is no activity in it to read. Use this where a sweep or a predicate runs over every one of an actor's received records; use :func:received_activity_in where the record is known to hold a body and its absence is a fault.

ref_id(value)

Return the ID of a string-or-AS2 reference, if present.

require_received_activity(client, activity_id, actor_id=None, what='activity')

The activity activity_id the actor received, as archived.

:func:read_received_activity, failing when nothing is archived.

Parameters:

Name Type Description Default
client DataLayerClient

DataLayerClient for the receiving actor's container.

required
activity_id str

The sender's id for the activity.

required
actor_id str | None

Whose store to read. Defaults to client's own actor.

None
what str

What the activity is, for the failure message.

'activity'

Raises:

Type Description
AssertionError

If the actor holds no received activity activity_id.

reset_datalayer(client)

Clear every store on the node client addresses, via the API.

Clearing only clears. The former init flag asked the server to seed default actors as part of the reset; provisioning is now the caller's job, via :func:seed_exchange_actors or :func:seed_actor (see the route docstring for why per-actor storage made the server-side seed unworkable).

Parameters:

Name Type Description Default
client DataLayerClient

DataLayerClient instance.

required

reset_demo_failures()

Clear the demo failure accumulator.

Call at the start of each scenario entry point to ensure failures from a previous run do not pollute the current one. See DEMOCI-01-003.

seed_actor(client, name, actor_type='Organization', actor_id=None)

Create or return an actor record in the remote DataLayer.

Calls POST /actors/ with the supplied parameters. The endpoint is idempotent: if an actor with the same actor_id already exists it is returned unchanged (HTTP 200).

Parameters:

Name Type Description Default
client DataLayerClient

DataLayerClient instance pointing at the target API server.

required
name str

Display name for the actor.

required
actor_type str

ActivityStreams actor type string (default: "Organization").

'Organization'
actor_id str | None

Optional full URI for the actor. When absent the server derives one from VULTRON_SERVER__BASE_URL. Must be under this node's authority; use :func:seed_peer for foreign-authority ids.

None

Returns:

Type Description
as_Actor

The created (or pre-existing) as_Actor object.

seed_case_actor(client)

Provision the CaseActor this container's reports are proposed to.

ProposeReportCaseToActorNode sends Create(CaseProposal) to a CaseActor whose URI it derives from the report, and delivery is an ordinary HTTP POST to that actor's inbox (ADR-0042). The inbox route resolves the actor from the store its URI names, so the CaseActor has to be a hosted actor before the proposal is delivered or the round-trip never starts.

The identity is stable: one CaseActor per container, whatever the report (#1872, closed). That is what lets a demo provision it before anything else happens -- before the submit-report trigger runs, when no report id exists yet -- instead of chasing a per-report id after the fact. The trigger's own outbox is then the sole delivery of the Offer; the demo never re-posts it.

In the exchange demos one container plays both the participant node and the CaseActor service, so that container is the one that must host it. Going through POST /actors/ is what puts the record in the CaseActor's own store, since the route opens the store the id names (ADR-0073).

Returns:

Type Description
as_Actor

The created (or pre-existing) CaseActor as an as_Actor.

seed_exchange_actors(client)

Create the Reporter, Vendor and Coordinator actors on client's node.

Each gets its own store, holding its own record, which is the whole of what a single-container exchange demo needs: the three actors reach each other by URL, and delivery derives a recipient's inbox from its URI alone (http_delivery), so no actor needs a stored copy of another's record.

Idempotent, because POST /actors/ is.

Returns:

Type Description
tuple[as_Actor, as_Actor, as_Actor]

A tuple of (reporter, vendor, coordinator) actors as created.

seed_peer(client, local_actor_id, peer_id, name, actor_type='Organization')

Register a peer in a hosted actor's address book.

Calls POST /actors/{slug}/peers/ on the target container. The peer is recorded as an address-book entry in local_actor_id's own store — it is not created as a hosted actor (ADR-0081). Idempotent: re-registering an already known peer returns the existing record with HTTP 200.

Parameters:

Name Type Description Default
client DataLayerClient

DataLayerClient instance pointing at the container that hosts local_actor_id.

required
local_actor_id str

Full URI of the hosted actor whose address book to update.

required
peer_id str

Full absolute URI of the peer actor to register.

required
name str

Display name for the peer.

required
actor_type str

ActivityStreams actor type string (default: "Organization").

'Organization'

Returns:

Type Description
as_Actor

The created (or pre-existing) peer as_Actor object.

served_field(obj, wire_key, field_name)

obj's field served as wire_key or, failing that, as field_name.

The store route serves a stored object under one of two shapes: an AS2 object's fields under their wire (camelCase) names, a bare core record's under their field names (attributed_to), so a reader that may get either shape reads both. The wire name wins when both are present.

setup_clean_environment(client)

Reset the node and provision the three default demo actors.

Clears every store on the node, then creates the Reporter, Vendor and Coordinator actors. The seeding step is explicit because clearing a node leaves it hosting nothing at all: under ADR-0073 there is no store that outlives the reset for a server-side init to populate.

Returns:

Type Description
tuple[as_Actor, as_Actor, as_Actor]

A tuple of (reporter, vendor, coordinator) actors.

setup_demo_logging()

Configure console logging for standalone demo script execution.

verify_object_stored(client, obj_id, actor_id=None)

Fetch an object from the DataLayer by ID and verify it is present.

Logs the stored representation so all fields are visible. Nested objects are stored as ID-string references (not inline copies); the log therefore shows ID strings for nested fields such as object_, target, etc. To inspect a nested object, call verify_object_stored again with the nested object's own ID.

Parameters:

Name Type Description Default
client DataLayerClient

DataLayerClient for the container to read from.

required
obj_id str

Id of the object to fetch.

required
actor_id str | None

Whose replica to look in. Defaults to client's own actor. "Is this object stored?" has no answer under ADR-0073 without naming an actor, so pass this whenever the read is about an actor other than the one the client is bound to — typically because the activity was delivered to a different recipient's inbox.

None

Returns:

Type Description
as_Object

The retrieved as_Object.

Raises:

Type Description
HTTPStatusError

If the object is not found.

verify_received_activity_stored(client, activity_id, actor_id=None)

Verify the receiving actor archived activity_id, and log it.

The received-activity counterpart of :func:verify_object_stored: an activity delivered to an actor's inbox is held in its archive record, never under the sender's id (DL-06-006).

Parameters:

Name Type Description Default
client DataLayerClient

DataLayerClient for the receiving actor's container.

required
activity_id str

The sender's id for the activity.

required
actor_id str | None

Whose store to read. Defaults to client's own actor.

None

Returns:

Type Description
dict

The archived activity, as the store serves it.

Raises:

Type Description
AssertionError

If the actor holds no received activity activity_id.