Skip to content

recorder

recorder

Orchestra timeline recorder (GH #468).

Subscribes to the EventBus, projects conductor events into the orchestra vocabulary, maintains the live fleet snapshot, appends each projected event to <orchestra_dir>/<YYYY-MM-DD>.jsonl and serves a bounded ring buffer to IPC readers.

The projection is deliberately lossy. A viewer sees which score is playing which sheet on which instrument and how it ended; never where the workspace is, what the prompt said, or why a sheet failed. The job_id is shown as given (operators name their scores), because the whole point is to watch the fleet by name.

Classes

OrchestraEvent

Bases: TypedDict

One projected event. Every field is public-safe by construction.

OrchestraRecorder

OrchestraRecorder(config)

EventBus subscriber projecting the fleet into the orchestra timeline.

Not thread-safe; runs on the conductor's event loop like the observer recorder. File writes are append-only and flushed per event: a viewer tailing today's file sees each beat within one write.

Source code in src/marianne/daemon/orchestra/recorder.py
def __init__(self, config: OrchestraConfig) -> None:
    self._config = config
    self._event_bus: EventBus | None = None
    self._sub_id: str | None = None
    self._recent: deque[OrchestraEvent] = deque(maxlen=config.ring_size)
    self._jobs: dict[str, _JobView] = {}
    self._handle: Any | None = None
    self._handle_day: str | None = None
    self._watchers: set[asyncio.Queue[OrchestraEvent]] = set()
Methods:
seed_job
seed_job(job, *, total_sheets, started_at, status='running')

Register a job the recorder did not see start (conductor restart).

Source code in src/marianne/daemon/orchestra/recorder.py
def seed_job(self, job: str, *, total_sheets: int | None, started_at: float | None,
             status: str = "running") -> None:
    """Register a job the recorder did not see start (conductor restart)."""
    view = self._jobs.get(job)
    if view is None:
        view = _JobView(job, started_at or time.time())
        self._jobs[job] = view
    view.total_sheets = total_sheets
    view.status = status
snapshot
snapshot()

The fleet as it stands: every job the recorder knows, newest first.

Source code in src/marianne/daemon/orchestra/recorder.py
def snapshot(self) -> dict[str, Any]:
    """The fleet as it stands: every job the recorder knows, newest first."""
    jobs = sorted(self._jobs.values(), key=lambda v: v.started_at, reverse=True)
    return {
        "ts": time.time(),
        "jobs": [v.to_dict() for v in jobs],
    }
watch
watch()

A bounded queue that receives every projected event from now on.

Source code in src/marianne/daemon/orchestra/recorder.py
def watch(self) -> asyncio.Queue[OrchestraEvent]:
    """A bounded queue that receives every projected event from now on."""
    queue: asyncio.Queue[OrchestraEvent] = asyncio.Queue(maxsize=self._config.ring_size)
    self._watchers.add(queue)
    return queue

Functions:

project_event

project_event(event)

Project a bus event into the orchestra vocabulary, or None to drop it.

Only whitelisted source events project, and only whitelisted fields are read from their payloads, so a new internal field can never leak.

Source code in src/marianne/daemon/orchestra/recorder.py
def project_event(event: ObserverEvent) -> OrchestraEvent | None:
    """Project a bus event into the orchestra vocabulary, or None to drop it.

    Only whitelisted source events project, and only whitelisted fields are
    read from their payloads, so a new internal field can never leak.
    """
    source = str(event.get("event", ""))
    mapping = _DIRECT.get(source)
    if mapping is None:
        return None
    kind, outcome = mapping
    data = event.get("data") or {}
    if not isinstance(data, dict):
        data = {}
    note: str | None = None
    if kind == "sheet.fallback":
        src = data.get("from_instrument")
        dst = data.get("to_instrument")
        if isinstance(src, str) and isinstance(dst, str):
            note = f"{src} -> {dst}"
    elif kind == "job.chain_refused":
        # The refusal message is free text (it can carry a resolved score
        # path or an exception string); the projection carries only a fixed
        # vocabulary word so no path or error text reaches the public page.
        note = _refusal_word(data.get("message"))
    elif kind == "job.chained":
        # Only a concert action is a chain; other trigger actions are not shown.
        actions = data.get("actions")
        if not isinstance(actions, list) or not any(
            isinstance(a, dict) and "concert" in a for a in actions
        ):
            return None
    sheet_raw = event.get("sheet_num")
    sheet = int(sheet_raw) if isinstance(sheet_raw, int) and sheet_raw > 0 else None
    attempt = data.get("attempt")
    if kind in {"sheet.dispatched", "sheet.ended"} and isinstance(attempt, int) and attempt > 1:
        note = f"attempt {attempt}"
    return {
        "ts": float(event.get("timestamp") or time.time()),
        "job": str(event.get("job_id", "")),
        "sheet": sheet,
        "kind": kind,
        "instrument": _instrument_of(data),
        "outcome": outcome,
        "note": note,
    }

read_day

read_day(path, *, limit=None)

Read one day's JSONL for replay; malformed lines are skipped.

Source code in src/marianne/daemon/orchestra/recorder.py
def read_day(path: Path, *, limit: int | None = None) -> list[OrchestraEvent]:
    """Read one day's JSONL for replay; malformed lines are skipped."""
    events: list[OrchestraEvent] = []
    try:
        with open(path, encoding="utf-8") as handle:
            for line in handle:
                line = line.strip()
                if not line:
                    continue
                try:
                    raw = json.loads(line)
                except ValueError:
                    continue
                if isinstance(raw, dict) and "kind" in raw and "job" in raw:
                    events.append(raw)  # type: ignore[arg-type]
    except OSError:
        return []
    return events[-limit:] if limit else events