diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c080ec1..538fdee 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,6 +16,7 @@ concurrency: jobs: test: name: Python ${{ matrix.python }} on ${{ matrix.os }} + timeout-minutes: 10 runs-on: ${{ matrix.os }} strategy: fail-fast: false @@ -37,6 +38,9 @@ jobs: cache: pip - run: python -m pip install -r requirements-dev.txt - run: python -m pytest --cov=policy_engine --cov-report=term-missing + - name: Verify benchmark worker flow (not a timing gate) + if: matrix.os == 'windows-latest' && matrix.python == '3.11' + run: python scripts/benchmark_policy.py --group gateway --processes 1 --values 1 --loops 1 --warmups 0 - run: python -m build if: matrix.os == 'windows-latest' && matrix.python == '3.11' - run: python scripts/verify_distribution.py @@ -44,6 +48,7 @@ jobs: quality: runs-on: ubuntu-latest + timeout-minutes: 10 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -57,6 +62,8 @@ jobs: - run: python -m ruff check . - run: python -m mypy policy_engine - run: python -m pip_audit --local --progress-spinner off + - name: Verify all benchmark workloads (not a timing gate) + run: python scripts/benchmark_policy.py --processes 1 --values 1 --loops 1 --warmups 0 --timeout 30 - run: python -m build - run: python -m twine check dist/* - name: Verify distributions and installed journeys diff --git a/CHANGELOG.md b/CHANGELOG.md index bf3ad96..8f36beb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,8 @@ until the owner publishes a release. passing-suite evidence, and `pack` / `verify-artifact` / pinned `check` commands. - Public fail-closed `guarded_call` and opt-in minimized audit events; actual pinned-file consumer. - Self-contained offline schemas and automated wheel/sdist inventories plus installed journeys. +- Optional pyperf benchmark harness with 20 correctness-checked synthetic workloads, source/input + fingerprints, explicit timing boundaries, and cross-platform runner verification. - Direct Request construction now validates fields and bounded contexts before freezing; mixed-key batch errors remain structured; unpaired surrogates and integers over 4,096 bits are rejected. - A regression-tested agent-tool enforcement example covering explicit allow, explicit deny, diff --git a/README.md b/README.md index 298bca5..75eaa84 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,11 @@ CI runs the same meaningful checks across supported Python versions. A wheel-ins also part of release verification. The runtime intentionally has no third-party dependencies, so there is no application dependency lockfile; development tools are constrained in the `dev` extra. +For workload sizing and repeatable measurements, see [Performance](docs/PERFORMANCE.md). From a +checkout or source archive, the development extra installs pyperf for the correctness-checked +harness covering gateway, rule-scaling, and batch workloads. These tools are not required for +runtime installation or policy evaluation; the harness does not ship inside the runtime wheel. + ## Architecture The enforcement point creates a request and calls `PolicyEngine.evaluate`. Strict loading and diff --git a/ROADMAP.md b/ROADMAP.md index 6971925..8d97438 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -42,6 +42,10 @@ enforcement consumer are implemented. Further framework adapters, signing, and h follow representative-user demand, not block evaluation of the release candidate. The rationale is recorded in `docs/COMPETITIVE_LANDSCAPE.md`. +An optional, correctness-checked benchmark corpus now covers gateway, rule-scaling, and batch +workloads. Use `docs/PERFORMANCE.md` to characterize a target host; shared-runner timing is not a +production capacity guarantee. Representative consumer trials remain the next adoption gate. + ## Samsarix adoption - Define a public API, event, schema, artifact, or deployment contract before connecting to Samsarix Unified. diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md new file mode 100644 index 0000000..ddd1231 --- /dev/null +++ b/docs/PERFORMANCE.md @@ -0,0 +1,142 @@ +# Workload sizing and performance measurements + +Use these measurements to characterize this embedded Python library on **your** application host. +They do not establish production capacity, an SLA, service tail latency, or parity with another +policy engine. The corpus is synthetic and public, not a production trace or customer workload. + +## Run from a checkout or source archive + +Use the activated environment from the README, then install optional maintainer tools: + +```bash +python -m pip install -e ".[dev]" +python scripts/benchmark_policy.py --group gateway --fast -o gateway.json +python -m pyperf show gateway.json +python -m pyperf stats gateway.json +``` + +The development extra installs pyperf (and its platform-measurement dependency), not additional +runtime dependencies. The harness is in the source archive, not the runtime wheel, so run it from +a checkout or unpacked source archive. Use a **new** output filename; pyperf refuses to overwrite an +existing result. `--group` accepts `gateway`, +`scaling`, `batch`, or `all` (the default). Run with `--help` for pyperf's complete options. + +For a more substantial run, omit `--fast`. pyperf calibrates loop counts, excludes warmups, runs +separate worker processes, and retains samples and machine/interpreter metadata in JSON. Its +stability warnings matter: a short run on a busy desktop is exploratory, not a reliable regression +claim. No system tuning, priority changes, networking, or CPU affinity changes are requested by +the harness; pyperf may use CPUs already isolated by the host. Where supported, add `--timeout 30` +to bound each worker, not the entire suite. pyperf 2.10's pipe timeout cannot run on Windows Python +3.11 (missing `os.set_blocking`); the harness rejects that combination with a setup message. Use +Python 3.12+ for that option, or a supervisor/job-level timeout as in CI (10 minutes per job). +Without either limit the benchmark has no hard wall-clock deadline. Ctrl+C stops the run; +an interrupted output is not evidence +of a complete corpus run. Do not use memory tracing and call the resulting time normal latency. + +These choices follow pyperf's [benchmark methodology](https://pyperf.readthedocs.io/en/latest/run_benchmark.html) +and [runner options](https://pyperf.readthedocs.io/en/latest/runner.html). OPA's +[performance guidance](https://www.openpolicyagent.org/docs/policy-performance) also illustrates +why policy shape matters; the Samsarix corpus does not benchmark OPA or imply equivalent semantics. + +## Exactly what is timed + +All calls use the public API. Every selected operation is checked once before registration with +the timer. Tests additionally check the entire corpus, deterministic fingerprints, and rejection +of incorrect results. No policy/request loading, correctness assertion, or fixture generation is +included unless the workload explicitly names that operation. + +| Workload | Shape and timed boundary | +| --- | --- | +| `gateway.construct_engine` | Validate an in-memory 8-rule policy and compute its digest; excludes disk/JSON decoding. | +| `gateway.parse_request` | Validate and freeze one in-memory mapping with nested context. | +| `gateway.mapping_allow`, `mapping_deny`, `mapping_default` | Reuse an engine, validate a fresh mapping on each call, and evaluate. The explicit-deny input also matches the allow rule. | +| `gateway.parsed_allow`, `parsed_explain` | Evaluate an already validated Request; explanation variant retains the full trace but does not serialize it. | +| `gateway.guard_no_audit`, `guard_audit_json` | Evaluate a parsed request and run a constant-return callback; audit variant also serializes the minimized event to JSON and discards it. No disk, network, or durable audit is simulated. | +| `gateway.guard_denied_audit_json` | Evaluate an overlapping deny, serialize audit, raise/catch ActionDenied, return its Decision; callback is not executed. | +| `scaling.parsed_16_rules`, `parsed_128_rules`, `parsed_512_rules` | Two relevant gateway rules plus nonmatching tenant rules; one parsed allow request, all rules evaluated. | +| `scaling.parsed_64_conditions` | A two-rule policy whose allow rule has 64 matching conditions. | +| `scaling.parsed_64_patterns` | A two-rule policy whose allow rule matches the last of 64 resource patterns. | +| `batch.evaluate_1`, `evaluate_100`, `evaluate_1000` | Prevalidated batch, 8 rules, alternating allow/overlapping-deny inputs (size 1 is allow only). Includes construction of all decisions and the batch result. | +| `batch.parse_100` | Validate/freeze/correlate 100 in-memory request mappings; no evaluation. | +| `batch.evaluate_explain_json_100` | Evaluate 100 parsed requests with full explanations and serialize the whole response to JSON. | + +Times are **per named call**. Batch times are for the **whole batch**, not per decision. Dividing +by the request count gives an amortized cost, not single-request latency. Calibrated sample values +are averages over repeated calls; their percentiles are not production request p95/p99. +The benchmark includes normal Python call/loop overhead; nothing is subtracted as a guessed baseline. + +## Compare like with like + +```bash +python -m pyperf compare_to before.json after.json --table +``` + +Run both on the same quiet host, interpreter, power configuration, and pyperf version, with the +same group and settings. Alternate before/after runs and repeat before claiming a regression. +Confirm matching `corpus_version`, workload names, `workload_sha256`, and `harness_sha256` metadata. +`policy_engine_source_sha256` identifies the actually imported package's Python sources, including +when the checkout and installed wheel differ. Record the source commit or artifact hash separately; +a source fingerprint is content identity, not provenance attestation. The harness fingerprint is +the script's exact bytes, so line-ending changes can affect it. Changes to workload inputs, expected +semantics, or timing boundaries require a new corpus version and updated golden test. + +Raw pyperf JSON may include hostname, executable paths, CPU details, and other host metadata. +Inspect/redact it before sharing. The harness does not collect real requests, secrets, or production +events, and does not upload results. Store local raw measurements outside Git (for example in `dist/`). + +CI runs all corpus correctness tests and single-loop worker smoke checks on Linux and Windows. +These intentionally short runs can emit instability warnings. CI gates **execution and correctness**, +not nanosecond thresholds on shared runners; they must not be used as published speed claims. + +## Initial local characterization (exploratory) + +On August 31, 2026, the full v1 corpus completed on CPython 3.11.9, 64-bit Windows, with 8 logical +CPUs and `QueryPerformanceCounter` (100 ns reported resolution). The command used 3 worker processes, +3 measured values per process, 1 warmup, and a 30 ms minimum raw-value duration: + +```bash +python scripts/benchmark_policy.py --processes 3 --values 3 --warmups 1 --min-time 0.03 -o dist/workloads-20260831-final.json +``` + +| Selected whole-call workload | Mean ± sample standard deviation (9 values) | +| --- | ---: | +| Construct 8-rule engine | 2.25 ms ± 0.06 ms | +| Evaluate parsed request, 8 rules | 107 µs ± 28 µs | +| Validate mapping and evaluate, 8 rules | 330 µs ± 59 µs | +| Evaluate parsed request, 512 rules | 9.57 ms ± 0.48 ms | +| Evaluate parsed request, 64 matching conditions | 426 µs ± 24 µs | +| Evaluate parsed request, last of 64 patterns | 164 µs ± 5 µs | +| Evaluate prevalidated 100-request batch | 19.5 ms ± 0.6 ms | +| Parse/validate 100-request batch | 35.8 ms ± 3.6 ms | +| Evaluate and serialize explanations for 100 requests | 25.7 ms ± 0.9 ms | +| Evaluate prevalidated 1,000-request batch | 198 ms ± 5 ms | + +pyperf emitted stability warnings for multiple workloads: this desktop run did not meet its strict +criterion for a stable result. The differences illustrate the expected work boundaries and roughly +linear all-rule/all-request scans; they are **not** product latency claims, published baselines, or +capacity limits. Rerun on the actual deployment class with a quiet/tuned host before setting a budget. +The complete local JSON (not committed because it contains host metadata) had SHA-256 +`f157cc37c7e6ad818790d0062258fda71eb210adfe0bfeb8a2429284ff44542b` and contained all 20 +workloads. Its package-source fingerprint was +`9a56a5c8511d3b50cf0e762af55a15ded7c417856171998717c75a55b466f43f`; harness fingerprint was +`c7e8c9657633ec845df7126a891ead9b422e1d1d1ea4f97f0fb3109ebf785adb`. These are evidence for +that local run only, not authenticity or reproducible archive hashes. + +## Application guidance and limits + +- Construct and reuse one PolicyEngine per selected immutable policy. `decide` rebuilds it for + one-shot convenience; it is not the repeated-request fast path. +- A reused Request avoids repeated validation only when its exact immutable attributes are still + current and trusted. Rebuild requests when identity, resource state, context, or permissions change. + Do not cache decisions based only on principal/action/resource or bypass validation for speed. +- The evaluator scans all rules and collects every match, including on explicit deny. Increasing + rules, patterns, conditions, list lengths, or requested explanations can increase CPU and allocation. +- Batch evaluation is sequential, not parallel, atomic enforcement, or a server-side bulk endpoint. + The maximum 1,000 requests and 512 rules are input ceilings, not recommended batch sizes or latency + guarantees. Combined worst cases and large context/list values need application-specific testing. +- Explanation JSON size and audit durability may dominate actual integration cost. Add your own + storage, transport, concurrency, cancellation, resource-state checks, and actual operation timing + before making a production budget. Synchronous evaluation has no built-in deadline/cancellation. + +Policy evaluation remains local CPU/memory work with no model/token/network fees. Benchmarking uses +synthetic non-production evaluations; no change to the existing license grant is implied. diff --git a/docs/PRODUCTIZATION.md b/docs/PRODUCTIZATION.md index 352b259..449c984 100644 --- a/docs/PRODUCTIZATION.md +++ b/docs/PRODUCTIZATION.md @@ -273,9 +273,27 @@ identity. No other repository, website, account, infrastructure, or Git history 1. Representative integration trials: attribute construction, enforcement coverage, expected load, licensing fit, and support expectations. -2. Measured benchmark corpus and workload-specific batch/explanation limits if needed. +2. Apply the implemented benchmark corpus (`docs/PERFORMANCE.md`) to the target deployment host + and actual policy shapes; set application-specific batch/explanation budgets from those trials. 3. Framework adapters driven by those trials; signing/hot reload only with explicit requirements. No general-purpose hosted control plane is planned for this library. Disposition: **engineering release candidate with named external gates**, not a published or independently production-validated offering. Optional roadmap items are not core-path placeholders. + +## 2026-08-31 workload-characterization increment + +Added a versioned 20-workload synthetic corpus and optional pyperf harness for the public API. It +separates engine construction, request parsing, mapping/parsed evaluation, allow/deny/audit guard +paths, rule/pattern/condition scaling, batch parsing, batch evaluation, and explained JSON output. +Every timed operation has an untimed correctness preflight, deterministic input fingerprint, source +fingerprint, and harness fingerprint. Unit tests cover every case; Linux and Windows CI execute the +actual worker flow without using shared-runner timings as thresholds. `docs/PERFORMANCE.md` records +exact timing boundaries, a deliberately caveated local characterization, privacy considerations, +and comparison methodology. Runtime dependencies remain empty; pyperf is a development-only tool. + +The local run confirmed a material workload-shape effect and the expected sequential all-rule scan, +but emitted stability warnings on the desktop host. It is evidence that the corpus works, not a +latency claim or replacement for representative consumer trials. Application-specific performance +budgets, production security review, license confirmation, package publication, and actual adoption +remain owner/external gates. diff --git a/pyproject.toml b/pyproject.toml index fd5677c..727ae47 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,6 +36,7 @@ dev = [ "mypy>=1.15,<3", "pip-audit>=2.7,<3", "pip>=26.2,<27", + "pyperf>=2.10,<3", "pytest>=8,<10", "pytest-cov>=6,<8", "ruff>=0.11,<1", diff --git a/scripts/benchmark_policy.py b/scripts/benchmark_policy.py new file mode 100644 index 0000000..ef4829f --- /dev/null +++ b/scripts/benchmark_policy.py @@ -0,0 +1,392 @@ +"""Correctness-checked synthetic workloads; optional pyperf runner, not a runtime API.""" + +from __future__ import annotations + +import hashlib +import json +import os +from collections.abc import Callable +from dataclasses import dataclass +from functools import partial +from pathlib import Path +from typing import Any + +import policy_engine +from policy_engine import ( + ActionDenied, + AuditEvent, + BatchDecision, + BatchRequest, + Decision, + PolicyEngine, + Request, + evaluate_batch, + guarded_call, + parse_batch, + parse_request, +) + +CORPUS_VERSION = "samsarix-workloads-v1" +GROUPS = ("gateway", "scaling", "batch") + + +def fingerprint(value: Any) -> str: + """Hash the exact generated JSON inputs, independent of object key order.""" + encoded = json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + return hashlib.sha256(encoded).hexdigest() + + +def package_fingerprint() -> str: + """Identify measured Python sources without relying on a possibly unrelated Git checkout.""" + root = Path(policy_engine.__file__).resolve().parent + digest = hashlib.sha256() + for path in sorted(root.rglob("*.py")): + digest.update(path.relative_to(root).as_posix().encode() + b"\0") + digest.update(hashlib.sha256(path.read_bytes()).digest()) + return digest.hexdigest() + + +def gateway_policy(rule_count: int = 8) -> dict[str, Any]: + """Build two relevant rules plus nonmatching tenant rules for deterministic scale tests.""" + if not 2 <= rule_count <= 512: + raise ValueError("rule_count must be between 2 and 512") + rules = [ + { + "id": "allow-docs", + "effect": "allow", + "principals": ["agent:docs"], + "actions": ["file.read"], + "resources": ["workspace/public/*"], + "when": { + "environment": {"equals": "development"}, + "subject.team": {"equals": "docs"}, + "roles": {"contains": "reader"}, + "risk": {"lte": 3}, + }, + }, + { + "id": "deny-secrets", + "effect": "deny", + "actions": ["file.*"], + "resources": ["*.env", "*/secrets/*"], + }, + ] + rules.extend( + { + "id": f"tenant-{index}", + "effect": "allow", + "principals": [f"tenant:{index}:*"], + "actions": ["file.read", "file.write"], + "resources": [f"tenant/{index}/*"], + "when": {"approved": {"equals": True}}, + } + for index in range(rule_count - 2) + ) + return {"schema_version": 1, "id": "benchmark-gateway", "rules": rules} + + +def gateway_request(index: int = 0, outcome: str = "allow") -> dict[str, Any]: + """Generate synthetic attributes only; the deny case matches both relevant rules.""" + if outcome not in ("allow", "deny", "default"): + raise ValueError("unknown outcome") + return { + "request_id": f"request-{index}", + "principal": "agent:docs", + "action": "file.write" if outcome == "default" else "file.read", + "resource": "workspace/public/secrets/key" if outcome == "deny" else "workspace/public/doc", + "context": { + "environment": "development", + "subject": {"team": "docs"}, + "roles": ["reader", "contributor"], + "risk": 1, + "approved": False, + }, + } + + +def _check_decision(result: object, *, outcome: str, explain: bool = False) -> None: + """Verify precedence, correlation, and trace shape before any timed sample.""" + if not isinstance(result, Decision): + raise AssertionError("expected Decision") + expected_reason = { + "allow": "explicit_allow", + "deny": "explicit_deny", + "default": "default_deny", + } + expected_allow = () if outcome == "default" else ("allow-docs",) + expected_deny = ("deny-secrets",) if outcome == "deny" else () + if ( + result.allowed != (outcome == "allow") + or result.reason != expected_reason[outcome] + or result.allow_rule_ids != expected_allow + or result.deny_rule_ids != expected_deny + or result.request_id != "request-0" + or (result.evaluations is not None) != explain + or (explain and len(result.evaluations or ()) != 8) + ): + raise AssertionError("gateway decision contract changed") + + +def _serialize_audit(event: AuditEvent) -> None: + """Measure minimized JSON conversion without retaining events or pretending to persist them.""" + json.dumps(event.to_dict(), sort_keys=True, separators=(",", ":")) + + +def _operation() -> str: + """A fixed callback isolates guard overhead; real operation cost is intentionally excluded.""" + return "executed" + + +def _guard_denied(engine: PolicyEngine, request: Request) -> Decision: + """Include the public denial exception path, never a sensitive real operation.""" + try: + guarded_call(engine, request, _operation, audit_sink=_serialize_audit) + except ActionDenied as exc: + return exc.decision + raise AssertionError("denied callback was authorized") + + +def _equal(expected: object, result: object) -> None: + if result != expected: + raise AssertionError("benchmark result did not match its fixture") + + +def _check_batch(result: object, *, count: int, serialized: bool = False) -> None: + """Assert every ordered result, not just a matching allow count.""" + if serialized: + if not isinstance(result, str): + raise AssertionError("expected JSON batch") + document = json.loads(result) + decisions = document["decisions"] + else: + if not isinstance(result, BatchDecision): + raise AssertionError("expected BatchDecision") + decisions = [decision.to_dict() for decision in result.decisions] + expected = [ + ( + f"request-{index}", + index % 2 == 0, + "explicit_allow" if index % 2 == 0 else "explicit_deny", + ) + for index in range(count) + ] + actual = [(item["request_id"], item["allowed"], item["reason"]) for item in decisions] + _equal(expected, actual) + for index, item in enumerate(decisions): + _equal(["allow-docs"], item["allow_rule_ids"]) + _equal([] if index % 2 == 0 else ["deny-secrets"], item["deny_rule_ids"]) + _equal(serialized, "evaluations" in item) + if serialized: + _equal(8, len(item["evaluations"])) + + +@dataclass(frozen=True) +class Workload: + """A timed public-API call plus untimed correctness and reproducibility information.""" + + name: str + group: str + operation: Callable[[], object] + check: Callable[[object], None] + metadata: dict[str, str | int] + + def verify(self) -> None: + """Run the exact timed operation once and reject invalid benchmark output.""" + self.check(self.operation()) + + +def workloads() -> tuple[Workload, ...]: + """Return a fixed, bounded corpus; never import user policies or production data.""" + cases: list[Workload] = [] + policy = gateway_policy() + engine = PolicyEngine(policy) + document = gateway_request() + request = parse_request(document) + + def add(name, group, operation, check, *, policy_doc=policy, inputs=document, units=1): + cases.append( + Workload( + name, + group, + operation, + check, + { + "corpus_version": CORPUS_VERSION, + "workload_sha256": fingerprint({"policy": policy_doc, "inputs": inputs}), + "rule_count": len(policy_doc["rules"]), + "requests_per_call": units, + }, + ) + ) + + add( + "gateway.construct_engine", + "gateway", + partial(PolicyEngine, policy), + lambda value: _equal(engine.policy_digest, value.policy_digest), + ) + add( + "gateway.parse_request", + "gateway", + partial(parse_request, document), + partial(_equal, request), + ) + for outcome in ("allow", "deny", "default"): + raw = gateway_request(outcome=outcome) + add( + f"gateway.mapping_{outcome}", + "gateway", + partial(engine.evaluate, raw), + partial(_check_decision, outcome=outcome), + inputs=raw, + ) + for explain in (False, True): + add( + "gateway.parsed_explain" if explain else "gateway.parsed_allow", + "gateway", + partial(engine.evaluate, request, explain=explain), + partial(_check_decision, outcome="allow", explain=explain), + ) + for audit in (False, True): + add( + "gateway.guard_audit_json" if audit else "gateway.guard_no_audit", + "gateway", + partial( + guarded_call, + engine, + request, + _operation, + audit_sink=_serialize_audit if audit else None, + ), + partial(_equal, "executed"), + ) + denied = gateway_request(outcome="deny") + add( + "gateway.guard_denied_audit_json", + "gateway", + partial(_guard_denied, engine, parse_request(denied)), + partial(_check_decision, outcome="deny"), + inputs=denied, + ) + + for count in (16, 128, 512): + scaled_policy = gateway_policy(count) + scaled_engine = PolicyEngine(scaled_policy) + add( + f"scaling.parsed_{count}_rules", + "scaling", + partial(scaled_engine.evaluate, request), + partial(_check_decision, outcome="allow"), + policy_doc=scaled_policy, + ) + dense_policy = gateway_policy(2) + dense_policy["rules"][0]["when"] = {f"field_{index}": {"equals": index} for index in range(64)} + dense_request = gateway_request() + dense_request["context"] = {f"field_{index}": index for index in range(64)} + add( + "scaling.parsed_64_conditions", + "scaling", + partial(PolicyEngine(dense_policy).evaluate, parse_request(dense_request)), + partial(_check_decision, outcome="allow"), + policy_doc=dense_policy, + inputs=dense_request, + ) + pattern_policy = gateway_policy(2) + pattern_policy["rules"][0]["resources"] = [f"other/{index}/*" for index in range(63)] + [ + "workspace/public/*" + ] + add( + "scaling.parsed_64_patterns", + "scaling", + partial(PolicyEngine(pattern_policy).evaluate, request), + partial(_check_decision, outcome="allow"), + policy_doc=pattern_policy, + ) + + for count in (1, 100, 1000): + batch_doc = { + "schema_version": 1, + "requests": [ + gateway_request(index, "allow" if index % 2 == 0 else "deny") + for index in range(count) + ], + } + batch = parse_batch(batch_doc) + add( + f"batch.evaluate_{count}", + "batch", + partial(evaluate_batch, engine, batch), + partial(_check_batch, count=count), + inputs=batch_doc, + units=count, + ) + if count == 100: + add( + "batch.parse_100", + "batch", + partial(parse_batch, batch_doc), + partial(_equal, batch), + inputs=batch_doc, + units=count, + ) + add( + "batch.evaluate_explain_json_100", + "batch", + partial(_batch_json, engine, batch), + partial(_check_batch, count=count, serialized=True), + inputs=batch_doc, + units=count, + ) + return tuple(cases) + + +def _batch_json(engine: PolicyEngine, batch: BatchRequest) -> str: + """Include evaluation, full explanations, and JSON serialization, but not network transport.""" + return json.dumps(evaluate_batch(engine, batch, explain=True).to_dict(), separators=(",", ":")) + + +def check_timeout_support(timeout: float | None) -> None: + """Reject pyperf's unsupported Windows Python 3.11 pipe timeout before spawning workers.""" + if timeout is not None and not hasattr(os, "set_blocking"): + raise ValueError( + "--timeout requires os.set_blocking (unavailable on Windows Python 3.11); " + "use Python 3.12+ or omit this option and apply an external job timeout" + ) + + +def main() -> None: + """Run selected workloads with pyperf's isolated workers and calibrated loops.""" + try: + import pyperf + except ImportError: + raise SystemExit( + 'Install the optional tools first: python -m pip install -e ".[dev]"' + ) from None + + def worker_args(command, args): + command.extend(("--group", args.group)) + + runner = pyperf.Runner(add_cmdline_args=worker_args) + runner.argparser.add_argument("--group", choices=("all", *GROUPS), default="all") + args = runner.parse_args() + try: + check_timeout_support(args.timeout) + except ValueError as exc: + runner.argparser.error(str(exc)) + runner.metadata.update( + { + "policy_engine_version": policy_engine.__version__, + "policy_engine_source_sha256": package_fingerprint(), + "harness_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + "timing_boundary": "one call; batch values are per whole batch, not per decision", + } + ) + for case in workloads(): + if args.group not in ("all", case.group): + continue + case.verify() + runner.bench_func(case.name, case.operation, metadata=case.metadata) + + +if __name__ == "__main__": + main() diff --git a/scripts/verify_distribution.py b/scripts/verify_distribution.py index e19f9a1..d18c5b2 100644 --- a/scripts/verify_distribution.py +++ b/scripts/verify_distribution.py @@ -39,6 +39,8 @@ def main() -> None: for directory in ("docs", "examples", "tests", "scripts"): assert any(name.startswith(directory + "/") for name in names), directory assert "requirements-dev.txt" in names + assert "scripts/benchmark_policy.py" in names + assert "docs/PERFORMANCE.md" in names assert not any( part in {".venv", ".git", "__pycache__", "helix_core"} for name in names diff --git a/tests/test_benchmark_workloads.py b/tests/test_benchmark_workloads.py new file mode 100644 index 0000000..5d0994d --- /dev/null +++ b/tests/test_benchmark_workloads.py @@ -0,0 +1,84 @@ +"""Correctness and reproducibility tests for the optional benchmark corpus, without timing gates.""" + +from __future__ import annotations + +import runpy +from pathlib import Path + +import pytest + +BENCHMARK = runpy.run_path( + str(Path(__file__).resolve().parents[1] / "scripts" / "benchmark_policy.py") +) + + +def test_every_benchmark_verifies_its_timed_operation(): + cases = BENCHMARK["workloads"]() + assert len(cases) == 20 + assert len({case.name for case in cases}) == len(cases) + assert {case.group for case in cases} == set(BENCHMARK["GROUPS"]) + for case in cases: + case.verify() + assert len(case.metadata["workload_sha256"]) == 64 + assert case.metadata["corpus_version"] == "samsarix-workloads-v1" + + +def test_corpus_inputs_are_repeatable_and_detached(): + first = BENCHMARK["workloads"]() + second = BENCHMARK["workloads"]() + assert [(c.name, c.metadata) for c in first] == [(c.name, c.metadata) for c in second] + one = BENCHMARK["gateway_policy"]() + one["rules"].clear() + assert len(BENCHMARK["gateway_policy"]()["rules"]) == 8 + assert BENCHMARK["fingerprint"]({"a": 1, "b": 2}) == BENCHMARK["fingerprint"]({"b": 2, "a": 1}) + assert BENCHMARK["fingerprint"]({"a": 2}) != BENCHMARK["fingerprint"]({"a": 1}) + assert len(BENCHMARK["package_fingerprint"]()) == 64 + assert BENCHMARK["fingerprint"]([(c.name, c.metadata) for c in first]) == ( + "39581f5eccfc9a3468f7cc5a66f6f8a288c7ddc314394dc394d7b044d48c5508" + ) + + +def test_workload_preflight_rejects_wrong_results(): + for case in BENCHMARK["workloads"](): + with pytest.raises((AssertionError, AttributeError)): + case.check(None) + + +@pytest.mark.parametrize("count", [0, 1, 513]) +def test_rule_scaling_cannot_exceed_runtime_limits(count): + with pytest.raises(ValueError): + BENCHMARK["gateway_policy"](count) + + +def test_unknown_request_outcome_rejected(): + with pytest.raises(ValueError): + BENCHMARK["gateway_request"](outcome="invalid") + + +def test_unsupported_worker_timeout_has_an_actionable_error(monkeypatch): + monkeypatch.delattr(BENCHMARK["os"], "set_blocking", raising=False) + BENCHMARK["check_timeout_support"](None) + with pytest.raises(ValueError, match="external job timeout"): + BENCHMARK["check_timeout_support"](30) + + +def test_guard_workloads_exercise_both_audited_paths(monkeypatch): + events = [] + monkeypatch.setitem(BENCHMARK["workloads"].__globals__, "_serialize_audit", events.append) + cases = {case.name: case for case in BENCHMARK["workloads"]()} + cases["gateway.guard_no_audit"].verify() + assert not events + cases["gateway.guard_audit_json"].verify() + cases["gateway.guard_denied_audit_json"].verify() + assert [event.allowed for event in events] == [True, False] + assert all(event.request_id is None for event in events) + + +def test_batch_json_preflight_rejects_missing_explanations(): + import json + + case = next(c for c in BENCHMARK["workloads"]() if c.name == "batch.evaluate_explain_json_100") + result = json.loads(case.operation()) + del result["decisions"][0]["evaluations"] + with pytest.raises(AssertionError): + case.check(json.dumps(result)) diff --git a/tests/test_package.py b/tests/test_package.py index dfe1c4b..551369c 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -100,6 +100,16 @@ def test_distribution_and_api_versions_match() -> None: assert distribution.get_all("License-File") == ["LICENSE"] +def test_benchmark_tools_do_not_become_runtime_dependencies() -> None: + distribution = metadata("samsarix-policy-engine") + requirements = distribution.get_all("Requires-Dist", []) + assert requirements + assert all("extra ==" in requirement for requirement in requirements) + benchmark = [requirement for requirement in requirements if requirement.startswith("pyperf")] + assert len(benchmark) == 1 + assert 'extra == "dev"' in benchmark[0] + + def test_license_uses_standard_busl_parameters() -> None: license_text = (ROOT / "LICENSE").read_text(encoding="utf-8")