amiril 0.0.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- amiril/__init__.py +51 -0
- amiril/_adapters.py +399 -0
- amiril/_engine/__init__.py +1 -0
- amiril/_engine/engine.py +113 -0
- amiril/_engine/expr.py +653 -0
- amiril/_engine/numbers.py +111 -0
- amiril/_engine/regex.py +262 -0
- amiril/_engine/rules.py +192 -0
- amiril/_engine/sentence.py +251 -0
- amiril/_engine/timeparse.py +72 -0
- amiril/_engine/validate.py +863 -0
- amiril/_engine/values.py +273 -0
- amiril/_kernel/__init__.py +1 -0
- amiril/_kernel/bundle.py +245 -0
- amiril/_kernel/coerce.py +103 -0
- amiril/_kernel/events.py +87 -0
- amiril/_kernel/guard.py +1196 -0
- amiril/_kernel/ids.py +66 -0
- amiril/_kernel/messages.py +30 -0
- amiril/_kernel/normalise.py +165 -0
- amiril/_kernel/records.py +131 -0
- amiril/_kernel/store.py +661 -0
- amiril/_runtime.py +617 -0
- amiril/adk.py +577 -0
- amiril/control/__init__.py +25 -0
- amiril/control/_delivery.py +567 -0
- amiril/control/_disk.py +418 -0
- amiril/control/_holds.py +252 -0
- amiril/control/_jsonschema.py +265 -0
- amiril/control/_pathc.py +85 -0
- amiril/control/_records.py +293 -0
- amiril/control/_redact.py +79 -0
- amiril/control/_transport.py +184 -0
- amiril/control/_wire.py +73 -0
- amiril/control/client.py +1313 -0
- amiril/control/config.py +204 -0
- amiril/control/schemas/bundle.response.schema.json +22 -0
- amiril/control/schemas/common.schema.json +593 -0
- amiril/control/schemas/decisions.request.schema.json +558 -0
- amiril/control/schemas/decisions.response.schema.json +23 -0
- amiril/control/schemas/error.response.schema.json +54 -0
- amiril/control/schemas/heartbeat.request.schema.json +305 -0
- amiril/control/schemas/heartbeat.response.schema.json +34 -0
- amiril/control/schemas/hold-create.request.schema.json +138 -0
- amiril/control/schemas/hold.response.schema.json +226 -0
- amiril/control/schemas/installation-register.request.schema.json +492 -0
- amiril/control/schemas/installation-register.response.schema.json +85 -0
- amiril/core.py +89 -0
- amiril/docs/README.md +14 -0
- amiril/docs/durability/langgraph.md +292 -0
- amiril/docs/frameworks/adk.md +141 -0
- amiril/docs/frameworks/langgraph.md +154 -0
- amiril/docs/frameworks/no-framework.md +238 -0
- amiril/docs/frameworks/write-an-adapter.md +203 -0
- amiril/durable.py +342 -0
- amiril/langgraph.py +746 -0
- amiril/plain.py +454 -0
- amiril/py.typed +0 -0
- amiril/seams.py +357 -0
- amiril/testing.py +21 -0
- amiril-0.0.0.dev0.dist-info/METADATA +114 -0
- amiril-0.0.0.dev0.dist-info/RECORD +64 -0
- amiril-0.0.0.dev0.dist-info/WHEEL +4 -0
- amiril-0.0.0.dev0.dist-info/licenses/LICENSE +202 -0
amiril/_engine/expr.py
ADDED
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
"""Expression evaluation (spec/edoc.md, sections 5 to 9).
|
|
2
|
+
|
|
3
|
+
Documents reach the evaluator validated, so node shapes are trusted and
|
|
4
|
+
only data-dependent failures arise, as `EvalError`. Three-valued logic:
|
|
5
|
+
Missing propagates through every operator; `and`, `or`, `not` and the
|
|
6
|
+
quantifiers follow 8.1; an error raised while evaluating an operand
|
|
7
|
+
always wins over a Missing elsewhere (8.2).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from .._kernel.normalise import to_json
|
|
16
|
+
from .numbers import extreme_max, extreme_min, neumaier_sum
|
|
17
|
+
from .regex import compile_pattern
|
|
18
|
+
from .timeparse import hour_of_epoch, hour_of_iso
|
|
19
|
+
from .validate import tool_label
|
|
20
|
+
from .values import (
|
|
21
|
+
ABSENT,
|
|
22
|
+
MISSING,
|
|
23
|
+
EvalError,
|
|
24
|
+
Selection,
|
|
25
|
+
count_distinct,
|
|
26
|
+
describe,
|
|
27
|
+
equal,
|
|
28
|
+
is_number,
|
|
29
|
+
record_field,
|
|
30
|
+
record_path,
|
|
31
|
+
record_view,
|
|
32
|
+
segments,
|
|
33
|
+
type_name,
|
|
34
|
+
walk,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
_NO_IT = object()
|
|
38
|
+
PICK_ALL_CAP = 20
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Evidence:
|
|
42
|
+
"""What a rule read, keyed by path; the first read of a path wins (edoc.md 9)."""
|
|
43
|
+
|
|
44
|
+
__slots__ = ("entries",)
|
|
45
|
+
|
|
46
|
+
def __init__(self) -> None:
|
|
47
|
+
self.entries: dict[str, dict] = {}
|
|
48
|
+
|
|
49
|
+
def read(self, path: str, value: Any, truncated: int | None = None) -> None:
|
|
50
|
+
if path in self.entries:
|
|
51
|
+
return
|
|
52
|
+
if value is MISSING:
|
|
53
|
+
self.entries[path] = {"path": path, "value": None, "missing": True}
|
|
54
|
+
elif value is ABSENT:
|
|
55
|
+
self.entries[path] = {"path": path, "value": None, "absent": True}
|
|
56
|
+
elif type(value) is Selection:
|
|
57
|
+
return
|
|
58
|
+
else:
|
|
59
|
+
entry = {"path": path, "value": value}
|
|
60
|
+
if truncated is not None:
|
|
61
|
+
entry["truncated"] = truncated
|
|
62
|
+
self.entries[path] = entry
|
|
63
|
+
|
|
64
|
+
def name(self, path: str, name: str) -> None:
|
|
65
|
+
entry = self.entries.get(path)
|
|
66
|
+
if entry is not None and "name" not in entry:
|
|
67
|
+
entry["name"] = name
|
|
68
|
+
|
|
69
|
+
def as_list(self) -> list[dict]:
|
|
70
|
+
return list(self.entries.values())
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class HistoryIndex:
|
|
74
|
+
"""Scope narrowing (edoc.md 6.5) and per-tool lookup over one snapshot's
|
|
75
|
+
history, computed once and shared by every rule evaluated against it."""
|
|
76
|
+
|
|
77
|
+
__slots__ = ("call", "history", "run_floor", "_scoped", "_groups")
|
|
78
|
+
|
|
79
|
+
def __init__(self, call: Any, history: list, run_floor: int | None = None) -> None:
|
|
80
|
+
self.call = call
|
|
81
|
+
self.history = history
|
|
82
|
+
# kernel.md 6.1: records of the same root run that arrived before the
|
|
83
|
+
# live run started belong to an evicted run; they are session history only.
|
|
84
|
+
self.run_floor = run_floor
|
|
85
|
+
self._scoped: dict[str, list] = {}
|
|
86
|
+
self._groups: dict[str, dict[str, list]] = {}
|
|
87
|
+
|
|
88
|
+
def scoped(self, scope: str) -> list:
|
|
89
|
+
recs = self._scoped.get(scope)
|
|
90
|
+
if recs is None:
|
|
91
|
+
recs = self._scoped[scope] = self._filter(scope)
|
|
92
|
+
return recs
|
|
93
|
+
|
|
94
|
+
def _filter(self, scope: str) -> list:
|
|
95
|
+
call = self.call
|
|
96
|
+
if scope == "run":
|
|
97
|
+
root = record_field(call, "root_run_id")
|
|
98
|
+
floor = self.run_floor
|
|
99
|
+
if floor is None:
|
|
100
|
+
return [r for r in self.history if record_field(r, "root_run_id") == root]
|
|
101
|
+
return [r for r in self.history
|
|
102
|
+
if record_field(r, "root_run_id") == root and getattr(r, "arrival", floor) >= floor]
|
|
103
|
+
if scope == "session":
|
|
104
|
+
sid = record_field(call, "session_id")
|
|
105
|
+
if sid is None or sid is ABSENT:
|
|
106
|
+
return self.scoped("run")
|
|
107
|
+
return [r for r in self.history if record_field(r, "session_id") == sid]
|
|
108
|
+
name = scope.split(":", 1)[1]
|
|
109
|
+
mine = record_field(call, "correlation")
|
|
110
|
+
key = mine.get(name) if type(mine) is dict else None
|
|
111
|
+
if key is None:
|
|
112
|
+
return []
|
|
113
|
+
out = []
|
|
114
|
+
for r in self.history:
|
|
115
|
+
corr = record_field(r, "correlation")
|
|
116
|
+
if type(corr) is dict and name in corr and equal(corr[name], key):
|
|
117
|
+
out.append(r)
|
|
118
|
+
return out
|
|
119
|
+
|
|
120
|
+
def by_tool(self, scope: str, tool: str) -> list:
|
|
121
|
+
groups = self._groups.get(scope)
|
|
122
|
+
if groups is None:
|
|
123
|
+
groups = self._groups[scope] = {}
|
|
124
|
+
for r in self.scoped(scope):
|
|
125
|
+
groups.setdefault(record_field(r, "tool_id"), []).append(r)
|
|
126
|
+
return groups.get(tool, ())
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class Env:
|
|
130
|
+
__slots__ = ("call", "context", "history", "scope", "sets", "vars", "it", "it_is_record", "evidence")
|
|
131
|
+
|
|
132
|
+
def __init__(self, call: Any, context: dict, history: HistoryIndex, scope: str, sets: dict) -> None:
|
|
133
|
+
self.call = call
|
|
134
|
+
self.context = context
|
|
135
|
+
self.history = history
|
|
136
|
+
self.scope = scope
|
|
137
|
+
self.sets = sets
|
|
138
|
+
self.vars: dict[str, Any] = {}
|
|
139
|
+
self.it: Any = _NO_IT
|
|
140
|
+
self.it_is_record = False
|
|
141
|
+
self.evidence = Evidence()
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class Evaluator:
|
|
145
|
+
def __init__(self, doc: dict, predicates: dict[str, Callable[..., Any]] | None = None) -> None:
|
|
146
|
+
self.predicates = dict(predicates or {})
|
|
147
|
+
args_aliases: dict[str, str] = (doc.get("aliases") or {}).get("args") or {}
|
|
148
|
+
# canonical name -> raw names that alias to it, in document order (edoc.md 6.1, arg).
|
|
149
|
+
self._reverse_alias: dict[str, list[str]] = {}
|
|
150
|
+
for raw, canon in args_aliases.items():
|
|
151
|
+
self._reverse_alias.setdefault(canon, []).append(raw)
|
|
152
|
+
self._plans: dict[int, tuple[list[tuple[str, Any]], Any]] = {}
|
|
153
|
+
self._ops: dict[str, Callable[[Any, Env], Any]] = {
|
|
154
|
+
"==": self._eq, "!=": self._ne, "<": self._lt, "<=": self._le, ">": self._gt, ">=": self._ge,
|
|
155
|
+
"and": self._and, "or": self._or, "not": self._not,
|
|
156
|
+
"+": self._add, "-": self._sub, "*": self._mul, "/": self._div,
|
|
157
|
+
"min": self._min, "max": self._max, "abs": self._abs,
|
|
158
|
+
"in": self._in, "matches": self._matches, "len": self._len,
|
|
159
|
+
"present": self._present, "is": self._is,
|
|
160
|
+
"all": self._all, "any": self._any, "exists": self._exists,
|
|
161
|
+
"arg": self._arg, "path": self._path, "ctx": self._ctx, "set": self._set, "var": self._var,
|
|
162
|
+
"it": self._it, "lit": self._lit, "prev": self._prev,
|
|
163
|
+
"calls": self._calls, "prior": self._prior, "agg": self._agg,
|
|
164
|
+
"hour_utc": self._hour_utc, "predicate": self._predicate,
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
# ------------------------------------------------------------ core
|
|
168
|
+
|
|
169
|
+
def eval(self, node: Any, env: Env) -> Any:
|
|
170
|
+
t = type(node)
|
|
171
|
+
if t is dict:
|
|
172
|
+
(op, arg), = node.items()
|
|
173
|
+
return self._ops[op](arg, env)
|
|
174
|
+
if t is int:
|
|
175
|
+
return float(node)
|
|
176
|
+
return node
|
|
177
|
+
|
|
178
|
+
def _operands(self, nodes: list, env: Env) -> tuple[list, bool]:
|
|
179
|
+
vals = [self.eval(n, env) for n in nodes]
|
|
180
|
+
return vals, any(v is MISSING for v in vals)
|
|
181
|
+
|
|
182
|
+
# ------------------------------------------------------------ reads
|
|
183
|
+
|
|
184
|
+
def _arg(self, path: str, env: Env) -> Any:
|
|
185
|
+
segs = segments(path)
|
|
186
|
+
head = segs[0]
|
|
187
|
+
args = record_field(env.call, "args")
|
|
188
|
+
if type(args) is not dict:
|
|
189
|
+
args = {}
|
|
190
|
+
key = head
|
|
191
|
+
if head not in args:
|
|
192
|
+
for raw in self._reverse_alias.get(head, ()):
|
|
193
|
+
if raw in args:
|
|
194
|
+
key = raw
|
|
195
|
+
break
|
|
196
|
+
if key in args:
|
|
197
|
+
value = args[key] if len(segs) == 1 else walk(args[key], segs[1:])
|
|
198
|
+
else:
|
|
199
|
+
value = ABSENT
|
|
200
|
+
env.evidence.read(f"call.args.{path}", value)
|
|
201
|
+
return value
|
|
202
|
+
|
|
203
|
+
def _path(self, path: str, env: Env) -> Any:
|
|
204
|
+
segs = segments(path)
|
|
205
|
+
value = record_view(env.call) if len(segs) == 1 else record_path(env.call, path[5:])
|
|
206
|
+
env.evidence.read(path, value)
|
|
207
|
+
return value
|
|
208
|
+
|
|
209
|
+
def _ctx(self, path: str, env: Env) -> Any:
|
|
210
|
+
value = walk(env.context, segments(path))
|
|
211
|
+
env.evidence.read(f"context.{path}", value)
|
|
212
|
+
return value
|
|
213
|
+
|
|
214
|
+
def _set(self, name: str, env: Env) -> Any:
|
|
215
|
+
return env.sets.get(name, [])
|
|
216
|
+
|
|
217
|
+
def _var(self, name: str, env: Env) -> Any:
|
|
218
|
+
return env.vars[name]
|
|
219
|
+
|
|
220
|
+
def _it(self, path: str, env: Env) -> Any:
|
|
221
|
+
item = env.it
|
|
222
|
+
if env.it_is_record:
|
|
223
|
+
return record_view(item) if path == "" else record_path(item, path)
|
|
224
|
+
return item if path == "" else walk(item, segments(path))
|
|
225
|
+
|
|
226
|
+
def _lit(self, values: list, env: Env) -> Any:
|
|
227
|
+
return [float(v) if type(v) is int else v for v in values]
|
|
228
|
+
|
|
229
|
+
# ------------------------------------------------------------ history
|
|
230
|
+
|
|
231
|
+
def _select(self, spec: dict, env: Env) -> Selection:
|
|
232
|
+
scope = spec.get("scope", env.scope)
|
|
233
|
+
tool = spec["tool"]
|
|
234
|
+
label = tool_label(tool)
|
|
235
|
+
status = spec.get("status", "ok")
|
|
236
|
+
# Steps 1 to 3: scope, tool, status.
|
|
237
|
+
if type(tool) is list:
|
|
238
|
+
wanted = set(tool)
|
|
239
|
+
recs = [r for r in env.history.scoped(scope) if record_field(r, "tool_id") in wanted]
|
|
240
|
+
elif tool == "*":
|
|
241
|
+
recs = env.history.scoped(scope)
|
|
242
|
+
else:
|
|
243
|
+
recs = env.history.by_tool(scope, tool)
|
|
244
|
+
if status != "any":
|
|
245
|
+
allowed = (status,) if type(status) is str else status
|
|
246
|
+
recs = [r for r in recs if record_field(r, "status") in allowed]
|
|
247
|
+
# Step 4: pre-evaluated equality terms, always evaluated, in order.
|
|
248
|
+
where = spec.get("where")
|
|
249
|
+
residual = None
|
|
250
|
+
if where is not None:
|
|
251
|
+
eq_terms, residual = self._where_plan(where)
|
|
252
|
+
empty = False
|
|
253
|
+
for path, node in eq_terms:
|
|
254
|
+
key = self.eval(node, env)
|
|
255
|
+
if key is MISSING or key is ABSENT:
|
|
256
|
+
empty = True
|
|
257
|
+
elif not empty:
|
|
258
|
+
if path == "":
|
|
259
|
+
recs = [r for r in recs if equal(record_view(r), key)]
|
|
260
|
+
else:
|
|
261
|
+
recs = [r for r in recs if equal(record_path(r, path), key)]
|
|
262
|
+
if empty:
|
|
263
|
+
recs = []
|
|
264
|
+
# Step 5: kind.
|
|
265
|
+
kind = spec.get("kind")
|
|
266
|
+
if kind is not None:
|
|
267
|
+
recs = [r for r in recs if record_field(r, "kind") == kind]
|
|
268
|
+
# Step 6: join.
|
|
269
|
+
join = spec.get("join")
|
|
270
|
+
if join is not None:
|
|
271
|
+
names = (join,) if type(join) is str else join
|
|
272
|
+
mine = record_field(env.call, "correlation")
|
|
273
|
+
if type(mine) is not dict:
|
|
274
|
+
mine = {}
|
|
275
|
+
keys = [mine.get(n) for n in names]
|
|
276
|
+
if any(k is None for k in keys):
|
|
277
|
+
recs = []
|
|
278
|
+
else:
|
|
279
|
+
kept = []
|
|
280
|
+
for r in recs:
|
|
281
|
+
corr = record_field(r, "correlation")
|
|
282
|
+
if type(corr) is dict and all(n in corr and equal(corr[n], k) for n, k in zip(names, keys)):
|
|
283
|
+
kept.append(r)
|
|
284
|
+
recs = kept
|
|
285
|
+
# Step 7: residual predicate.
|
|
286
|
+
if residual is not None and recs:
|
|
287
|
+
recs = [r for r in recs if self._where_holds(residual, r, env)]
|
|
288
|
+
return Selection(recs if type(recs) is list else list(recs), label)
|
|
289
|
+
|
|
290
|
+
def _where_plan(self, where: Any) -> tuple[list[tuple[str, Any]], Any]:
|
|
291
|
+
plan = self._plans.get(id(where))
|
|
292
|
+
if plan is not None:
|
|
293
|
+
return plan
|
|
294
|
+
terms = where["and"] if type(where) is dict and len(where) == 1 and "and" in where else [where]
|
|
295
|
+
eq_terms: list[tuple[str, Any]] = []
|
|
296
|
+
rest: list[Any] = []
|
|
297
|
+
for t in terms:
|
|
298
|
+
if type(t) is dict and len(t) == 1 and "==" in t:
|
|
299
|
+
left, right = t["=="]
|
|
300
|
+
if _is_it(left) and not _uses_it(right):
|
|
301
|
+
eq_terms.append((left["it"], right))
|
|
302
|
+
continue
|
|
303
|
+
if _is_it(right) and not _uses_it(left):
|
|
304
|
+
eq_terms.append((right["it"], left))
|
|
305
|
+
continue
|
|
306
|
+
rest.append(t)
|
|
307
|
+
residual = None if not rest else rest[0] if len(rest) == 1 else {"and": rest}
|
|
308
|
+
plan = self._plans[id(where)] = (eq_terms, residual)
|
|
309
|
+
return plan
|
|
310
|
+
|
|
311
|
+
def _where_holds(self, pred: Any, item: Any, env: Env) -> bool:
|
|
312
|
+
saved, saved_kind = env.it, env.it_is_record
|
|
313
|
+
env.it, env.it_is_record = item, True
|
|
314
|
+
try:
|
|
315
|
+
v = self.eval(pred, env)
|
|
316
|
+
finally:
|
|
317
|
+
env.it, env.it_is_record = saved, saved_kind
|
|
318
|
+
if v is True:
|
|
319
|
+
return True
|
|
320
|
+
if v is False or v is MISSING:
|
|
321
|
+
return False
|
|
322
|
+
raise EvalError(f"a where predicate must be boolean, got {describe(v)}")
|
|
323
|
+
|
|
324
|
+
def _calls(self, spec: dict, env: Env) -> Selection:
|
|
325
|
+
return self._select(spec, env)
|
|
326
|
+
|
|
327
|
+
def _exists(self, node: dict, env: Env) -> Any:
|
|
328
|
+
sel = self._select(node["calls"], env)
|
|
329
|
+
found = bool(sel.records)
|
|
330
|
+
env.evidence.read(f"history.{sel.label}.exists", found)
|
|
331
|
+
return found
|
|
332
|
+
|
|
333
|
+
def _prev(self, path: str, env: Env) -> Any:
|
|
334
|
+
recs = env.history.scoped(env.scope)
|
|
335
|
+
value = record_path(recs[-1], path) if recs else MISSING
|
|
336
|
+
env.evidence.read(f"history.prev.{path}", value)
|
|
337
|
+
return value
|
|
338
|
+
|
|
339
|
+
def _prior(self, spec: dict, env: Env) -> Any:
|
|
340
|
+
sel = self._select(spec, env)
|
|
341
|
+
pick = spec.get("pick", "latest")
|
|
342
|
+
path = spec["path"]
|
|
343
|
+
label = f"history.{sel.label}.{pick}.{path}"
|
|
344
|
+
if not sel.records:
|
|
345
|
+
env.evidence.read(label, MISSING)
|
|
346
|
+
return MISSING
|
|
347
|
+
if pick == "all":
|
|
348
|
+
values = []
|
|
349
|
+
n = len(sel.records)
|
|
350
|
+
for i, r in enumerate(sel.records):
|
|
351
|
+
v = record_path(r, path)
|
|
352
|
+
if v is ABSENT:
|
|
353
|
+
raise EvalError(f"{path} is absent on {sel.label} record {i + 1} of {n}")
|
|
354
|
+
values.append(v)
|
|
355
|
+
if n > PICK_ALL_CAP:
|
|
356
|
+
env.evidence.read(label, values[:PICK_ALL_CAP], truncated=n)
|
|
357
|
+
else:
|
|
358
|
+
env.evidence.read(label, values)
|
|
359
|
+
return values
|
|
360
|
+
rec = sel.records[-1] if pick == "latest" else sel.records[0]
|
|
361
|
+
value = record_path(rec, path)
|
|
362
|
+
env.evidence.read(label, value)
|
|
363
|
+
return value
|
|
364
|
+
|
|
365
|
+
def _agg(self, spec: dict, env: Env) -> Any:
|
|
366
|
+
sel = self._select(spec["of"]["calls"], env)
|
|
367
|
+
op = spec["op"]
|
|
368
|
+
field = spec.get("field")
|
|
369
|
+
label = f"history.{sel.label}.{op}" + (f".{field}" if field else "")
|
|
370
|
+
values: list[Any] = []
|
|
371
|
+
if field is not None:
|
|
372
|
+
n = len(sel.records)
|
|
373
|
+
for i, r in enumerate(sel.records):
|
|
374
|
+
v = record_path(r, field)
|
|
375
|
+
if v is ABSENT:
|
|
376
|
+
raise EvalError(f"{field} is absent on {sel.label} record {i + 1} of {n}")
|
|
377
|
+
values.append(v)
|
|
378
|
+
else:
|
|
379
|
+
values = [None] * len(sel.records)
|
|
380
|
+
extra, missing = self._operands(spec.get("with") or [], env)
|
|
381
|
+
if missing:
|
|
382
|
+
env.evidence.read(label, MISSING)
|
|
383
|
+
return MISSING
|
|
384
|
+
values.extend(extra)
|
|
385
|
+
if op == "count":
|
|
386
|
+
out: Any = float(len(values))
|
|
387
|
+
elif op == "count_distinct":
|
|
388
|
+
for v in values:
|
|
389
|
+
if v is ABSENT:
|
|
390
|
+
raise EvalError(f"{label} value needs a value, got absent (no such key)")
|
|
391
|
+
out = float(count_distinct(values))
|
|
392
|
+
else:
|
|
393
|
+
for v in values:
|
|
394
|
+
if not is_number(v):
|
|
395
|
+
raise EvalError(f"{label} value needs a number, got {describe(v)}")
|
|
396
|
+
if not values:
|
|
397
|
+
out = 0.0 if op == "sum" else MISSING
|
|
398
|
+
elif op == "sum":
|
|
399
|
+
out = neumaier_sum(values)
|
|
400
|
+
elif op == "min":
|
|
401
|
+
out = extreme_min(values)
|
|
402
|
+
else:
|
|
403
|
+
out = extreme_max(values)
|
|
404
|
+
env.evidence.read(label, out)
|
|
405
|
+
return out
|
|
406
|
+
|
|
407
|
+
# ------------------------------------------------------------ comparison
|
|
408
|
+
|
|
409
|
+
def _eq(self, nodes: list, env: Env) -> Any:
|
|
410
|
+
a = self.eval(nodes[0], env)
|
|
411
|
+
b = self.eval(nodes[1], env)
|
|
412
|
+
if a is MISSING or b is MISSING:
|
|
413
|
+
return MISSING
|
|
414
|
+
if a is ABSENT or b is ABSENT:
|
|
415
|
+
return False
|
|
416
|
+
return equal(a, b)
|
|
417
|
+
|
|
418
|
+
def _ne(self, nodes: list, env: Env) -> Any:
|
|
419
|
+
r = self._eq(nodes, env)
|
|
420
|
+
return MISSING if r is MISSING else not r
|
|
421
|
+
|
|
422
|
+
def _ordered(self, nodes: list, env: Env, what: str) -> tuple[Any, Any] | None:
|
|
423
|
+
a = self.eval(nodes[0], env)
|
|
424
|
+
b = self.eval(nodes[1], env)
|
|
425
|
+
if a is MISSING or b is MISSING:
|
|
426
|
+
return None
|
|
427
|
+
if is_number(a) and is_number(b):
|
|
428
|
+
return a, b
|
|
429
|
+
if type(a) is str and type(b) is str:
|
|
430
|
+
return a, b
|
|
431
|
+
raise EvalError(f"{what} needs two numbers or two strings, got {describe(a)} and {describe(b)}")
|
|
432
|
+
|
|
433
|
+
def _lt(self, nodes: list, env: Env) -> Any:
|
|
434
|
+
p = self._ordered(nodes, env, "<")
|
|
435
|
+
return MISSING if p is None else p[0] < p[1]
|
|
436
|
+
|
|
437
|
+
def _le(self, nodes: list, env: Env) -> Any:
|
|
438
|
+
p = self._ordered(nodes, env, "<=")
|
|
439
|
+
return MISSING if p is None else p[0] <= p[1]
|
|
440
|
+
|
|
441
|
+
def _gt(self, nodes: list, env: Env) -> Any:
|
|
442
|
+
p = self._ordered(nodes, env, ">")
|
|
443
|
+
return MISSING if p is None else p[0] > p[1]
|
|
444
|
+
|
|
445
|
+
def _ge(self, nodes: list, env: Env) -> Any:
|
|
446
|
+
p = self._ordered(nodes, env, ">=")
|
|
447
|
+
return MISSING if p is None else p[0] >= p[1]
|
|
448
|
+
|
|
449
|
+
# ------------------------------------------------------------ logic
|
|
450
|
+
|
|
451
|
+
@staticmethod
|
|
452
|
+
def _bool(v: Any, what: str) -> Any:
|
|
453
|
+
if v is True or v is False or v is MISSING:
|
|
454
|
+
return v
|
|
455
|
+
raise EvalError(f"{what} needs a boolean, got {describe(v)}")
|
|
456
|
+
|
|
457
|
+
def _and(self, nodes: list, env: Env) -> Any:
|
|
458
|
+
saw_missing = False
|
|
459
|
+
for n in nodes:
|
|
460
|
+
v = self._bool(self.eval(n, env), "and")
|
|
461
|
+
if v is False:
|
|
462
|
+
return False
|
|
463
|
+
if v is MISSING:
|
|
464
|
+
saw_missing = True
|
|
465
|
+
return MISSING if saw_missing else True
|
|
466
|
+
|
|
467
|
+
def _or(self, nodes: list, env: Env) -> Any:
|
|
468
|
+
saw_missing = False
|
|
469
|
+
for n in nodes:
|
|
470
|
+
v = self._bool(self.eval(n, env), "or")
|
|
471
|
+
if v is True:
|
|
472
|
+
return True
|
|
473
|
+
if v is MISSING:
|
|
474
|
+
saw_missing = True
|
|
475
|
+
return MISSING if saw_missing else False
|
|
476
|
+
|
|
477
|
+
def _not(self, node: Any, env: Env) -> Any:
|
|
478
|
+
v = self._bool(self.eval(node, env), "not")
|
|
479
|
+
return MISSING if v is MISSING else not v
|
|
480
|
+
|
|
481
|
+
# ------------------------------------------------------------ arithmetic
|
|
482
|
+
|
|
483
|
+
def _nums(self, nodes: list, env: Env, what: str) -> list[float] | None:
|
|
484
|
+
vals, missing = self._operands(nodes, env)
|
|
485
|
+
if missing:
|
|
486
|
+
return None
|
|
487
|
+
for v in vals:
|
|
488
|
+
if not is_number(v):
|
|
489
|
+
raise EvalError(f"{what} needs a number, got {describe(v)}")
|
|
490
|
+
return vals
|
|
491
|
+
|
|
492
|
+
def _add(self, nodes: list, env: Env) -> Any:
|
|
493
|
+
xs = self._nums(nodes, env, "+")
|
|
494
|
+
return MISSING if xs is None else neumaier_sum(xs)
|
|
495
|
+
|
|
496
|
+
def _mul(self, nodes: list, env: Env) -> Any:
|
|
497
|
+
xs = self._nums(nodes, env, "*")
|
|
498
|
+
if xs is None:
|
|
499
|
+
return MISSING
|
|
500
|
+
out = xs[0]
|
|
501
|
+
for x in xs[1:]:
|
|
502
|
+
out = out * x
|
|
503
|
+
return out
|
|
504
|
+
|
|
505
|
+
def _sub(self, nodes: list, env: Env) -> Any:
|
|
506
|
+
xs = self._nums(nodes, env, "-")
|
|
507
|
+
return MISSING if xs is None else xs[0] - xs[1]
|
|
508
|
+
|
|
509
|
+
def _div(self, nodes: list, env: Env) -> Any:
|
|
510
|
+
xs = self._nums(nodes, env, "/")
|
|
511
|
+
if xs is None:
|
|
512
|
+
return MISSING
|
|
513
|
+
if xs[1] == 0:
|
|
514
|
+
raise EvalError("division by zero")
|
|
515
|
+
return xs[0] / xs[1]
|
|
516
|
+
|
|
517
|
+
def _min(self, nodes: list, env: Env) -> Any:
|
|
518
|
+
xs = self._nums(nodes, env, "min")
|
|
519
|
+
return MISSING if xs is None else extreme_min(xs)
|
|
520
|
+
|
|
521
|
+
def _max(self, nodes: list, env: Env) -> Any:
|
|
522
|
+
xs = self._nums(nodes, env, "max")
|
|
523
|
+
return MISSING if xs is None else extreme_max(xs)
|
|
524
|
+
|
|
525
|
+
def _abs(self, node: Any, env: Env) -> Any:
|
|
526
|
+
xs = self._nums([node], env, "abs")
|
|
527
|
+
return MISSING if xs is None else abs(xs[0])
|
|
528
|
+
|
|
529
|
+
# ------------------------------------------------------------ membership, strings, shape
|
|
530
|
+
|
|
531
|
+
def _in(self, nodes: list, env: Env) -> Any:
|
|
532
|
+
(needle, hay), missing = self._operands(nodes, env)
|
|
533
|
+
if missing:
|
|
534
|
+
return MISSING
|
|
535
|
+
if type(hay) is not list:
|
|
536
|
+
raise EvalError(f"in needs a list on the right, got {describe(hay)}")
|
|
537
|
+
if needle is ABSENT:
|
|
538
|
+
return False
|
|
539
|
+
return any(equal(needle, h) for h in hay)
|
|
540
|
+
|
|
541
|
+
def _matches(self, nodes: list, env: Env) -> Any:
|
|
542
|
+
subject = self.eval(nodes[0], env)
|
|
543
|
+
if subject is MISSING:
|
|
544
|
+
return MISSING
|
|
545
|
+
if type(subject) is not str:
|
|
546
|
+
raise EvalError(f"matches needs a string, got {describe(subject)}")
|
|
547
|
+
return compile_pattern(nodes[1]).fullmatch(subject) is not None
|
|
548
|
+
|
|
549
|
+
def _len(self, node: Any, env: Env) -> Any:
|
|
550
|
+
v = self.eval(node, env)
|
|
551
|
+
if v is MISSING:
|
|
552
|
+
return MISSING
|
|
553
|
+
t = type(v)
|
|
554
|
+
if t is Selection:
|
|
555
|
+
n = float(len(v.records))
|
|
556
|
+
env.evidence.read(f"history.{v.label}.count", n)
|
|
557
|
+
return n
|
|
558
|
+
if t is str or t is list or t is dict:
|
|
559
|
+
return float(len(v))
|
|
560
|
+
raise EvalError(f"len needs a string, list or object, got {describe(v)}")
|
|
561
|
+
|
|
562
|
+
def _present(self, node: Any, env: Env) -> Any:
|
|
563
|
+
v = self.eval(node, env)
|
|
564
|
+
if v is MISSING:
|
|
565
|
+
return MISSING
|
|
566
|
+
return v is not ABSENT and v is not None
|
|
567
|
+
|
|
568
|
+
def _is(self, nodes: list, env: Env) -> Any:
|
|
569
|
+
v = self.eval(nodes[0], env)
|
|
570
|
+
if v is MISSING:
|
|
571
|
+
return MISSING
|
|
572
|
+
if v is ABSENT:
|
|
573
|
+
return False
|
|
574
|
+
return type_name(v) == nodes[1]
|
|
575
|
+
|
|
576
|
+
# ------------------------------------------------------------ quantifiers
|
|
577
|
+
|
|
578
|
+
def _quantify(self, nodes: list, env: Env, want: bool, what: str) -> Any:
|
|
579
|
+
items = self.eval(nodes[0], env)
|
|
580
|
+
if items is MISSING:
|
|
581
|
+
return MISSING
|
|
582
|
+
records = type(items) is Selection
|
|
583
|
+
if records:
|
|
584
|
+
items = items.records
|
|
585
|
+
elif type(items) is not list:
|
|
586
|
+
raise EvalError(f"{what} needs a list, got {describe(items)}")
|
|
587
|
+
saw_missing = False
|
|
588
|
+
saved, saved_kind = env.it, env.it_is_record
|
|
589
|
+
env.it_is_record = records
|
|
590
|
+
try:
|
|
591
|
+
for item in items:
|
|
592
|
+
env.it = item
|
|
593
|
+
v = self._bool(self.eval(nodes[1], env), what)
|
|
594
|
+
if v is MISSING:
|
|
595
|
+
saw_missing = True
|
|
596
|
+
elif v is want:
|
|
597
|
+
return want
|
|
598
|
+
finally:
|
|
599
|
+
env.it, env.it_is_record = saved, saved_kind
|
|
600
|
+
return MISSING if saw_missing else (not want)
|
|
601
|
+
|
|
602
|
+
def _all(self, nodes: list, env: Env) -> Any:
|
|
603
|
+
return self._quantify(nodes, env, False, "all")
|
|
604
|
+
|
|
605
|
+
def _any(self, nodes: list, env: Env) -> Any:
|
|
606
|
+
return self._quantify(nodes, env, True, "any")
|
|
607
|
+
|
|
608
|
+
# ------------------------------------------------------------ time, escape hatch
|
|
609
|
+
|
|
610
|
+
def _hour_utc(self, node: Any, env: Env) -> Any:
|
|
611
|
+
v = self.eval(node, env)
|
|
612
|
+
if v is MISSING:
|
|
613
|
+
return MISSING
|
|
614
|
+
if is_number(v):
|
|
615
|
+
h = hour_of_epoch(v)
|
|
616
|
+
if h is None:
|
|
617
|
+
raise EvalError(f"hour_utc value out of range, got {describe(v)}")
|
|
618
|
+
return float(h)
|
|
619
|
+
if type(v) is str:
|
|
620
|
+
h = hour_of_iso(v)
|
|
621
|
+
if h is None:
|
|
622
|
+
raise EvalError(f"hour_utc needs epoch seconds or an ISO-8601 time, got {describe(v)}")
|
|
623
|
+
return float(h)
|
|
624
|
+
raise EvalError(f"hour_utc needs epoch seconds or an ISO-8601 time, got {describe(v)}")
|
|
625
|
+
|
|
626
|
+
def _predicate(self, nodes: list, env: Env) -> Any:
|
|
627
|
+
name = nodes[0]
|
|
628
|
+
fn = self.predicates[name]
|
|
629
|
+
args, missing = self._operands(nodes[1:], env)
|
|
630
|
+
if missing:
|
|
631
|
+
return MISSING
|
|
632
|
+
try:
|
|
633
|
+
# The host sees None for an absent argument, never the evaluator's marker;
|
|
634
|
+
# its result is data like any other: plain JSON, or the predicate failed.
|
|
635
|
+
return to_json(fn(*[None if a is ABSENT else a for a in args]))
|
|
636
|
+
except Exception as exc: # noqa: BLE001 - host code; its failure is the rule's evaluation error
|
|
637
|
+
try:
|
|
638
|
+
message = str(exc)
|
|
639
|
+
except Exception: # noqa: BLE001
|
|
640
|
+
message = "unprintable error"
|
|
641
|
+
raise EvalError(f"predicate {name} failed: {message}") from exc
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def _is_it(node: Any) -> bool:
|
|
645
|
+
return type(node) is dict and len(node) == 1 and "it" in node
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def _uses_it(node: Any) -> bool:
|
|
649
|
+
if type(node) is dict:
|
|
650
|
+
return any(k == "it" or _uses_it(v) for k, v in node.items())
|
|
651
|
+
if type(node) is list:
|
|
652
|
+
return any(_uses_it(n) for n in node)
|
|
653
|
+
return False
|