Skip to content

skip

skip

Runtime evaluation of skip_when command predicates (#360, renamed #119).

A score may declare, per sheet, a shell command that decides at dispatch time whether the sheet should be skipped:

skip_when:
  8: {command: 'grep -q "PHASES: 1" {workspace}/plan.md'}

Semantics (mirroring :class:SkipWhenCommand's own docstring):

  • exit 0 → the condition is met → SKIP the sheet.
  • exit non-zero → PROCEED (run the sheet normally).
  • timeout / spawn error / substitution error → PROCEED (fail-open).

The fail-open bias is deliberate and matches the model contract. The cost of a wrong-skip is silently dropping real work (invisible, unrecoverable); the cost of a wrong-proceed is one phantom instance (visible in logs, leaves an artifact). For brand-stake workflows, silent omission is the higher-severity failure, so a broken predicate must never cause a skip. Every fail-open path logs a WARNING so the misconfiguration is diagnosable.

This replicates the process-group-safe subprocess pattern from ValidationEngine._check_command_succeeds (execution/validation/engine.py) rather than importing it — the musician path must not depend on the validation engine, and the skip/proceed return shape differs from a ValidationResult. A future pass could unify both on a shared runner (see #360).

Classes

Functions:

evaluate_skip_command async

evaluate_skip_command(swc, *, workspace, context, sheet_num=None)

Evaluate a skip_when command predicate.

Parameters:

Name Type Description Default
swc SkipWhenCommand

The command rule (command string + timeout).

required
workspace Path

The sheet's workspace (substituted for {workspace}).

required
context dict[str, Any]

Template variables for {key} substitution (shell-quoted). workspace is injected/overridden from the workspace arg.

required
sheet_num int | None

Optional sheet number for log correlation.

None

Returns:

Type Description
bool

(should_skip, reason). should_skip is True only on a clean

str

exit-0; every error path returns (False, "") (fail-open).

Source code in src/marianne/daemon/baton/skip.py
async def evaluate_skip_command(
    swc: SkipWhenCommand,
    *,
    workspace: Path,
    context: dict[str, Any],
    sheet_num: int | None = None,
) -> tuple[bool, str]:
    """Evaluate a ``skip_when`` command predicate.

    Args:
        swc: The command rule (command string + timeout).
        workspace: The sheet's workspace (substituted for ``{workspace}``).
        context: Template variables for ``{key}`` substitution (shell-quoted).
            ``workspace`` is injected/overridden from the ``workspace`` arg.
        sheet_num: Optional sheet number for log correlation.

    Returns:
        ``(should_skip, reason)``. ``should_skip`` is True only on a clean
        exit-0; every error path returns ``(False, "")`` (fail-open).
    """
    if swc.command is None:
        _logger.warning(
            "baton.skip_command.no_command",
            extra={"sheet_num": sheet_num},
        )
        return (False, "")

    full_context = dict(context)
    full_context["workspace"] = str(workspace)

    try:
        expanded = _substitute(swc.command, full_context)
    except Exception as exc:  # noqa: BLE001 — structured logger reports baton.skip_command.substitution_failed  #  pragma: no cover — replace() is total, defensive
        _logger.warning(
            "baton.skip_command.substitution_failed",
            extra={"sheet_num": sheet_num, "error": str(exc), "command": _truncate(swc.command)},
        )
        return (False, "")

    proc: asyncio.subprocess.Process | None = None
    pgid: int | None = None
    timed_out = False
    try:
        try:
            proc = await asyncio.create_subprocess_exec(
                "bash", "-c", expanded,
                cwd=str(workspace),
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
                start_new_session=True,
            )
        except (OSError, ValueError) as exc:
            # Spawn failure (bad cwd, exec error). Fail-open.
            _logger.warning(
                "baton.skip_command.spawn_failed",
                extra={"sheet_num": sheet_num, "error": str(exc), "command": _truncate(expanded)},
            )
            return (False, "")

        if proc.pid is not None:
            try:
                pgid = os.getpgid(proc.pid)
            except ProcessLookupError:
                # The parent already exited (e.g. `cmd & exit 0`). It was
                # spawned with start_new_session=True, so it led its own
                # group and pgid == pid by construction; keep killing the
                # group its children inherited (GH #410, Blueprint i3).
                pgid = proc.pid

        # Daemon-own-group safety: if start_new_session failed and the child
        # shares the daemon's process group, a group kill would signal the
        # conductor itself. Abort and fail-open.
        if pgid is not None:
            try:
                daemon_pgid: int | None = os.getpgid(0)
            except ProcessLookupError:
                daemon_pgid = None
            if daemon_pgid is not None and pgid == daemon_pgid:
                try:
                    proc.kill()
                except ProcessLookupError:
                    pass
                try:
                    await proc.wait()
                except ProcessLookupError:
                    pass
                _logger.warning(
                    "baton.skip_command.shares_daemon_pgid",
                    extra={"sheet_num": sheet_num, "pgid": pgid},
                )
                return (False, "")

        # Wait the #406-safe way (GH #410): parent exit + bounded pipe drain +
        # group kill + descendant reap, so a backgrounded child that inherited
        # the pipes cannot make us burn the whole timeout.
        bounded = await run_bounded_command(
            proc,
            timeout_seconds=swc.timeout_seconds,
            pgid=pgid,
            context="skip_command",
        )
        timed_out = bounded.timed_out

        if timed_out:
            _logger.warning(
                "baton.skip_command.timeout",
                extra={
                    "sheet_num": sheet_num,
                    "timeout_seconds": swc.timeout_seconds,
                    "command": _truncate(expanded),
                },
            )
            return (False, "")

        if proc.returncode == 0:
            reason = f"skip_when exited 0: {_truncate(expanded)}"
            return (True, reason)
        return (False, "")

    except Exception as exc:  # noqa: BLE001 — structured logger reports baton.skip_command.error
        # Any unexpected runtime error: fail-open.
        _logger.warning(
            "baton.skip_command.error",
            extra={"sheet_num": sheet_num, "error": str(exc), "command": _truncate(expanded)},
        )
        return (False, "")