Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
| Three verdict tiers, entity-scoped frames and shadow mode by default: with `frame.database.entity_tables` (derived by `learn entities` from the setup: main tables, the tables a contract reads through, and the acting user's table), a row added or changed outside the entity tables (a scheduler, a queue, a recomputed total, a notification) is a logged side effect on a CONFIRMED result, by names only, and a candidate for the learner; a removed row, any entity-table row the write doesn't declare, another user's row and an unexcused column of the actor's row still refute. Settling ignores motion outside the scope; a generated read's own check columns are not compared on undeclared rows. The verifier waits for declared records with backoff (8 s budget, database reads only) before judging. A scope is admitted only when planted wrong-row, wrong-value, duplicate, sibling-edit, late-revert and lost-update faults and the actor-table attacks are all caught under it. A new contract is in shadow (`WriteResult.blocks` false, verdict recorded in full) until N clean checks in a row (20 to 50, default 30), then a person can turn gating on. Not yet: another user's unattributed edit of an entity-table record still stops the write; a harm confined to a non-entity table is logged, not stopped | (this PR) | Adversarial tests on SQLite (each safety-bar fault under a scope, settling under a moving queue, admission refusals); real-app replay pending | `openadapt-flow gate`, `openadapt-flow learn entities`, [VERDICT_TIERS.md](packages/flow/docs/VERDICT_TIERS.md) |
1 change: 1 addition & 0 deletions openadapt/cli_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
"fleet": "services fleet",
"flight": "run --flight",
"for-each": "run --for-each",
"gate": "verify gate",
"guard": "run --guard",
"hooks": "setup hooks",
"induce": "compile --induce",
Expand Down
125 changes: 125 additions & 0 deletions packages/flow/docs/VERDICT_TIERS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# Verdict tiers, entity-scoped frames and shadow mode

A whole-database frame stops a correct write whenever any row moves. On a
live app many rows move with no harm: a scheduler's heartbeat, a task queue,
prices or totals the app recomputes after a save, a notification for each
watcher of a record. This page describes how the verifier separates those
from real harm without letting any planted fault through.

## Three tiers

Every check of a write ends in one of these tiers. `WriteResult.tier` names
it, and `to_dict()` returns it with `side_effects`, `enforcement` and
`blocks`.

| Tier | Outcome | What it covers |
| --- | --- | --- |
| `hard` | `REFUTED` | The target is missing, a value is wrong after normalization, a duplicate, a changed or removed row in a business-entity table that the write doesn't declare (including another user's row and an unexcused column of the acting user's row), a late revert, a lost update, any removed row, and anything no row comparison explains. |
| `logged` | `CONFIRMED` | The write holds, and rows moved only outside the entity tables (added or changed, never removed). Each is listed in the frame evidence as `side_effects`: table, change, row count and column names, never keys or values. The same rows go to `openadapt-flow learn` as candidate excuses. |
| `doubt` | `UNCERTAIN` | Timing or knowledge doubt that the verifier's own waiting didn't clear. |
| `clean` | `CONFIRMED` | Nothing else moved. |

A logged pass is still `CONFIRMED`. A harm that slips through the logged
tier is therefore counted as a silent pass by any grader that reads the
outcome. The tier never hides a pass.

### Retry before reporting a doubt

Before a write is judged, the verifier waits for its declared records to
become visible: 0.5 s, then 1, 2 and 4 s, within 8 s in all
(`OPENADAPT_VERIFY_RETRY_S` sets the budget; 0 turns it off). The wait
reads only through database verifiers, so the wait itself can't move a
bookkeeping row. It never decides anything: the full judge runs afterwards
either way. A record that is present stops the wait at once.

The database frame's own settling (`settle_s`, `settle_attempts`) ignores
motion in tables outside the entity tables, so a scheduler that never stops
doesn't keep a write unsettled. Those tables are still diffed against the
baseline in the read that is judged.

## Entity-scoped frames

`frame.database.entity_tables` lists the business-entity tables. When it is
set, the hard checks cover those tables and rows elsewhere are logged. The
tables the frame already names (`views`, `judged_by`, `new_row_fields`,
side records, learned excuses, owner tables, the app profile's rules)
always count as entity tables. When it is unset, every table is judged as
before.

The list is derived from the setup, never written by hand
(`openadapt-flow learn entities`):

- each kind's main table;
- every table a contract's own read selects from, which covers the child
tables a write adds and the tables a field's location reads through;
- the acting user's table: the one table that every column bound to an
actor parameter references by foreign key. When it can't be derived, no
scope is proposed, because another user's row must stay a stop.

On a frame that diffs the whole database, a surface's own check columns
(`pin__*`, `empty__*`, which a generated read computes as 1 or 0) are not
compared on undeclared rows. One can flip with the clock and no write. The
stored columns they are computed from are compared themselves.

## The safety bar

A relaxation (an entity scope, or a learned mask) is admitted only if the
planted faults are all still caught under it
(`openadapt_flow.runtime.effects.admission`):

- wrong row, wrong value, duplicate, sibling business-record edit, late
revert and lost update;
- for a relaxation that touches the acting user's table, another user's row
and another column of the actor's own row.

Every class must have at least one case, every case must be caught, and
every case caught before the relaxation must be run again under it.
`fault_gate` names count for the same classes (`wrong_record` is a wrong
row, `unrelated_edit` a sibling edit).

```
openadapt-flow learn entities propose --manifest manifest.yaml --read read.yaml --out scope.json
openadapt-flow learn entities stage scope.json --out candidate/
# run the planted faults against candidate/ and write faults.json
openadapt-flow learn entities apply scope.json --faults faults.json --by "A. Reviewer"
```

`faults.json` is `openadapt.relaxation-faults/v1`: the proposal's
`proposal_sha256` and one `{case, class, caught}` per case. `apply` refuses
results run under another proposal, and writes every contract or none.

## Shadow mode by default

A contract is new to an app until it has been seen to judge real writes
correctly. Until then (`enforcement: shadow`) its verdicts are computed and
recorded in full, but `WriteResult.blocks` is false, so a caller that stops
on a verdict doesn't stop. Each check is appended to the contract's gate log
(`OPENADAPT_GATE_DIR`, by default `<OPENADAPT_LEDGER_DIR>/gates`, else
`~/.openadapt/gates`; names and outcomes only).

After N checks in a row with no stop of a correct write, gating is offered,
and a person turns it on:

```
openadapt-flow gate status contract.yaml
openadapt-flow gate label contract.yaml <write_id> caught # a real harm: keeps the run
openadapt-flow gate label contract.yaml <write_id> false_stop # breaks it, and is counted
openadapt-flow gate enable contract.yaml --by "A. Reviewer" # refused until offered
```

N is `OPENADAPT_GATE_CLEAN_RUNS`, kept between 20 and 50 (default 30). A
stop that nobody has labelled breaks the run, since it may be a false stop.
`OPENADAPT_ENFORCEMENT=gating` gates every contract (the behaviour before
shadow mode), and `shadow` keeps every contract in shadow. Shadow mode
changes only `blocks`. The ledger still holds a refuted attempt, so a retry
is never sent silently.

## Limits

- An edit by another user to a record in an entity table, with no audit
log or modified-by field to attribute it, still stops the write. Nothing
in the store tells it apart from the agent editing a sibling record.
- A harm confined to a table outside the entity tables (an agent that
changes a notification or a queue row) is logged, not stopped. The scope
is admitted only when the planted faults, which target business records,
are all caught. It is not a check on side tables.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Show a contract's shadow-mode run of clean checks, label a stop as a real catch or a false stop, and turn gating on once it is offered (`docs/VERDICT_TIERS.md`).
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Learn the app's own per-request writes from a shadow run or from read-only requests (`learn probe`), and write them into the contracts.
Learn the app's own per-request writes from a shadow run or from read-only requests (`learn probe`), scope the frame to the setup's business entities (`learn entities`, admitted only if the planted faults are still caught), and write them into the contracts.
8 changes: 4 additions & 4 deletions packages/flow/openadapt_flow/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13171,8 +13171,6 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None:
from openadapt_flow.cli_fleet import register_fleet_parser
from openadapt_flow.cli_receipt import register as _register_receipt
from openadapt_flow.cli_reconcile import register as _register_reconcile
from openadapt_flow.cli_rollback import register as _register_rollback
from openadapt_flow.cli_shadow import register as _register_shadow
from openadapt_flow.compile_agent.cli import add_parser as _add_compile_agent_parser
from openadapt_flow.flight.cli import add_parser as _add_flight_parser
from openadapt_flow.hooks.cli import add_parser as _add_hooks_parser
Expand All @@ -13181,8 +13179,9 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None:
from openadapt_flow.txplan.cli import add_parser as _add_plan_parser
from openadapt_flow.txplan.proxy_cli import add_parser as _add_proxy_parser

_register_rollback(sub)
_register_shadow(sub)
__import__("openadapt_flow.cli_rollback", fromlist=["_"]).register(sub)
__import__("openadapt_flow.cli_shadow", fromlist=["_"]).register(sub)
__import__("openadapt_flow.cli_gate", fromlist=["_"]).register(sub)
__import__("openadapt_flow.readiness.cli", fromlist=["cli"]).register(sub)
_register_receipt(sub)
_register_learn(sub)
Expand Down Expand Up @@ -13633,6 +13632,7 @@ def _qualify_default_form(argv: list[str]) -> list[str]:
"openadapt_flow.cli_no_outbound:_cmd_list",
"openadapt_flow.cli_no_outbound:_cmd_remove",
"openadapt_flow.cli_local_seal:_guarded",
"openadapt_flow.cli_gate:cmd_gate",
"openadapt_flow.cli_receipt:cmd_anchor",
"openadapt_flow.cli_receipt:cmd_keys_export",
"openadapt_flow.cli_receipt:cmd_verify",
Expand Down
81 changes: 81 additions & 0 deletions packages/flow/openadapt_flow/cli_gate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"""CLI: ``openadapt-flow gate`` -- shadow mode and gating, per contract.

openadapt-flow gate status contract.yaml
openadapt-flow gate label contract.yaml <write_id> caught|false_stop
openadapt-flow gate enable contract.yaml --by "A. Reviewer"
openadapt-flow gate disable contract.yaml --by "A. Reviewer"

See ``openadapt_flow.enforcement`` and ``docs/VERDICT_TIERS.md``.
"""

from __future__ import annotations

import argparse
import json
import sys


def register(sub: argparse._SubParsersAction) -> None:
p = sub.add_parser(
"gate",
help="Show a contract's shadow run of clean checks, label a stop, or "
"turn gating on once it is offered",
allow_abbrev=False,
)
gsub = p.add_subparsers(dest="gate_command", required=True)
s = gsub.add_parser(
"status",
help="mode, clean checks in a row, whether gating is offered",
allow_abbrev=False,
)
s.add_argument("contract")
s.add_argument("--json", action="store_true")
s.set_defaults(func=cmd_gate)
s = gsub.add_parser(
"label",
help="label one stop: caught (a real harm) or false_stop",
allow_abbrev=False,
)
s.add_argument("contract")
s.add_argument("write_id")
s.add_argument("verdict", choices=("caught", "false_stop"))
s.set_defaults(func=cmd_gate)
for name, text in (
("enable", "turn gating on (only once it is offered)"),
("disable", "go back to shadow"),
):
s = gsub.add_parser(name, help=text, allow_abbrev=False)
s.add_argument("contract")
s.add_argument("--by", required=True, help="who decided")
s.set_defaults(func=cmd_gate)


def cmd_gate(args: argparse.Namespace) -> int:
from openadapt_flow import enforcement

digest = enforcement.contract_digest(args.contract)
if args.gate_command == "label":
enforcement.label(digest, args.write_id, args.verdict)
st = enforcement.status(digest)
elif args.gate_command == "enable":
try:
st = enforcement.enable(digest, args.by)
except enforcement.GateRefused as exc:
print(f"gate: {exc}", file=sys.stderr)
return 2
elif args.gate_command == "disable":
st = enforcement.disable(digest, args.by)
else:
st = enforcement.status(digest)
if getattr(args, "json", False):
print(json.dumps(st.to_dict(), indent=2))
return 0
print(f"mode: {st.mode}")
print(f"clean checks in a row: {st.clean_in_a_row} of {st.needed}")
print(f"checks recorded: {st.checks}; stops labelled false: {st.false_stops}")
if st.offered:
print(
"gating is offered: run `openadapt-flow gate enable "
f"{args.contract} --by <name>` to let this contract block"
)
return 0
1 change: 1 addition & 0 deletions packages/flow/openadapt_flow/cli_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"fleet": "services fleet",
"flight": "run --flight",
"for-each": "run --for-each",
"gate": "verify gate",
"guard": "run --guard",
"hooks": "setup hooks",
"induce": "compile --induce",
Expand Down
Loading
Loading