Skip to content

log_sources

log_sources

Shared log-source discovery for daemon-managed score runs.

Attributes

Classes

LogSource dataclass

LogSource(path, label, follow=False, job_filter=None, kind='workspace', state='available', alias_state='none', raw_state='redacted')

Concrete source that can contribute lines to an operator log view.

Attributes
source_id property
source_id

Stable-ish identifier for cross-surface display and tests.

Functions:

read_registry_job_metadata

read_registry_job_metadata(job_id, *, db_path=DAEMON_STATE_DB_PATH)

Read persisted job file metadata from the daemon registry.

Source code in src/marianne/core/log_sources.py
def read_registry_job_metadata(
    job_id: str,
    *,
    db_path: Path = DAEMON_STATE_DB_PATH,
) -> dict[str, str | None]:
    """Read persisted job file metadata from the daemon registry."""
    path = db_path.expanduser()
    if not path.exists() or path.stat().st_size == 0:
        return {}

    try:
        with sqlite3.connect(f"file:{path}?mode=ro", uri=True) as conn:
            conn.row_factory = sqlite3.Row
            row = conn.execute(
                """
                SELECT workspace, log_path, snapshot_path, config_path
                FROM jobs
                WHERE job_id = ?
                """,
                (job_id,),
            ).fetchone()
    except sqlite3.Error:
        return {}

    return dict(row) if row is not None else {}

line_matches_job

line_matches_job(line, job_id)

Return whether a log line belongs to a job.

Structured JSON records are matched by their job_id field first. A fallback remains for historical compact/spaced JSON strings and deterministic interactive transcript names.

Source code in src/marianne/core/log_sources.py
def line_matches_job(line: str, job_id: str) -> bool:
    """Return whether a log line belongs to a job.

    Structured JSON records are matched by their ``job_id`` field first. A
    fallback remains for historical compact/spaced JSON strings and deterministic
    interactive transcript names.
    """
    try:
        record = json.loads(line)
    except json.JSONDecodeError:
        record = None

    if isinstance(record, dict) and record.get("job_id") == job_id:
        return True

    needle_spaced = f'"job_id": "{job_id}"'
    needle_compact = f'"job_id":"{job_id}"'
    transcript_needle = f"mzt-{job_id}-"
    return (
        needle_spaced in line
        or needle_compact in line
        or transcript_needle in line
    )

iter_source_lines

iter_source_lines(source)

Read source lines, applying a job filter when required.

Source code in src/marianne/core/log_sources.py
def iter_source_lines(source: LogSource) -> list[str]:
    """Read source lines, applying a job filter when required."""
    with open(source.path, encoding="utf-8", errors="replace") as handle:
        if source.job_filter is None:
            return list(handle)
        return [
            line
            for line in handle
            if line_matches_job(line, source.job_filter)
        ]

source_has_lines

source_has_lines(source)

True when the source holds at least one line its filter admits.

Stops at the first match: the shared conductor log grows to tens of MB, and reading all of it to answer yes or no stalled every log lookup.

Source code in src/marianne/core/log_sources.py
def source_has_lines(source: LogSource) -> bool:
    """True when the source holds at least one line its filter admits.

    Stops at the first match: the shared conductor log grows to tens of MB,
    and reading all of it to answer yes or no stalled every log lookup.
    """
    with open(source.path, encoding="utf-8", errors="replace") as handle:
        if source.job_filter is None:
            return any(True for _ in handle)
        return any(line_matches_job(line, source.job_filter) for line in handle)

discover_job_log_sources

discover_job_log_sources(job_id, state, *, db_path=DAEMON_STATE_DB_PATH, registry_metadata=None, conductor_log_path=None, interactive_log_root=Path('~/.marianne/interactive-logs'))

Discover authoritative and compatibility log sources for a job.

Source code in src/marianne/core/log_sources.py
def discover_job_log_sources(
    job_id: str,
    state: CheckpointState,
    *,
    db_path: Path = DAEMON_STATE_DB_PATH,
    registry_metadata: dict[str, str | None] | None = None,
    conductor_log_path: Path | None = None,
    interactive_log_root: Path = Path("~/.marianne/interactive-logs"),
) -> list[LogSource]:
    """Discover authoritative and compatibility log sources for a job."""
    metadata = (
        registry_metadata
        if registry_metadata is not None
        else read_registry_job_metadata(job_id, db_path=db_path)
    )
    sources: list[LogSource] = []
    seen: set[Path] = set()

    _append_source(
        sources,
        seen,
        metadata.get("log_path"),
        "registry log_path",
        kind="registry",
        follow=state.status == JobStatus.RUNNING,
        alias_state="canonical",
    )

    workspaces: list[Path] = []
    if state.worktree_path:
        workspaces.append(Path(state.worktree_path))
    if metadata.get("workspace"):
        workspaces.append(Path(str(metadata["workspace"])))
    if isinstance(state.config_snapshot, dict):
        raw_workspace = state.config_snapshot.get("workspace")
        if raw_workspace:
            workspaces.append(Path(str(raw_workspace)))

    workspace_seen: set[Path] = set()
    for workspace in workspaces:
        try:
            resolved = workspace.expanduser().resolve()
        except OSError:
            resolved = workspace.expanduser()
        if resolved in workspace_seen:
            continue
        workspace_seen.add(resolved)
        _append_workspace_sources(sources, seen, resolved, state)

    snapshot_paths: list[Path] = []
    if metadata.get("snapshot_path"):
        snapshot_paths.append(Path(str(metadata["snapshot_path"])))
    snapshot_root = Path("~/.marianne/snapshots").expanduser() / job_id
    if snapshot_root.is_dir():
        snapshot_paths.extend(
            path for path in sorted(snapshot_root.iterdir(), reverse=True) if path.is_dir()
        )

    snapshot_seen: set[Path] = set()
    for snapshot_path in snapshot_paths:
        try:
            resolved = snapshot_path.expanduser().resolve()
        except OSError:
            resolved = snapshot_path.expanduser()
        if resolved in snapshot_seen:
            continue
        snapshot_seen.add(resolved)
        _append_snapshot_sources(sources, seen, resolved, job_id)

    _append_interactive_sources(
        sources,
        seen,
        job_id,
        state,
        interactive_log_root=interactive_log_root,
    )
    _append_conductor_sources(
        sources,
        seen,
        job_id,
        state,
        conductor_log_path=conductor_log_path or resolve_daemon_log_path(),
    )

    return sources