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 @@
| Wrap the same task again on the same app: when the app already has a record matching a canary's values (an earlier wrap's or attempt's canary), `openadapt wrap` adds a short random suffix (`oa` and six hex digits) to one text input of that canary, the longest public input that every claim of the new record binds as plain text (never a sign-in input, an email address, a URL, or an input the checks declare as a code or a typed value), so the second canary isn't confused with the first; otherwise the values are saved as written, and the record check still wants exactly one match. `"unique_canaries": false` in the task file saves the values as written. `status: admitted` exits 0 even when the attempt only admitted a kept draft (`verified: false`, with a stderr line that nothing was saved with the caller's inputs), and a run prints one plaintext-at-rest warning while the ledger keeps a line per write | In PR | Synthetic (the bundled clinic app, never reset between wraps, with saves not deduplicated: two wraps of one task both admit, the second canary with a suffix; with the suffix off the second canary halts on two matching records, and a CLI retry of that draft admits it with exit 0) and unit tests for the collision check, the input choice, `admit` with a stubbed canary (secret inputs unchanged), the exit status and the one-line warning (strict mode and a failed ledger write still refuse) | [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md#3-describe-the-task), `openadapt_flow.compile_agent.pipeline`, `openadapt_flow.at_rest.one_warning_line`, `packages/flow/tests/e2e/test_wrap_canary_unique_e2e.py`, `packages/flow/tests/test_wrap_rough_edges.py` |
46 changes: 46 additions & 0 deletions packages/flow/docs/WRAP_PUBLISH.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,23 @@ Save this as `task.json`, with your app's address:
`expect` names the fields that every record this task saves shares (here,
the demo list). `verifier` is the read that checks the save independently.

`canary_params` are the values of the test save (the canary) that runs
before the program is admitted. The canary is a real save, so choose values
that are safe to write to the app.

The checks want exactly one record that matches the canary's values. If the
app already has one, from an earlier wrap of the same task or an earlier
attempt, `wrap` adds a short random suffix to one text input of that canary,
for example `canary note 1 oa3f9c2e`. Otherwise the values are saved as
written. The suffix goes on the longest input that the checks compare as plain
text and whose value has a letter. It never goes on a sign-in input, an email
address, a URL, or an input the checks declare as a code (`map`) or a typed
value (`kind`). A field that accepts only certain text, such as a list of
options stored as their labels or a date written in words, can still get it,
and then the canary fails without saving anything wrong. To keep the values
exactly as written, add `"unique_canaries": false` and remove the earlier
canary's record before you wrap the task again.

## 4. Wrap the task

```bash
Expand All @@ -82,6 +99,35 @@ the run is a script. To admit without a person at the terminal, pass
If the model key for `--provider` is not set, `wrap` stops before the agent
starts with `[MISSING_MODEL_KEY]` and the variable to set. Nothing is recorded.

`wrap` prints one JSON result. `verified` says whether this call's own save
was read back `VERIFIED`: run 1's save on a first run, the program's save on
a later run. The exit status follows from it:

| Exit status | When |
|---|---|
| 0 | `verified` is `true`, or `status` is `admitted`. |
| 1 | Anything else that ran, such as a run that halted or an attempt to check in the app (`RECONCILIATION_REQUIRED`). |
| 2 | Nothing ran: a setup problem, a missing model key, or `wrap run` with no admitted program. |
| 130 | Interrupted (Ctrl-C); the wrapped command was stopped. |

Run 1 can save and be read back while the program is not admitted yet (a
`draft`, or a failed canary), so check `status` as well as the exit status.

A program is admitted only after its canary ended `VERIFIED`, so admission
exits 0 even when `verified` is `false`. That happens when you run `wrap`
again after a failed canary: the earlier attempt's run 1 already saved your
values, so this attempt only runs the canary and admits the program. `wrap`
says on stderr that this attempt saved nothing with your inputs. Check the
app before you save the same values again. When you wrap your own agent
command (`-- COMMAND`) and it exits with an error, `wrap` exits with that
command's status instead.

The first run writes a JIT draft (its recording, bundle and run folders) in
plaintext. `wrap` prints one warning about it per run, and every plaintext
write still gets a line in the plaintext ledger
(`~/.openadapt/plaintext-at-rest.jsonl` by default). With
`OPENADAPT_FLOW_AT_REST=strict`, Flow refuses to write the plaintext draft.

## 5. Publish

```bash
Expand Down
43 changes: 42 additions & 1 deletion packages/flow/openadapt_flow/at_rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@
_KEY_BYTES: Final[int] = 32
_lock = threading.Lock()
_warned: set[str] = set()
#: Open :func:`one_warning_line` blocks, and whether one of them already
#: printed its line. Process-wide (not per thread): a wrapped run writes from
#: its MCP endpoint's threads too, and the run gets one line in all.
_one_line_depth = 0
_one_line_printed = False


class LocalKeyError(RuntimeError):
Expand Down Expand Up @@ -135,6 +140,29 @@ def opted_out(source: str) -> Iterator[None]:
os.environ[name] = value


@contextmanager
def one_warning_line() -> Iterator[None]:
"""Print at most one plaintext-at-rest warning while the block runs.

For one run of a command that writes several plaintext artifacts (a JIT
draft's recording, bundle and run directories): the first write prints
one line that names it and the ledger, and every later write in the block
gets its ledger line only. Nothing else changes: strict mode still
refuses before anything is written, and a write the ledger can't record
is still refused.
"""
global _one_line_depth, _one_line_printed
with _lock:
_one_line_depth += 1
try:
yield
finally:
with _lock:
_one_line_depth -= 1
if _one_line_depth == 0:
_one_line_printed = False


def explicit_key() -> bool:
"""Whether the deployment configured a key (rather than the local one)."""
return bool(
Expand Down Expand Up @@ -286,12 +314,22 @@ def record_plaintext(purpose: str, reason: str) -> None:
def _record(
purpose: str, reason: str, *, warning: str, path: Optional[str] = None
) -> None:
global _one_line_printed
strict() # an unknown mode stops here too, not only at the CLI
with _lock:
if purpose in _warned:
return
_warned.add(purpose)
print(warning, file=sys.stderr)
quiet = _one_line_depth > 0 and _one_line_printed
if _one_line_depth > 0 and not quiet:
_one_line_printed = True
warning = (
"WARNING: this run writes files in plaintext that can hold "
f"patient data, starting with {purpose}. Each one is listed in "
f"{ledger_path()}. Set {MODE_ENV}=strict to refuse instead."
)
if not quiet:
print(warning, file=sys.stderr)
try:
ledger = ledger_path()
ledger.parent.mkdir(parents=True, exist_ok=True)
Expand Down Expand Up @@ -845,5 +883,8 @@ def default_key() -> Optional[str]:


def _reset_for_tests() -> None:
global _one_line_depth, _one_line_printed
with _lock:
_warned.clear()
_one_line_depth = 0
_one_line_printed = False
10 changes: 9 additions & 1 deletion packages/flow/openadapt_flow/compile_agent/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,8 +327,16 @@ def review(stage: str, shown: dict[str, Any]) -> bool:
prompt = "Type ok to confirm you reviewed every step: "
else:
for canary in shown["canaries"]:
stamp = canary.get("stamp") or {}
# The suffix tells the person which record the canary saved.
suffix = (
f" ({stamp['param']} ends in {stamp['suffix']})"
if stamp.get("param") and stamp.get("suffix")
else ""
)
print(
f"Canary: {canary['status']}, receipt {canary['receipt_outcome']}"
f"Canary: {canary['status']}, receipt "
f"{canary['receipt_outcome']}{suffix}"
)
prompt = "Type ok to admit this program: "
return ask(prompt).strip().lower() == "ok"
Expand Down
166 changes: 157 additions & 9 deletions packages/flow/openadapt_flow/compile_agent/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import hashlib
import json
import re
import secrets
import time
import uuid
from dataclasses import dataclass, field
Expand Down Expand Up @@ -1178,6 +1179,7 @@ def admit(
person: Optional[str] = None,
review: Optional[Callable[[str, dict[str, Any]], bool]] = None,
canary_params: Optional[Sequence[Mapping[str, Any]]] = None,
unique_canaries: bool = False,
) -> CompileResult:
"""Canary the draft, then admit it.

Expand All @@ -1194,6 +1196,14 @@ def admit(

Each canary also gets a verify-run receipt against the confirmed
checks; a canary passes only when both end VERIFIED.

``unique_canaries``: when a record already in the system of record
matches what a canary would save (an earlier attempt's or an earlier
wrap's canary), a short random suffix goes on one text input of that
canary (see :func:`_canary_stamp_param`), so the record check doesn't
find two matching records. The check still wants exactly one. With
no such record the values are saved as given. The values given are
checked against run 1's before any suffix is added.
"""

jit = self._jit()
Expand Down Expand Up @@ -1248,6 +1258,19 @@ def admit(
if getattr(self.task, "params", None)
else rows[min(i, len(rows) - 1)]
)
stamp: Optional[dict[str, str]] = None
if unique_canaries and _canary_would_collide(
self.out_dir / CONFIRMED_FILE,
self.observer.system_of_record,
params,
):
name = _canary_stamp_param(
self.out_dir / CONFIRMED_FILE, self._public_params(), params
)
if name is not None:
suffix = "oa" + secrets.token_hex(3)
params = {**params, name: f"{params[name]} {suffix}"}
stamp = {"param": name, "suffix": suffix}
values = self.task.validate(params)
try:
result, receipt, path = self._governed(
Expand All @@ -1265,15 +1288,18 @@ def admit(
"needs_person", str(exc), admission={"canaries": canaries}
)
outcome = _receipt_outcome(receipt)
canaries.append(
{
"status": result.status,
"model_calls": result.model_calls,
"receipt_outcome": outcome,
"receipt": str(path) if path else None,
"halt_reason": result.halt_reason,
}
)
entry: dict[str, Any] = {
"status": result.status,
"model_calls": result.model_calls,
"receipt_outcome": outcome,
"receipt": str(path) if path else None,
"halt_reason": result.halt_reason,
}
if stamp is not None:
# Which input got the suffix, so the person can find the
# canary's record in the app. Never a value.
entry["stamp"] = stamp
canaries.append(entry)
if result.status != "VERIFIED" or outcome != "VERIFIED":
return self._result(
"canary_failed",
Expand Down Expand Up @@ -1520,6 +1546,123 @@ def _duplicate_canary_rows(
return None


def _canary_would_collide(
confirmed: Path,
records: Optional[Sequence[Mapping[str, Any]]],
row: Mapping[str, Any],
) -> bool:
"""Whether a record already there could match what this canary saves.

Compares each new-record claim's match with every record: a literal with
the record's field, an input with the canary's value, ignoring case and
repeated spaces. Anything it can't judge counts as a possible match
(no read, a claim routed to another read, an input the checks read as a
code or a typed value), so the canary then gets its suffix.
"""

import yaml

if records is None:
return True
try:
doc = yaml.safe_load(confirmed.read_text(encoding="utf-8")) or {}
except (OSError, yaml.YAMLError):
return True
claims = [
effect
for effect in doc.get("effects") or []
if isinstance(effect, dict) and _claims_new_record(effect, count_new_only=False)
]
if not claims:
return True

def text(value: Any) -> str:
return " ".join(str(value).split()).casefold()

def same(stored: Any, wanted: Any) -> bool:
if isinstance(wanted, dict):
if isinstance(wanted.get("param"), str):
keys = {k for k, v in wanted.items() if v is not None}
value = row.get(wanted["param"])
if not keys <= _STAMPABLE_BINDING_KEYS or value is None:
return True
wanted = value
elif "literal" in wanted:
wanted = wanted["literal"]
else:
return True
if stored is None or wanted is None:
return stored is None and wanted is None
return text(stored) == text(wanted)

for claim in claims:
if str(claim.get("probe") or "").startswith(_SURFACE_ROUTE):
return True
match = claim.get("match") or {}
if not isinstance(match, dict) or not match:
return True
for record in records:
if all(same(record.get(field), want) for field, want in match.items()):
return True
return False


#: Binding keys a stamped input may carry. ``map`` (a select's codes),
#: ``kind`` (a typed value such as a date) and ``null`` mean the app or the
#: check would not take arbitrary text, so such an input is never stamped.
_STAMPABLE_BINDING_KEYS = frozenset({"param", "stored"})


def _canary_stamp_param(
confirmed: Path, public: Sequence[str], row: Mapping[str, Any]
) -> Optional[str]:
"""The one input a canary suffix goes on, or None when none can take it.

A candidate is a public (never a secret) input that every claim of the
new record in the confirmed checks binds plainly, whose canary value is
free text: it has a letter and isn't an email address or a URL. The
longest value wins (a note rather than a short label), then the name.
The suffix keeps the record's match unique, so one input is enough.
"""

import yaml

try:
doc = yaml.safe_load(confirmed.read_text(encoding="utf-8")) or {}
except (OSError, yaml.YAMLError):
return None
plain: set[str] = set()
typed: set[str] = set()
for effect in doc.get("effects") or []:
if not isinstance(effect, dict) or not _claims_new_record(
effect, count_new_only=False
):
continue
for binding in (effect.get("match") or {}).values():
if not isinstance(binding, dict) or not isinstance(
binding.get("param"), str
):
continue
keys = {k for k, v in binding.items() if v is not None}
if keys <= _STAMPABLE_BINDING_KEYS:
plain.add(binding["param"])
else:
typed.add(binding["param"])
candidates = []
for name in sorted((plain - typed) & set(public)):
value = row.get(name)
if (
isinstance(value, str)
and any(c.isalpha() for c in value)
and "@" not in value
and "://" not in value
):
candidates.append(name)
if not candidates:
return None
return max(candidates, key=lambda name: (len(row[name]), name))


def compile_first_run(
prompt: str,
*,
Expand All @@ -1538,6 +1681,7 @@ def compile_first_run(
review: Optional[Callable[[str, dict[str, Any]], bool]] = None,
hold: Optional[Callable[[GateRequest], bool]] = None,
canary_params: Optional[Sequence[Mapping[str, Any]]] = None,
unique_canaries: bool = False,
task_id: Optional[str] = None,
policy: str = "clinical-write",
cache_dir: Union[str, Path] = ".openadapt-compile-agent",
Expand Down Expand Up @@ -1587,6 +1731,9 @@ def compile_first_run(
canary_params: The values each canary saves, one mapping per canary
(the last is reused). A canary is a real save on the record the
task names, so choose values that are safe there. Required.
unique_canaries: When a record already matches a canary's values
(an earlier attempt's canary), add a short random suffix to one
text input of that canary (see :meth:`FirstRunCompiler.admit`).
model_key: The customer's own model key, for a model-driven agent.
reset: Called before every run to reset a test app. Tests only.
before_capture: Trusted Python preparation/preflight on the exact
Expand Down Expand Up @@ -1649,6 +1796,7 @@ def compile_first_run(
person=person,
review=review,
canary_params=canary_params,
unique_canaries=unique_canaries,
)
if first is not None:
admitted.run1 = first.run1
Expand Down
Loading
Loading