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
@@ -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` |
167 changes: 167 additions & 0 deletions packages/flow/openadapt_flow/tx/induce.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down Expand Up @@ -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,
)
)

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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(
Expand Down
97 changes: 95 additions & 2 deletions packages/flow/openadapt_flow/tx/lens.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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``."""

Expand Down Expand Up @@ -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")

Expand Down Expand Up @@ -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
Expand All @@ -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(
Expand All @@ -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:
Expand Down
11 changes: 11 additions & 0 deletions packages/flow/openadapt_flow/tx/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading