Metadata-Version: 2.4
Name: subpoena
Version: 0.1.0a3
Summary: Trace-native testing: OpenTelemetry spans as the test interface, enforcement proven by an independent witness.
License: Apache-2.0
Project-URL: Homepage, https://subpoena.dev
Project-URL: Source, https://github.com/sprigworks/subpoena
Project-URL: Documentation, https://github.com/sprigworks/subpoena/blob/main/python/README.md
Project-URL: Changelog, https://github.com/sprigworks/subpoena/blob/main/CHANGELOG.md
Keywords: opentelemetry,testing,tracing,traceql,observability
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: opentelemetry-api<2,>=1.27
Requires-Dist: opentelemetry-sdk<2,>=1.27
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Requires-Dist: pyyaml>=6; extra == "test"
Requires-Dist: pytest-timeout>=2; extra == "test"
Dynamic: license-file

# Subpoena for Python

The Python port of Subpoena's tier-1 harness. It implements the parts of the
contract in [docs/ports.md](https://github.com/sprigworks/subpoena/blob/main/docs/ports.md)
listed below, checked by shared cases and Python fixtures against the Go contract.

| Part | Module | Checked by |
| --- | --- | --- |
| Harness (H1–H6) | `subpoena.harness` | [`conformance/harness.yaml`](https://github.com/sprigworks/subpoena/blob/main/conformance/harness.yaml), all cases |
| TraceQL subset (Q1–Q3) | `subpoena.traceql`, native, no Go needed | the whole corpus in `tests/test_traceql.py`, and `subpoena-conform` over `python -m subpoena.traceql`: 139 cases, 0 mismatches |
| Witness file (W3, W4) | `subpoena.witness` | [`conformance/witness.yaml`](https://github.com/sprigworks/subpoena/blob/main/conformance/witness.yaml), all cases, and the `witness.ReadLog` cases (`tests/test_witness.py`) |
| Absence checks (W5) | `subpoena.harness`: `no_spawn`, `require_no_spawn`, `check_no_spawn`, `watch_spawns`, `SpawnRule` | the same cases, and the `pkg/harness/watch_test.go` table (`tests/test_watch_spawns.py`) |
| Network absence (W6) | `subpoena.witness.Sinkhole`; `subpoena.harness`: `no_dial`, `require_no_dial`, `check_no_dial`, `dial_to` | the `pkg/witness/sinkhole_test.go` and `pkg/harness/network_test.go` cases (`tests/test_network.py`) |
| Invariants by name | `subpoena.invariants`: `load`, `names`; the nearest `invariants/` above the caller, or a given directory | `tests/test_invariants.py` |
| pytest fixtures | `subpoena.pytest_plugin` (loaded automatically): `subpoena_harness`, `subpoena_watch_spawns`, `subpoena_sinkhole` | `tests/test_pytest_plugin.py`, in a real inner pytest run |
| Session cgroups (W2) | `subpoena.cgroup`: `from_env`, `Manager.create`, `Group.start` / `add` / `procs` / `id` / `remove`, `session_trace` | the `pkg/cgroup/cgroup_test.go` cases (`tests/test_cgroup.py`); the real-cgroup case needs a writable cgroup v2 hierarchy |
| Production tiers | `subpoena.production`: `Exporter`, `collector_config`, `test_tier_keys` | `tests/test_production.py`: the `pkg/production` cases, and the collector config against [`examples/gateway/production/otelcol.yaml`](https://github.com/sprigworks/subpoena/blob/main/examples/gateway/production/otelcol.yaml) |
| Generated names | generated by Weaver from your registry, like [the example](https://github.com/sprigworks/subpoena/blob/main/generated/python/semconv.py) | `pkg/production/languages_test.go` |
| Cross-examination (G1) | `subpoena-cross <dir>` (`subpoena.cross`), groups, `-j`, `-select`, evidence | `tests/test_cross.py`, `tests/test_cross_parity.py`: verdicts and fail-closed parity on real pytest runs; CI runs the quickstart |
| Lint (L1) | `subpoena-lint <dir>` (`subpoena.lint`) | `tests/test_lint.py`: eight rules, import aliases and fail-closed load errors |

```
pip install subpoena
```

Python 3.9+; depends on `opentelemetry-api` and `opentelemetry-sdk` only.
Alpha: APIs will change.

```python
from subpoena.harness import Harness, require_absent, require_exists

from accounts import Database, delete_account

FORBIDDEN = '{ name = "db.erase" }'
DENIAL = '{ name = "delete_account.denied" && span.role = "viewer" }'


def test_viewer_cannot_delete_an_account():
    h = Harness()
    db = Database({"acct-1": "alice"})

    delete_account(db, h.tracer_provider, "viewer", "acct-1")  # inject the harness provider

    tr = h.collect()                 # before any assertion
    require_exists(tr, DENIAL)       # the denial is on the record
    require_absent(tr, FORBIDDEN)    # no erase span; Inconclusive fails too
    assert db.rows == {"acct-1": "alice"}
```

Trimmed from [`examples/python-quickstart`](https://github.com/sprigworks/subpoena/tree/main/examples/python-quickstart),
whose full test file also has an admin control test, and which CI
cross-examines.

Load a promoted query by name instead of pasting it, so the test asserts
the string that OATS and the alert rules use:
`require_absent(tr, invariants.load("no_exec_after_deny"))`.
`tr.query(q)` returns a `Result` holding `matches` and the snapshot's
`complete` flag; `tr.spans(trace_id)` returns one trace's spans.
Installing the package registers a pytest plugin with three fixtures.
`subpoena_harness` is a fresh `Harness`, shut down after the test.
`subpoena_watch_spawns(witness, trace_id, rule)` registers the teardown
check, which runs even after the test fails. `subpoena_sinkhole` is a running
`Sinkhole`, stopped at teardown. You still call `collect()` and stop the
sinkhole yourself before asserting, and Inconclusive still fails.

`collect()` raises `IncompleteError` (carrying the snapshot) if a span was
dropped, never ended, or lost attributes, events or links to span limits. Absence on an incomplete snapshot is Inconclusive, and
`require_absent` fails on it unless `allow_inconclusive=True` is passed.

## Development

From a checkout of [github.com/sprigworks/subpoena](https://github.com/sprigworks/subpoena):

```
make python        # venv, pytest, subpoena-conform
```

`make python` needs [uv](https://docs.astral.sh/uv/) and Go 1.25+ (for
`subpoena-conform`).

CI runs Python 3.9 and 3.12.

## Lint

```
subpoena-lint [-registry generated/python/semconv.py] [-invariants invariants] [-dead-telemetry] <dir>...
python -m subpoena.lint <dir>
```

The registry file and invariants directory are found by walking up from the
first target (invariants are found separately for each target). Registry data
is parsed with `ast`, never executed. `--registry`, `--invariants` and
`--dead-telemetry` are aliases for the flags above. Exit codes are 0 clean,
1 findings, 2 usage or load error. Unreadable files, invalid Python, missing
explicit configuration and star imports fail the run. Dot directories,
`testdata`, `vendor`, `venv`, `__pycache__` and `node_modules` are skipped.

The rules have the meanings in [lint/README.md](../lint/README.md):
`unknown-telemetry`, `no-trace-assertion`, `unwitnessed-enforcement`,
`unguarded-absence`, `missing-provenance`, `orphan-invariant`,
`provider-override`, and opt-in `dead-telemetry`. The separate `registry-drift`
subcommand remains Go-only. Span methods (`start_span`,
`start_as_current_span`, `update_name`), attribute methods (`set_attribute`,
`set_attributes`) and literal `attributes` dictionaries are checked. As in Go,
a literal equal to a registry name is accepted; prefer the generated constant.
Enum member values are not telemetry names.

Test modules (`test_*.py`, `*_test.py`, plus `conftest.py`) need
`# subpoena:spec_derived` or `# subpoena:impl_derived` before their first Python
statement. Helper-only files need provenance but need not collect. A
`# subpoena:pure_logic` header exempts collection only if the file imports no
telemetry. An enforcement point uses the same comment above `def` (or its
decorators) as `subpoena-cross`. Witness calls are checked across each target
tree, not per enforcement function, as in Go. A provider call is exempt only
with `# subpoena:own_provider <reason>` on its line or the line above, or
inside a non-test `if __name__ == "__main__":` block.

Resolution follows import aliases, direct assignments, imported constructors,
`Harness.tracer()`, `Harness.collect()`, `read_log()` and direct parameter
annotations. A different object's `collect()` or `spawned()` does not count.
Only a preceding, unconditional collection in the same function guards an
absence assertion; a nested function, lambda, conditional or comprehension
cannot establish that ordering. Unknown absence/query receivers are checked
by name, like Go's fallback; known unrelated receivers are excluded.

The lint reads source statically. It does no type checking and cannot prove
runtime behavior.
Dynamic imports, re-exports, string annotations, arbitrary factory functions,
fixtures, helper wrappers and fields storing harness objects are not inferred;
call the harness directly or annotate parameters with imported classes.
Functions and methods with a `test` prefix count, including unittest methods;
custom pytest filename patterns are not read. Imports are resolved file-wide
within module scope, and within their function scope. Branch bindings retain
uncertainty: a possible provider override is reported, while a conditional
harness binding cannot establish an unconditional collection. Cross-examination remains the
behavioral backstop. Keep `-dead-telemetry` for targets covering the whole
service; test references and the generated registry itself do not count as
application emissions.

## Cross-examination options

```
subpoena-cross -j 4 -select -evidence-dir ./cross-evidence ./my-service
```

`-j N` (`--jobs N`) runs single mutants in isolated copies, preserving discovery
order in the report. The default is 1. Group runs remain sequential.
`-select` (`--select`) records per-test line coverage using the Python standard
library. Each test runs alone, and each selected subset must be green without
mutation. Every selected non-kill is rerun against the whole suite; groups
always run the whole suite. Code reached only in a subprocess may not show up
in coverage, so full-suite fallback matters. Custom tracing or coverage plugins
can interfere with selection; omit `-select` when they do.

`-evidence-dir DIR` (`--evidence-dir DIR`) keeps full pytest output (`.txt`),
raw plugin records (`.jsonl`) and run metadata (`.json`) for baseline, coverage,
subset, single-mutant and group runs, including kills. Exclusive file creation
and a unique run prefix prevent concurrent runs from overwriting evidence.
Each result exposes its raw output path as `evidence_file`, also printed by the CLI.
An evidence directory inside the target is excluded from source copies.
These are raw, unsigned test records. Snapshot hashes cover
mutant-bearing files, not the complete build. Like the Go runner, source
copying is not atomic. Python discovers and hashes markers in the saved copy,
then makes each run's tree from it.

Layered controls use `group=<name>` on statement or guard markers:

```python
# subpoena:enforcement_point
def allowed(admin):
    if not admin:
        return False  # subpoena:enforcement group=access
    if not admin:  # subpoena:enforcement_guard false group=access
        return False
    return True
```

Groups must have 2–8 layers. A layer surviving alone is masked only when it
is killed together with other surviving layers. An independently killed layer
cannot mask another. Masked layers fail unless a reviewed `cross-masked.txt`
in the target names each one with a reason:

```
service.py | allowed | group=access | return False | first of two independent refusal layers
service.py | allowed | group=access | not admin | second independent refusal layer
```

Paths are relative to the target. Removed text is collapsed to one line.
Duplicate, ambiguous or malformed entries are errors; stale entries fail the
run. Never add a group or acceptance entry to hide a testable survivor. Keep
release checks at `-j 1`, or confirm parallel kills there: contention can alter
timing-sensitive tests. `--timeout` remains the per-run timeout in seconds.
