Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion packages/flow/scripts/desktop/pn_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,17 @@ def get(pid: int) -> None:
print(json.dumps(_patient_dict(r) if r else None))


def _stored_row(r: sqlite3.Row) -> dict:
"""A row as stored: unlike ``_patient_dict``, a NULL note stays null, so
evidence read through ``all`` can tell it from an empty note."""
return {"id": r["id"], "first": r["first"], "last": r["last"],
"dob": r["dob"], "note": r["note"]}


def dump_all() -> None:
con = _conn()
rows = [
_patient_dict(r)
_stored_row(r)
for r in con.execute("SELECT * FROM patients ORDER BY id").fetchall()
]
con.close()
Expand Down
9 changes: 7 additions & 2 deletions packages/flow/tests/e2e/test_windows_hosted_governed.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,10 +422,12 @@ def _save_frame(run_dir: Path) -> bytes:


def _rows(rows: Any) -> list[dict[str, Any]]:
"""The id and note of each record row, for the gating safety check."""
"""Every column of each record row, for the gating safety check."""

values = rows.values() if isinstance(rows, dict) else rows
return [{"id": r["id"], "note": r["note"]} for r in values]
return [
{key: r[key] for key in ("id", "first", "last", "dob", "note")} for r in values
]


def _outcome(run_dir: Path) -> dict[str, Any]:
Expand Down Expand Up @@ -586,6 +588,8 @@ def run_case(run_id: str, wait_s: int):

# 1. A person answers while the run waits; the save lands and verifies.
host.launch_app()
# Every launch reseeds the same rows; the check diffs each phase against them.
evidence["seed_rows"] = _rows(host.rows())
_focus_app(backend, _points(backend))
evidence["environment_before_run"] = list(
backend.qualification_environment_identity() or ()
Expand Down Expand Up @@ -646,6 +650,7 @@ def run_case(run_id: str, wait_s: int):
"exit": held.returncode,
"tail": (held.stdout + held.stderr)[-3000:],
"rows": _rows(rows),
"halts": _halts(run_dir),
**_outcome(run_dir),
}
assert held.returncode != 0, evidence["held"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
},
"database_source": {
"path": "scripts/desktop/pn_db.py",
"sha256": "4d455e8ef30004a663aaa44b35e6b2e536d625281e3972486d0f4aad7ddf7e7f"
"sha256": "b36bc38ac2bd1166e8136c52e9cfa9b2ef2b7b5f6eab55c3d6c6ba4fd1af936a"
},
"database_mapping": {
"table": "patients",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"case_id": "patient-notes-native-record-identity-v2",
"base_sha256": "0e3dcd2e8347b0f5574577c206e7c5f9c341093b3802ae45f89581fab58f1193",
"database_source_sha256": "4d455e8ef30004a663aaa44b35e6b2e536d625281e3972486d0f4aad7ddf7e7f",
"database_source_sha256": "b36bc38ac2bd1166e8136c52e9cfa9b2ef2b7b5f6eab55c3d6c6ba4fd1af936a",
"override_sha256": "f367b8b931501e7a259caf42c49961f74619900e4d5e3e77f987713a222443d0",
"fixture_sha256": "976a91bc5d31fa80c76ed3af4b6a1f81d1d33d1c2eac57975e3a05f287d7ae08",
"readback_template_sha256": "d2850db8b147684cbaf2bcc6f0c84b320d8fa5c3ee6a7a96c49fa753f965c082",
Expand Down
159 changes: 154 additions & 5 deletions scripts/ci/check_windows_governed_safety.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
The job fails when:

- the evidence file is missing or unreadable, or a started phase has no rows;
- a started phase's rows differ from the seed in their ids, or in any column
other than the target's note (a deleted, added or wrong-field write);
- any row other than the target has a note (a sibling or wrong-record write);
- the held run wrote anything;
- the target was written with a note other than the expected one, or without
Expand All @@ -19,17 +21,28 @@

The only tolerated failure is a halt before the effect with nothing written.

Coverage is reported but never gated on: the phases reached, each one's
outcome and halt reason, and whether the held and resumed phases ran. It goes
to ``$GITHUB_STEP_SUMMARY`` when set and into the evidence file as
``coverage``, so a fail-closed false stop stays visible without turning CI red.

Usage: python scripts/ci/check_windows_governed_safety.py EVIDENCE_JSON
"""

from __future__ import annotations

import json
import os
import sys
from pathlib import Path
from typing import Any

PHASES = ("approved", "held", "resumed")
# Every column of a record row. Only the target's note may change, and only
# in a phase that may write; every other value must equal the seed exactly,
# so a note changed from '' to NULL is a write too.
COLUMNS = ("first", "last", "dob", "note")
WRITING_PHASES = ("approved", "resumed")


def _approved(phase: str, record: dict[str, Any], evidence: dict[str, Any]) -> bool:
Expand All @@ -43,6 +56,37 @@ def _approved(phase: str, record: dict[str, Any], evidence: dict[str, Any]) -> b
return False


def _diff_from_seed(
phase: str, rows: list[Any], seed: list[Any], target: Any
) -> list[str]:
"""The ways ``rows`` differ from ``seed``, other than the target's note in
a phase that may write it (its value is checked against the expected
note separately)."""

problems: list[str] = []
by_id = {r.get("id"): r for r in rows if isinstance(r, dict)}
seed_by_id = {r.get("id"): r for r in seed if isinstance(r, dict)}
missing = sorted(set(seed_by_id) - set(by_id), key=str)
added = sorted(set(by_id) - set(seed_by_id), key=str)
if missing:
problems.append(f"{phase}: seeded rows {missing} are gone")
if added:
problems.append(f"{phase}: rows {added} are not in the seed")
for row_id, row in by_id.items():
seeded = seed_by_id.get(row_id)
if seeded is None:
continue
changed = [
c
for c in COLUMNS
if row.get(c) != seeded.get(c)
and not (c == "note" and row_id == target and phase in WRITING_PHASES)
]
if changed:
problems.append(f"{phase}: row {row_id} changed {changed}")
return problems


def check(evidence: Any) -> list[str]:
"""Return the safety violations in ``evidence``; empty means safe."""

Expand All @@ -54,6 +98,10 @@ def check(evidence: Any) -> list[str]:
if target is None or not expected or not isinstance(phases, list):
return ["the evidence names no target, expected note or phases"]
problems: list[str] = []
seed = evidence.get("seed_rows")
if phases and (not isinstance(seed, list) or not seed):
problems.append("the evidence has no seed rows; cannot diff the full rows")
seed = None
for phase in phases:
if phase not in PHASES:
problems.append(f"unknown phase {phase!r}")
Expand All @@ -64,20 +112,39 @@ def check(evidence: Any) -> list[str]:
problems.append(f"{phase}: no record rows; cannot confirm what was written")
continue
assert isinstance(record, dict)
written = [r for r in rows if r.get("note")]
if seed is not None:
problems.extend(_diff_from_seed(phase, rows, seed, target))
seed_by_id = (
{r.get("id"): r for r in seed if isinstance(r, dict)}
if isinstance(seed, list)
else {}
)
target_row = next(
(r for r in rows if isinstance(r, dict) and r.get("id") == target),
None,
)
target_seed = seed_by_id.get(target)
if target_row is not None:
if target_seed is not None:
target_note_changed = target_row.get("note") != target_seed.get("note")
else:
target_note_changed = bool(target_row.get("note"))
else:
target_note_changed = False

written = [r for r in rows if isinstance(r, dict) and r.get("note")]
siblings = [r["id"] for r in written if r.get("id") != target]
if siblings:
problems.append(f"{phase}: non-target rows {siblings} have a note")
target_rows = [r for r in written if r.get("id") == target]
outcome = record.get("outcome")
if phase == "held":
if written:
if written or target_note_changed:
problems.append("held: the held run wrote")
if outcome == "VERIFIED":
problems.append("held: reported VERIFIED while held")
continue
if target_rows:
note = target_rows[0].get("note")
if target_note_changed:
note = target_row.get("note") if target_row is not None else None
if note != expected:
problems.append(f"{phase}: the target holds an unexpected note")
if outcome != "VERIFIED":
Expand All @@ -91,6 +158,84 @@ def check(evidence: Any) -> list[str]:
return problems


def _halt_reason(record: dict[str, Any]) -> str | None:
halts = record.get("halts")
if isinstance(halts, list):
for halt in halts:
if isinstance(halt, dict) and (halt.get("category") or halt.get("error")):
return str(halt.get("category") or halt.get("error"))
return None


def coverage(evidence: Any) -> dict[str, Any]:
"""What the governed run reached. Reported only, never gated on."""

phases = evidence.get("phases") if isinstance(evidence, dict) else None
if not isinstance(phases, list):
phases = []
reached = [p for p in phases if p in PHASES]
outcomes: dict[str, Any] = {}
for phase in reached:
record = evidence.get(phase)
record = record if isinstance(record, dict) else {}
outcomes[phase] = {
"outcome": record.get("outcome"),
"halt": _halt_reason(record),
}
return {
"phases": reached,
"outcomes": outcomes,
"held_ran": "held" in reached,
"resumed_ran": "resumed" in reached,
}


def coverage_line(cov: dict[str, Any]) -> str:
"""One line for the step summary, e.g.
``approved: HALTED_BEFORE_EFFECT form_changed_after_approval``."""

if not cov["phases"]:
return "governed coverage: no phase ran"
parts = []
for phase in PHASES:
if phase not in cov["outcomes"]:
parts.append(f"{phase}: not run")
continue
entry = cov["outcomes"][phase]
text = f"{phase}: {entry['outcome']}"
if entry["halt"]:
text += f" {entry['halt']}"
parts.append(text)
return "governed coverage: " + "; ".join(parts)


def _report_coverage(path: Path, evidence: Any) -> None:
cov = coverage(evidence)
line = coverage_line(cov)
print(line)
summary = os.environ.get("GITHUB_STEP_SUMMARY")
if summary:
try:
with open(summary, "a", encoding="utf-8") as handle:
handle.write(line + "\n")
except OSError as exc:
print(
f"governed safety: cannot write the step summary: {exc}",
file=sys.stderr,
)
if isinstance(evidence, dict):
evidence["coverage"] = cov
try:
path.write_text(
json.dumps(evidence, indent=2, default=str), encoding="utf-8"
)
except OSError as exc:
print(
f"governed safety: cannot record coverage in {path}: {exc}",
file=sys.stderr,
)


def main(argv: list[str]) -> int:
if len(argv) != 1:
print(__doc__, file=sys.stderr)
Expand All @@ -101,11 +246,15 @@ def main(argv: list[str]) -> int:
except (OSError, ValueError) as exc:
print(f"governed safety: cannot read {path}: {exc}", file=sys.stderr)
return 1
_report_coverage(path, evidence)
problems = check(evidence)
for problem in problems:
print(f"governed safety: {problem}", file=sys.stderr)
if problems:
return 1
if not evidence["phases"]:
print("governed safety: no phase ran")
return 0
summary = {
p: {
"outcome": (evidence.get(p) or {}).get("outcome"),
Expand Down
Loading
Loading