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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# These generated bytes and override pins are identical on Windows and Unix.
*.json -text
patient_notes_v2.ps1 -text
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Native record identity v2 fixture

This is a new synthetic qualification case. It exposes the loaded SQLite record
ID in a readonly standard WinForms `TextBox` named `currentRecordId`. The original
`patient_notes.ps1`, its save handler, and the older caption-based readback spec
remain unchanged. Earlier results retain their original case and denominator.

The fixture clears the ID, note and header before loading or changing records.
It publishes an ID only after the selected grid key, the actual `pn_db.py get`
result's ID and a fresh selection read agree. Missing, malformed or mismatched
records leave the ID empty. A failed list load also clears the selection and
list. The original save handler still saves to the selected grid key; the new
fixture adds no save guard.

This PR delivers fixture data and offline generation only. The generated
legacy-shaped readback template is nonauthoritative: it does not enforce exact
canonical-ID matching or admit a runtime. That consumer work remains separate.

`contract.json` declares the database mapping and a data-only readback template.
The generator applies exact overrides to a hash-pinned base and emits a distinct
script, pack and manifest. Run from `packages/flow`:

```sh
python tests/fixtures/native_record_identity_v2/build_fixture.py --check
```

The base pin uses LF bytes; checkout CRLF is explicitly converted to LF before
comparison. No other normalization occurs. Generated files preserve their
committed bytes on either platform. The caller supplies its owned readback
session; the pack contains no endpoint or credentials. Record IDs must be
canonical signed int64 strings, including zero and the integer boundaries.
Search selects a candidate. The intended contract requires exact canonical
record-ID comparison; the existing verifier also accepts delimited caption
values. This candidate remains held for a generic exact-value consumer contract
and planted invalid-display controls.
There is no virtual-grid or complete row-count claim.

Offline tests parse the entire generated PowerShell source and execute only its
actual database/load/selection functions, using stand-in controls and the real
SQLite CLI. They test reset, missing/ambiguous/invalid identity, wrong loaded row,
selection replacement during load, invalid list data and actual subprocess
failure. They also compare CLI IDs with independent SQLite reads and plant
incorrect mapping/schema controls. Nonempty notes prime every failure/reset
case so stale-value clearing controls are not vacuous. JSON root-shape checks
precede PowerShell pipeline enumeration. They open no GUI and send no desktop input.
These checks establish source behavior under those stand-ins, not native
WinForms behavior.

Native qualification is **unperformed**. The intended structural read uses
request contract `openadapt.native-value-read/v3` and the separate
`openadapt.native-value-completeness/v3` proof schema. These are source references
from frozen #2291 at `1a2503da4e240ba24620845cf85737d087c38e39`, with shared
helper commit `4be4b543da10286105090950c57a89d5e7a9a497` (Git blob
`78e47eb02e7498b5111766f25f3604e8ab78ee50`). They do not establish final protocol,
runtime or native qualification; all contract holds remain false or null.
Readonly identity uses `require_editable=False`; it is not an editable-field
baseline. Unsupported, sensitive, truncated or disagreeing values must refuse,
with no caption, preview or OCR fallback. The known-non-password guard and
mandatory `value_contract` negotiation remain prerequisites for future consumer
integration. This fixture does not qualify an older runtime.

A future native case must independently compare the selected key, loaded DB
row, actual managed control value and complete native UIA/Win32 observation,
then check the target and every sibling directly in SQLite. A complete text
observation alone does not prove that the text belongs to the saved row. The
protocol/source freeze, native binding evidence, combined approval campaign and
held-out evidence remain absent in `contract.json`. No prior failed campaign is
reclassified by this new case.
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Offline results

2026-11-20, source-only candidate:

- 21 focused pytest cases passed with no skips, using Python 3.12.13 and
PowerShell 7.5.0 on macOS. Flow and Types imports were bound to this checkout.
- One test executes 26 lifecycle cases from the generated PowerShell functions,
against stand-in controls and the real SQLite CLI. These are included in the
pytest count, not additional native trials.
- A separate planted omission of note clearing was rejected at selection reset.
- CLI IDs matched independent SQLite reads, including zero and signed int64
boundaries. Wrong schema/mapping controls refused. All lifecycle DB rows stayed
unchanged.
- Ruff 0.17.0 checks and formatting passed. Generated output matches its pinned
base/override/manifest; the original save-handler bytes match.

No WinForms UI, desktop input, lab, VM, cloud resource or native CI campaign was
used. Windows PowerShell 5.1 and native WinForms event/provider behavior remain
unmeasured. The shared consumer protocol, exact canonical-ID matching, live
DB-row-to-control binding, combined campaign and held-out qualification remain
held. No prior result or denominator changed.

## Protocol reference correction

The intended request contract is `openadapt.native-value-read/v3`; the separate
proof schema is `openadapt.native-value-completeness/v3`, as defined by frozen
#2291 at `1a2503da4e240ba24620845cf85737d087c38e39` and helper commit
`4be4b543da10286105090950c57a89d5e7a9a497`. These source references replace the
historical v2 references. Every false/null qualification hold remains in place;
the legacy-shaped template remains nonauthoritative.

The existing focused suite passed again: 21 cases, no skips (Python 3.12.13,
3.73 seconds), with Flow and Types imports verified against the correction
checkout. The existing generated-output check, changed-file Ruff lint/format
checks and repository source-boundary guard passed. All checks used the shared
CPU slot. No new test cases, native/GUI/provider execution, runtime integration
or qualification claim was added. Generated fixture, template, base and save
handler bytes are unchanged.
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
"""Build a NEW synthetic fixture and pack from a pinned, unchanged base.

This is repository-only test support. It does not qualify a native runtime.
"""

from __future__ import annotations

import argparse
import ast
import hashlib
import json
import sqlite3
from pathlib import Path
from typing import Any

HERE = Path(__file__).resolve().parent
FLOW = HERE.parents[2]


def sha256(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()


def load_contract() -> dict[str, Any]:
return json.loads((HERE / "contract.json").read_text())


def canonical_source(path: Path) -> bytes:
"""Windows checkout CRLF is explicit; no other byte normalization."""
return path.read_bytes().replace(b"\r\n", b"\n")


def save_handler(source: str) -> str:
return source.split("$saveButton.Add_Click({", 1)[1].split("\n})", 1)[0]


def build(base: bytes, override: dict[str, Any]) -> bytes:
contract = load_contract()
if sha256(base) != contract["base_source"]["sha256"]:
raise ValueError("base source differs from the pinned fixture")
if override["schema"] != "openadapt.synthetic-source-override/v1":
raise ValueError("unsupported source override schema")
text = base.decode("utf-8")
original_save = save_handler(text)
for patch in override["patches"]:
if text.count(patch["before"]) != 1:
raise ValueError("source override must match exactly once")
text = text.replace(patch["before"], patch["after"], 1)
if save_handler(text) != original_save:
raise ValueError("NEW fixture changed the original save handler")
return text.encode("utf-8")


def readback_spec(session: dict[str, Any]) -> dict[str, Any]:
"""Supply the caller's owned session; the data pack stores no endpoint."""
return {"session": session, **load_contract()["readback_template"]}


def validate_database(con: sqlite3.Connection, mapping: dict[str, str]) -> None:
"""Check the declared identity/value mapping against an actual SQLite DB."""
table = mapping["table"]
if not isinstance(table, str) or not table:
raise ValueError("missing table")
kind = con.execute(
"SELECT type FROM sqlite_master WHERE name = ?", (table,)
).fetchone()
if kind != ("table",):
raise ValueError("mapping must name an actual table")
quoted_table = '"' + table.replace('"', '""') + '"'
columns = {row[1]: row for row in con.execute(f"PRAGMA table_info({quoted_table})")}
key = columns.get(mapping["key"])
value = columns.get(mapping["value"])
if (
key is None
or key[2].upper() != mapping["key_type"]
or key[2].upper() != "INTEGER"
or key[5] != 1
or sum(bool(row[5]) for row in columns.values()) != 1
):
raise ValueError("identity must be the sole INTEGER primary key")
if value is None or value[2].upper() != mapping["value_type"] or value[2] != "TEXT":
raise ValueError("note mapping must name a TEXT column")
if mapping["key"] == mapping["value"]:
raise ValueError("identity and note mapping must differ")


def validate_source_mapping(source: bytes, contract: dict[str, Any]) -> None:
"""Bind pack data to the pinned CLI's actual lookup and write statements."""
mapping = contract["database_mapping"]
table, key, value = (mapping[name] for name in ("table", "key", "value"))
expected = {
"get": f"SELECT * FROM {table} WHERE {key} = ?",
"save": f"UPDATE {table} SET {value} = ? WHERE {key} = ?",
}
tree = ast.parse(source)
for name, sql in expected.items():
functions = [
node
for node in tree.body
if isinstance(node, ast.FunctionDef) and node.name == name
]
if len(functions) != 1:
raise ValueError("database operation is missing or ambiguous")
statements = [
node.args[0].value
for node in ast.walk(functions[0])
if isinstance(node, ast.Call)
and isinstance(node.func, ast.Attribute)
and node.func.attr == "execute"
and node.args
and isinstance(node.args[0], ast.Constant)
]
if statements != [sql]:
raise ValueError("pack mapping differs from actual CLI lookup/write SQL")
binding = contract["identity_binding"]
if any(
binding[name] != key
for name in ("selected_cell", "loaded_field", "save_target_cell")
):
raise ValueError("selection, load and save mapping must name the same key")
template = contract["readback_template"]
if template["identity"]["field"] != key or set(template["fields"]) != {value}:
raise ValueError("readback pack differs from the database mapping")


def outputs() -> dict[str, bytes]:
contract = load_contract()
base = canonical_source(FLOW / contract["base_source"]["path"])
database = canonical_source(FLOW / contract["database_source"]["path"])
if sha256(database) != contract["database_source"]["sha256"]:
raise ValueError("database CLI differs from the pinned source")
validate_source_mapping(database, contract)
override_bytes = (HERE / "override.json").read_bytes()
fixture = build(base, json.loads(override_bytes))
pack = (json.dumps(contract["readback_template"], indent=2) + "\n").encode()
manifest = {
"case_id": contract["case_id"],
"base_sha256": sha256(base),
"database_source_sha256": sha256(database),
"override_sha256": sha256(override_bytes),
"fixture_sha256": sha256(fixture),
"readback_template_sha256": sha256(pack),
"unchanged_save_handler_sha256": sha256(save_handler(base.decode()).encode()),
"native_validation_performed": False,
}
return {
"patient_notes_v2.ps1": fixture,
"readback.template.json": pack,
"manifest.json": (json.dumps(manifest, indent=2) + "\n").encode(),
}


def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
for name, data in outputs().items():
path = HERE / name
if args.check:
if not path.is_file() or path.read_bytes() != data:
raise SystemExit(f"generated file differs: {name}")
else:
path.write_bytes(data)


if __name__ == "__main__":
main()
Loading
Loading