diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0340-commit-one-record-update-through-a-transaction.md b/capabilities/04-the-core-a-checked-entry-every-time/0340-commit-one-record-update-through-a-transaction.md index 5bc9435c22..c6d389a0c5 100644 --- a/capabilities/04-the-core-a-checked-entry-every-time/0340-commit-one-record-update-through-a-transaction.md +++ b/capabilities/04-the-core-a-checked-entry-every-time/0340-commit-one-record-update-through-a-transaction.md @@ -1 +1 @@ -| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. Induction refuses a trace that shows no write it can attribute to a record (an update at the record's URL, or a create whose record is then read there) instead of guessing a route; the CLI allows a guessed item route only when it certifies the lens on a sandbox. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. A field the server is seen rewriting between `NULL` and `""` gets a `null_empty` codec, learned per field by the probe or from the trace, so that change alone is not a clobber; any other change on the field still is. The wire tap counts a GraphQL query (on `/graphql` or `/$graphql`) and a batch of `GET`s as reads. Another `POST` counts as a read only when it matches a read route declared as data; `probe_read_routes` learns those by replaying a trace on a sandbox reset to its pre-trace state and requiring that a whole-store digest not change. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | +| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. Induction refuses a trace that shows no write it can attribute to a record (an update at the record's URL, or a create whose record is then read there) instead of guessing a route; the CLI allows a guessed item route only when it certifies the lens on a sandbox. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. A field the server is seen rewriting between `NULL` and `""` gets a `null_empty` codec, learned per field by the probe or from the trace, so that change alone is not a clobber; any other change on the field still is. The wire tap counts a GraphQL query (on `/graphql` or `/$graphql`) and a batch of `GET`s as reads. Another `POST` counts as a read only when it matches a read route declared as data; `probe_read_routes` learns those by replaying a trace on a sandbox reset to its pre-trace state and requiring that a whole-store digest not change. An app whose calls all go to one RPC endpoint gets a lens whose read and write carry their arguments in the body (`body_template`), whose record is found at a path such as `result.0`, and whose 2xx answer with an `error` member counts as a failed call; induction learns it from a read that returns the named records and a write that a later read confirms, and reads back the fields the trace itself read. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | diff --git a/packages/flow/openadapt_flow/tx/induce.py b/packages/flow/openadapt_flow/tx/induce.py index b228df6237..c5a4b668b7 100644 --- a/packages/flow/openadapt_flow/tx/induce.py +++ b/packages/flow/openadapt_flow/tx/induce.py @@ -230,6 +230,7 @@ class _HarExchange: resp_status: int resp_json: Any etag_header: Optional[str] + raw_path: str = "" def _parse_flexible_date(value: str) -> Optional[date]: @@ -502,6 +503,7 @@ def _parse_har_exchanges(har: Mapping[str, Any]) -> list[_HarExchange]: resp_status=status, resp_json=resp_json, etag_header=_extract_etag_header_name(resp), + raw_path=path, ) ) @@ -602,6 +604,160 @@ def _record_id(rec: Mapping[str, Any], field_name: str) -> Optional[str]: return text or None +def _rpc_call(ex: _HarExchange) -> Optional[tuple[str, list[Any], Any]]: + """``(method, params, result)`` for a successful JSON-RPC-style call.""" + req = ex.req_data + resp = ex.resp_json + if ex.method != "POST" or not isinstance(req, Mapping): + return None + method = req.get("method") + params = req.get("params") + if not isinstance(method, str) or not isinstance(params, list): + return None + if not isinstance(resp, Mapping) or resp.get("error") is not None: + return None + if "result" not in resp: + return None + return method, params, resp["result"] + + +def _int_ids(value: Any) -> Optional[list[int]]: + if ( + isinstance(value, list) + and value + and all(isinstance(v, int) and not isinstance(v, bool) for v in value) + ): + return list(value) + return None + + +def _induce_rpc_lens( + scoped: list[_HarExchange], + base_url: str, + entity_name: Optional[str], +) -> Optional[EntityLensSpec]: + """A lens for an app whose every call is one RPC endpoint. + + Roles come from effects, as for REST. A *read* call names record ids in + its first argument and a field list in its second, and returns exactly + those records. A *write* call names one id and a dict of values, and a + later read of the same model shows those values. The read-back template + reads the union of every field the trace read for that model, so the + frame is the fields the app itself reads, not the whole table. + """ + calls = [(ex, c) for ex in scoped if (c := _rpc_call(ex)) is not None] + if not calls: + return None + reads: dict[str, list[tuple[_HarExchange, list[Any]]]] = {} + seen: dict[tuple[str, int], list[tuple[int, dict[str, Any]]]] = {} + for ex, (method, params, result) in calls: + if "." not in method or len(params) < 2: + continue + model, verb = method.rsplit(".", 1) + ids = _int_ids(params[0]) + asked = params[1] + if ( + ids is not None + and isinstance(asked, list) + and all(isinstance(f, str) for f in asked) + and isinstance(result, list) + and result + and all(isinstance(r, Mapping) and "id" in r for r in result) + and sorted(int(r["id"]) for r in result) == sorted(ids) + ): + reads.setdefault(model, []).append((ex, params)) + for r in result: + seen.setdefault((model, int(r["id"])), []).append((ex.seq, dict(r))) + + writes: dict[str, list[tuple[_HarExchange, list[Any]]]] = {} + for ex, (method, params, _result) in calls: + if "." not in method or len(params) < 2: + continue + model, _verb = method.rsplit(".", 1) + ids = _int_ids(params[0]) + values = params[1] + if ( + ids is None + or len(ids) != 1 + or not isinstance(values, Mapping) + or not values + ): + continue + later = [rec for seq, rec in seen.get((model, ids[0]), []) if seq > ex.seq] + if any(all(rec.get(k) == v for k, v in values.items()) for rec in later): + writes.setdefault(model, []).append((ex, params)) + if not writes: + return None + + model = max(writes, key=lambda m: (len(writes[m]), len(reads.get(m, [])))) + read_ex, read_params = reads[model][-1] + write_ex, write_params = writes[model][-1] + fields: list[str] = [] + for _ex, params in reads[model]: + for f in params[1]: + if f not in fields: + fields.append(f) + for _ex, params in writes[model]: + for f in params[1]: + if f not in fields: + fields.append(f) + + # Volatile: a field the server changed between two reads of one record + # that no write in the trace asked for. + requested: set[tuple[str, str]] = set() + for _ex, params in writes[model]: + for k, v in params[1].items(): + requested.add((k, _canonical_value(v))) + volatile: list[str] = [] + for (m, _rid), history in seen.items(): + if m != model: + continue + for (_s0, r0), (_s1, r1) in zip(history, history[1:]): + for f in fields: + if ( + f in r0 + and f in r1 + and r0[f] != r1[f] + and (f, _canonical_value(r1[f])) not in requested + and f not in volatile + ): + volatile.append(f) + + def _template(ex: _HarExchange, params: list[Any], second: Any) -> dict[str, Any]: + body = dict(ex.req_data or {}) + body["params"] = [["{id:int}"], second, *params[2:]] + return body + + get_one = EndpointTemplate( + method="POST", + path_template=read_ex.raw_path or read_ex.path, + id_field="id", + etag_header=None, + body_template=_template(read_ex, read_params, fields), + record_path="result.0", + error_path="error", + ) + write_endpoint = EndpointTemplate( + method="POST", + path_template=write_ex.raw_path or write_ex.path, + id_field="id", + etag_header=None, + body_template=_template(write_ex, write_params, "{payload}"), + error_path="error", + ) + name = entity_name or model.rsplit(".", 1)[-1] + return EntityLensSpec( + entity_name=name, + base_url=base_url, + id_field="id", + write_mode="patch", + get_one=get_one, + write_endpoint=write_endpoint, + identity_fields=tuple(f for f in _CANONICAL_IDENTITY_KEYS if f in fields)[:2], + volatile_fields=tuple(volatile), + ) + + def _shows_item_route(scoped: list[_HarExchange]) -> bool: """True when some 2xx response is one record served at its own URL.""" for ex in scoped: @@ -812,6 +968,17 @@ def induce_lens_from_har( origin_counts[ex.origin] = origin_counts.get(ex.origin, 0) + 1 base_url = max(origin_counts.items(), key=lambda kv: kv[1])[0] scoped = [ex for ex in exchanges if ex.origin == base_url] + rpc_calls = [ex for ex in scoped if _rpc_call(ex) is not None] + if rpc_calls and len(rpc_calls) * 2 >= len( + [ex for ex in scoped if ex.method == "POST"] + ): + rpc_lens = _induce_rpc_lens(scoped, base_url, entity_name) + if rpc_lens is None: + raise InductionRefused( + "RPC trace with no write the trace can attribute to a record: no " + "call that sets values on one id which a later read shows" + ) + return rpc_lens effect = _infer_effect_routes(scoped) if effect is None and not allow_unobserved_item_route: raise InductionRefused( diff --git a/packages/flow/openadapt_flow/tx/lens.py b/packages/flow/openadapt_flow/tx/lens.py index 7c65809f53..0b26bf241f 100644 --- a/packages/flow/openadapt_flow/tx/lens.py +++ b/packages/flow/openadapt_flow/tx/lens.py @@ -472,10 +472,16 @@ class LensHttpResponse: etag: Optional[str] = None extracted_entity_id: Optional[str] = None network_error: Optional[str] = None + #: The response's ``error_path`` value when the call failed inside a 2xx. + call_error: Optional[str] = None @property def ok(self) -> bool: - return self.status_code is not None and 200 <= self.status_code < 300 + return ( + self.status_code is not None + and 200 <= self.status_code < 300 + and self.call_error is None + ) def _render_template( @@ -495,6 +501,67 @@ def _replace(match: re.Match[str]) -> str: return _PLACEHOLDER_RE.sub(_replace, template) +_INT_PLACEHOLDER_RE = re.compile(r"^\{([A-Za-z0-9_.-]+):int\}$") +_WHOLE_PLACEHOLDER_RE = re.compile(r"^\{([A-Za-z0-9_.-]+)\}$") + + +def render_body_template( + template: Any, + context: Mapping[str, Any], + payload: Optional[Mapping[str, Any]] = None, +) -> Any: + """Fill an ``EndpointTemplate.body_template`` for one request. + + Containers are copied; ``"{payload}"`` becomes the write payload object, + ``"{name:int}"`` an integer (or an error), a whole ``"{name}"`` keeps the + value's type, and other strings substitute text. + """ + if isinstance(template, Mapping): + return { + str(k): render_body_template(v, context, payload) + for k, v in template.items() + } + if isinstance(template, list): + return [render_body_template(v, context, payload) for v in template] + if not isinstance(template, str): + return template + if template == "{payload}": + if payload is None: + raise ValueError("body template needs a payload") + return dict(payload) + as_int = _INT_PLACEHOLDER_RE.match(template) + if as_int: + found, val = _get_path(context, as_int.group(1)) + if not found or isinstance(val, bool): + raise ValueError(f"missing integer template parameter '{as_int.group(1)}'") + try: + return int(str(val)) + except ValueError as exc: + raise ValueError( + f"template parameter '{as_int.group(1)}' is not an integer" + ) from exc + whole = _WHOLE_PLACEHOLDER_RE.match(template) + if whole: + found, val = _get_path(context, whole.group(1)) + if not found or val is None: + raise ValueError(f"missing template parameter '{whole.group(1)}'") + return val + return _render_template(template, context) + + +def get_record_path(body: Any, path: str) -> tuple[bool, Any]: + """Follow a dotted path with list indexes (``result.0``) into JSON.""" + cur = body + for part in path.split("."): + if isinstance(cur, Mapping) and part in cur: + cur = cur[part] + elif isinstance(cur, list) and part.isdigit() and int(part) < len(cur): + cur = cur[int(part)] + else: + return False, None + return True, cur + + class EntityLensClient: """Declarative O(1) HTTP client driven strictly by an ``EntityLensSpec``.""" @@ -554,7 +621,16 @@ def _request( req_headers.update(extra_headers) body_bytes: Optional[bytes] = None - if json_payload is not None: + if endpoint.body_template is not None: + try: + rendered = render_body_template( + endpoint.body_template, context, json_payload + ) + except ValueError as exc: + return LensHttpResponse(status_code=None, network_error=str(exc)) + body_bytes = json.dumps(rendered).encode("utf-8") + req_headers.setdefault("Content-Type", "application/json") + elif json_payload is not None: body_bytes = json.dumps(dict(json_payload)).encode("utf-8") req_headers.setdefault("Content-Type", "application/json") @@ -593,12 +669,18 @@ def _request( etag = self._extract_header(resp_headers, endpoint.etag_header or "ETag") extracted_id = self._extract_entity_id(endpoint, parsed_json, resp_headers) + call_error: Optional[str] = None + if endpoint.error_path: + found_err, err_val = get_record_path(parsed_json, endpoint.error_path) + if found_err and err_val is not None: + call_error = json.dumps(err_val, default=str)[:500] return LensHttpResponse( status_code=status_code, json_body=parsed_json, headers=resp_headers, etag=etag, extracted_entity_id=extracted_id, + call_error=call_error, ) @staticmethod @@ -618,6 +700,14 @@ def _extract_entity_id( parsed_json: Any, headers: Mapping[str, str], ) -> Optional[str]: + if endpoint.record_path: + found_rec, rec = get_record_path(parsed_json, endpoint.record_path) + if found_rec and isinstance(rec, Mapping): + for id_key in (endpoint.id_field, self.lens.id_field): + found, val = _get_path(rec, id_key) + if found and val is not None and str(val).strip(): + return str(val) + return None if isinstance(parsed_json, Mapping): target_obj: Mapping[str, Any] = parsed_json if endpoint.records_key and isinstance( @@ -643,6 +733,9 @@ def unwrap_single_record( endpoint: EndpointTemplate, body: Any, ) -> Optional[dict[str, Any]]: + if endpoint.record_path: + found, rec = get_record_path(body, endpoint.record_path) + return dict(rec) if found and isinstance(rec, Mapping) else None if not isinstance(body, Mapping): return None if endpoint.records_key: diff --git a/packages/flow/openadapt_flow/tx/types.py b/packages/flow/openadapt_flow/tx/types.py index 67ba4db299..a870a1a427 100644 --- a/packages/flow/openadapt_flow/tx/types.py +++ b/packages/flow/openadapt_flow/tx/types.py @@ -197,6 +197,17 @@ class EndpointTemplate(_FrozenModel): etag_header: Optional[str] = "ETag" version_field: Optional[str] = None author_field: Optional[str] = None + #: JSON body sent with the request, for routes that take their arguments + #: in the body (an RPC call, a query document). Strings are templates: + #: ``"{id}"`` is the record id, ``"{id:int}"`` the id as an integer, + #: ``"{payload}"`` the write payload object; any other ``{name}`` is text. + body_template: Optional[Any] = None + #: Dotted path to the one record in the response, with list indexes + #: (``"result.0"``). Takes precedence over ``records_key``. + record_path: Optional[str] = None + #: Dotted path that is non-null when the call failed even though HTTP + #: said 2xx (an RPC ``error`` member). + error_path: Optional[str] = None class EntityLensSpec(_FrozenModel): diff --git a/packages/flow/tests/test_tx_rpc_lens.py b/packages/flow/tests/test_tx_rpc_lens.py new file mode 100644 index 0000000000..53064a74e5 --- /dev/null +++ b/packages/flow/tests/test_tx_rpc_lens.py @@ -0,0 +1,365 @@ +"""A lens for an app whose every call is one RPC endpoint (#2390). + +The real-app benchmark's held-out ERP sends every read and write as a +JSON-RPC ``POST`` to one path. A GET template can't read a record back, so +every update stopped before the agent acted, and induction found nothing. + +Three general pieces, none naming an app: + +- ``EndpointTemplate.body_template`` / ``record_path`` / ``error_path``: a + read or write whose arguments travel in the body, whose record sits at a + path such as ``result.0``, and whose failure arrives as a 2xx with an + ``error`` member. +- RPC induction from effects: a read names ids and fields and returns those + records; a write names one id and values that a later read shows. +- The read-back reads every field the trace read for that model. + +The CI part runs on a local server that speaks the same envelope. The live +part runs on a real app when ``OAFLOW_TX_LIVE_RPC_URL`` (the RPC endpoint, +for example ``http://127.0.0.1:9747/tryton/``), ``OAFLOW_TX_LIVE_RPC_USER`` +and ``OAFLOW_TX_LIVE_RPC_PASSWORD`` are set, and is skipped otherwise. +Synthetic records only. +""" + +from __future__ import annotations + +import base64 +import json +import os +import secrets +import tempfile +import threading +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any, Iterator, Optional +from urllib.parse import urlsplit + +import pytest + +from openadapt_flow.tx.induce import InductionRefused, induce_lens_from_har +from openadapt_flow.tx.lens import ( + EntityLensClient, + TransactionalCommitEngine, + get_record_path, + render_body_template, +) +from openadapt_flow.tx.types import TxTask +from openadapt_flow.tx.wire_tap import SessionWireTap, WirePolicy + + +def test_body_template_rendering() -> None: + tpl = {"method": "m.read", "params": [["{id:int}"], ["a"], {"u": "{who}"}], "id": 3} + assert render_body_template(tpl, {"id": "42", "who": "x"}) == { + "method": "m.read", + "params": [[42], ["a"], {"u": "x"}], + "id": 3, + } + assert render_body_template(["{payload}"], {}, {"a": 1}) == [{"a": 1}] + with pytest.raises(ValueError): + render_body_template(["{id:int}"], {"id": "abc"}) + with pytest.raises(ValueError): + render_body_template(["{payload}"], {}) + + +def test_record_path() -> None: + assert get_record_path({"result": [{"id": 1}]}, "result.0") == (True, {"id": 1}) + assert get_record_path({"result": []}, "result.0") == (False, None) + + +# --------------------------------------------------------------------------- +# A local server that speaks the envelope (CI) +# --------------------------------------------------------------------------- + + +class _RpcApp: + def __init__(self) -> None: + self.rows = { + 1: {"id": 1, "name": "Alpha", "code": "A-1", "stamp": 0}, + 2: {"id": 2, "name": "Beta", "code": "B-2", "stamp": 0}, + } + app = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args: Any) -> None: + pass + + def do_POST(self) -> None: + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + method, params = body["method"], body["params"] + out: dict[str, Any] = {"id": body.get("id")} + try: + if method == "model.thing.read": + out["result"] = [ + {"id": i, **{f: app.rows[i][f] for f in params[1]}} + for i in params[0] + ] + elif method == "model.thing.write": + for i in params[0]: + for k, v in params[1].items(): + if k not in app.rows[i]: + raise KeyError(k) + app.rows[i][k] = v + app.rows[i]["stamp"] += 1 + out["result"] = None + elif method == "model.other.search_read": + out["result"] = [{"id": 9, "label": "x"}] + else: + raise KeyError(method) + except KeyError as exc: + out = {"id": body.get("id"), "error": [repr(exc), ""]} + raw = json.dumps(out).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(raw))) + self.end_headers() + self.wfile.write(raw) + + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.base = f"http://127.0.0.1:{self.server.server_port}" + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + + def close(self) -> None: + self.server.shutdown() + self.server.server_close() + self.thread.join(timeout=5) + + +@pytest.fixture() +def rpc_app() -> Iterator[_RpcApp]: + app = _RpcApp() + try: + yield app + finally: + app.close() + + +def _rpc(base: str, path: str, method: str, params: list, auth: Optional[str] = None): + headers = {"Content-Type": "application/json"} + if auth: + headers["Authorization"] = auth + req = urllib.request.Request( + base + path, + data=json.dumps({"id": 1, "method": method, "params": params}).encode(), + headers=headers, + method="POST", + ) + with urllib.request.urlopen(req, timeout=30) as resp: + return json.loads(resp.read()) + + +def _demo( + base: str, + path: str, + model: str, + rid: int, + fields: list[str], + change: dict, + auth: Optional[str] = None, + ctx: Any = None, + noise: Optional[str] = None, +) -> dict: + tail = [ctx] if ctx is not None else [] + with SessionWireTap(base, WirePolicy(max_mutations=None)) as tap: + b = tap.base_url + if noise: + _rpc(b, path, noise, [[], ["id"], *tail], auth) + _rpc(b, path, f"{model}.read", [[rid], fields, *tail], auth) + _rpc(b, path, f"{model}.write", [[rid], change, *tail], auth) + _rpc(b, path, f"{model}.read", [[rid], fields, *tail], auth) + return tap.export_har() + + +def test_rpc_trace_induces_a_body_templated_lens(rpc_app) -> None: + har = _demo( + rpc_app.base, + "/rpc/", + "model.thing", + 1, + ["name", "code", "stamp"], + {"name": "Alpha 2"}, + noise="model.other.search_read", + ) + lens = induce_lens_from_har(har) + assert lens.entity_name == "thing" + assert lens.get_one.method == "POST" and lens.get_one.path_template == "/rpc/" + assert lens.get_one.body_template["method"] == "model.thing.read" + assert lens.get_one.body_template["params"][0] == ["{id:int}"] + assert lens.get_one.body_template["params"][1] == ["name", "code", "stamp"] + assert lens.get_one.record_path == "result.0" + assert lens.write_endpoint.body_template["params"][1] == "{payload}" + # The server bumped ``stamp`` without being asked: volatile, by evidence. + assert lens.volatile_fields == ("stamp",) + + +def test_rpc_lens_writes_and_reads_back(rpc_app, tmp_path) -> None: + har = _demo( + rpc_app.base, + "/rpc/", + "model.thing", + 1, + ["name", "code", "stamp"], + {"name": "Alpha 2"}, + ) + lens = induce_lens_from_har(har) + _, rec, _ = EntityLensClient(lens).get_one("2") + assert rec is not None and rec["code"] == "B-2" + engine = TransactionalCommitEngine(lens, tmp_path, allow_unqualified_prototype=True) + result = engine.execute( + TxTask( + task_id="t1", + operation="update", + entity_id="2", + intended_delta={"code": "B-3"}, + ) + ) + assert result.outcome == "UNCERTAIN" + assert set(result.reasons) == {"unqualified_observation_only"} + assert rpc_app.rows[2]["code"] == "B-3" and rpc_app.rows[2]["name"] == "Beta" + + +def test_rpc_error_inside_2xx_is_a_failed_write(rpc_app, tmp_path) -> None: + har = _demo( + rpc_app.base, "/rpc/", "model.thing", 1, ["name", "code"], {"name": "A"} + ) + lens = induce_lens_from_har(har) + resp = EntityLensClient(lens).write("update", {"nosuch": 1}, entity_id="2") + assert resp.status_code == 200 and not resp.ok and resp.call_error + engine = TransactionalCommitEngine(lens, tmp_path, allow_unqualified_prototype=True) + result = engine.execute( + TxTask( + task_id="t2", + operation="update", + entity_id="2", + intended_delta={"nosuch": 1}, + ) + ) + assert result.outcome != "CONFIRMED" + assert result.outcome in ("REFUTED", "UNCERTAIN", "BLOCKED_PRECOMMIT") + + +def test_rpc_trace_with_only_reads_is_refused(rpc_app) -> None: + with SessionWireTap(rpc_app.base, WirePolicy(max_mutations=None)) as tap: + _rpc(tap.base_url, "/rpc/", "model.thing.read", [[1], ["name"]]) + har = tap.export_har() + with pytest.raises(InductionRefused, match="RPC trace"): + induce_lens_from_har(har) + + +def test_rpc_write_without_a_confirming_read_is_refused(rpc_app) -> None: + with SessionWireTap(rpc_app.base, WirePolicy(max_mutations=None)) as tap: + _rpc(tap.base_url, "/rpc/", "model.thing.read", [[1], ["name"]]) + _rpc(tap.base_url, "/rpc/", "model.thing.write", [[1], {"name": "Z"}]) + har = tap.export_har() + with pytest.raises(InductionRefused): + induce_lens_from_har(har) + + +# --------------------------------------------------------------------------- +# Live application (lab only) +# --------------------------------------------------------------------------- + +LIVE = os.environ.get("OAFLOW_TX_LIVE_RPC_URL", "").strip() +USER = os.environ.get("OAFLOW_TX_LIVE_RPC_USER", "") +PASSWORD = os.environ.get("OAFLOW_TX_LIVE_RPC_PASSWORD", "") +live = pytest.mark.skipif( + not (LIVE and USER and PASSWORD), reason="set OAFLOW_TX_LIVE_RPC_*" +) + + +@pytest.fixture(scope="module") +def live_app() -> dict[str, Any]: + parts = urlsplit(LIVE) + base, path = f"{parts.scheme}://{parts.netloc}", parts.path + login = _rpc(base, path, "common.db.login", [USER, {"password": PASSWORD}, "en"]) + uid, session = login["result"] + auth = "Session " + base64.b64encode(f"{USER}:{uid}:{session}".encode()).decode() + tag = secrets.token_hex(3) + made = _rpc( + base, + path, + "model.party.party.create", + [[{"name": f"Lens party {tag}", "code": f"LENS-{tag}"}], {}], + auth, + ) + return { + "base": base, + "path": path, + "auth": auth, + "pid": made["result"][0], + "tag": tag, + } + + +FIELDS = ["name", "code", "active", "lang", "write_date"] + + +@live +def test_live_rpc_lens_induces_writes_and_reads_back(live_app) -> None: + b, path, auth, pid = ( + live_app["base"], + live_app["path"], + live_app["auth"], + live_app["pid"], + ) + har = _demo( + b, + path, + "model.party.party", + pid, + FIELDS, + {"name": f"Lens party {live_app['tag']} renamed"}, + auth=auth, + ctx={}, + noise="model.ir.lang.search_read", + ) + lens = induce_lens_from_har(har) + assert lens.entity_name == "party" + assert lens.get_one.body_template["method"] == "model.party.party.read" + assert "write_date" in lens.volatile_fields + engine = TransactionalCommitEngine( + lens, + tempfile.mkdtemp(prefix="lens-rpc-"), + headers={"Authorization": auth}, + allow_unqualified_prototype=True, + ) + new_code = f"LENS-{live_app['tag']}-2" + result = engine.execute( + TxTask( + task_id="live-" + secrets.token_hex(3), + operation="update", + entity_id=str(pid), + intended_delta={"code": new_code}, + ) + ) + truth = _rpc(b, path, "model.party.party.read", [[pid], ["name", "code"], {}], auth) + assert truth["result"][0]["code"] == new_code + assert truth["result"][0]["name"].endswith("renamed") + assert result.outcome == "UNCERTAIN", result.reasons + assert set(result.reasons) == {"unqualified_observation_only"} + + +@live +def test_live_rpc_error_is_not_a_success(live_app) -> None: + b, path, auth, pid = ( + live_app["base"], + live_app["path"], + live_app["auth"], + live_app["pid"], + ) + har = _demo( + b, + path, + "model.party.party", + pid, + FIELDS, + {"name": f"Lens party {live_app['tag']} again"}, + auth=auth, + ctx={}, + ) + lens = induce_lens_from_har(har) + resp = EntityLensClient(lens, headers={"Authorization": auth}).write( + "update", {"no_such_field": "x"}, entity_id=str(pid) + ) + # The app answers 200 with an ``error`` member; the lens reads it as failed. + assert resp.status_code == 200 and not resp.ok