aid-runtime-python 0.1.125__py3-none-any.whl → 0.1.127__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.
aid_runtime/__init__.py CHANGED
@@ -310,7 +310,7 @@ from aid_runtime.types import (
310
310
  )
311
311
 
312
312
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
313
- __version__ = "0.1.125"
313
+ __version__ = "0.1.127"
314
314
 
315
315
  __all__ = [
316
316
  "ANTHROPIC_VERSION",
@@ -55,6 +55,14 @@ from aid_runtime.retrieval.embedding import (
55
55
  embedder_for,
56
56
  estimate_tokens,
57
57
  )
58
+ from aid_runtime.retrieval.filters import (
59
+ FILTER_OPERATORS,
60
+ Filter,
61
+ compile_filters,
62
+ matches,
63
+ matches_all,
64
+ parse_filter,
65
+ )
58
66
  from aid_runtime.retrieval.gate import RetrievalGate
59
67
  from aid_runtime.retrieval.hybrid import (
60
68
  RankedId,
@@ -130,6 +138,7 @@ from aid_runtime.retrieval.types import (
130
138
 
131
139
  __all__ = [
132
140
  "DEFAULT_CANDIDATE_FACTOR",
141
+ "FILTER_OPERATORS",
133
142
  "FIXTURE_ENV",
134
143
  "BedrockEmbedder",
135
144
  "BedrockKnowledgeBaseClient",
@@ -148,6 +157,7 @@ __all__ = [
148
157
  "EmbeddingSpec",
149
158
  "FakeDeterministicEmbedder",
150
159
  "FileConnector",
160
+ "Filter",
151
161
  "FixedChunker",
152
162
  "FixtureKnowledgeBaseClient",
153
163
  "GeminiEmbedder",
@@ -205,6 +215,7 @@ __all__ = [
205
215
  "chunk_id_for",
206
216
  "chunker_for",
207
217
  "cite",
218
+ "compile_filters",
208
219
  "create_store",
209
220
  "embedder_for",
210
221
  "estimate_tokens",
@@ -213,7 +224,10 @@ __all__ = [
213
224
  "knowledge_base_env_id",
214
225
  "lexical_ranking",
215
226
  "lexical_score",
227
+ "matches",
228
+ "matches_all",
216
229
  "open_connector",
230
+ "parse_filter",
217
231
  "pinned_embedding",
218
232
  "reranker_for",
219
233
  "resolve_uri",
@@ -0,0 +1,165 @@
1
+ """Filter expressions over a chunk's identity and metadata.
2
+
3
+ The IR carries ``filters`` as strings, because the two hosted knowledge bases take
4
+ strings and a structured shape would have to be translated twice. This module pins
5
+ the grammar the *local* pipeline reads, and pins it narrowly: five comparison
6
+ operators, ANDed, no boolean algebra, no regular expressions.
7
+
8
+ The restriction is deliberate. A filter is a security boundary -- a tenant or
9
+ classification selector -- so it must be impossible to express one that silently
10
+ matches more than it says. Regex would make ``*=` a denial-of-service surface and
11
+ would not port to either hosted engine.
12
+
13
+ A mature library was considered and rejected. JMESPath (``jmespath``) is the closest
14
+ fit and exists in both Python and JavaScript, but its ``!=`` on an absent field is
15
+ true, which is the fail-open behaviour this module exists to prevent, and its grammar
16
+ is far larger than the five operators documented here. Wrapping it would mean writing
17
+ the validator and the absence rule by hand anyway, so the parser stays here where
18
+ both runtimes can be held to the same table.
19
+
20
+ Grammar::
21
+
22
+ filter := field op value
23
+ op := "==" | "!=" | "^=" (prefix) | "$=" (suffix) | "*=" (contains)
24
+ field := "doc_id" | "uri" | metadata key
25
+ value := bare token, or "..." / '...' quoted
26
+
27
+ Every entry in the list is ANDed. Evaluation is per chunk: a field the chunk does not
28
+ carry matches nothing, *including* under ``!=`` -- absence is not a value, and
29
+ treating it as one would widen a selector instead of narrowing it.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import re
35
+ from collections.abc import Sequence
36
+ from dataclasses import dataclass
37
+ from typing import Protocol
38
+
39
+ from aid_runtime.errors import ConfigurationError
40
+
41
+ __all__ = [
42
+ "FILTER_OPERATORS",
43
+ "Filter",
44
+ "compile_filters",
45
+ "matches",
46
+ "matches_all",
47
+ "metadata_fields",
48
+ "parse_filter",
49
+ ]
50
+
51
+ #: The operators the grammar admits, in the order a diagnostic lists them.
52
+ FILTER_OPERATORS: tuple[str, ...] = ("==", "!=", "^=", "$=", "*=")
53
+
54
+
55
+ class ChunkLike(Protocol):
56
+ """The slice of a chunk a filter observes.
57
+
58
+ Retrieval's ``Chunk`` satisfies this structurally. Naming the shape here rather
59
+ than importing it keeps this module free of a cycle back into ``retrieval.types``,
60
+ which imports :func:`metadata_fields` at module level.
61
+ """
62
+
63
+ doc_id: str
64
+ uri: str
65
+ metadata: dict[str, str]
66
+
67
+
68
+ _FIELD = r"[A-Za-z0-9_.\-]+"
69
+ _OPERATOR = r"==|!=|\^=|\$=|\*="
70
+ _EXPRESSION = re.compile(rf"^\s*({_FIELD})\s*({_OPERATOR})\s*(.*)", re.DOTALL)
71
+
72
+ #: Fields resolved from the chunk itself, never from ``chunk.metadata``.
73
+ _RESERVED_FIELDS = frozenset({"doc_id", "uri"})
74
+
75
+
76
+ @dataclass(frozen=True, slots=True)
77
+ class Filter:
78
+ """One parsed comparison. ``value`` is already unquoted."""
79
+
80
+ field: str
81
+ operator: str
82
+ value: str
83
+
84
+
85
+ def parse_filter(expression: str) -> Filter:
86
+ """Parse one expression, or explain precisely what is wrong with it.
87
+
88
+ An unsupported operator is reported against the operator itself rather than as a
89
+ generic "invalid expression": the five spellings are short enough to list, and a
90
+ user who wrote ``=`` instead of ``==`` should be told so.
91
+ """
92
+ if not isinstance(expression, str):
93
+ raise ConfigurationError(
94
+ f"a filter expression must be a string, not {type(expression).__name__}"
95
+ )
96
+ match = _EXPRESSION.match(expression)
97
+ if match is None:
98
+ raise ConfigurationError(
99
+ f"filter expression {expression!r} is not '<field> <op> <value>'; the operators are "
100
+ + ", ".join(FILTER_OPERATORS)
101
+ )
102
+ field, operator, raw = match.groups()
103
+ value = _unquote(raw.strip(), expression)
104
+ if not value:
105
+ raise ConfigurationError(
106
+ f"filter expression {expression!r} names field {field!r} with an empty value"
107
+ )
108
+ return Filter(field=field, operator=operator, value=value)
109
+
110
+
111
+ def _unquote(raw: str, expression: str) -> str:
112
+ """Strip one matching pair of quotes, and nothing else."""
113
+ if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in {'"', "'"}:
114
+ return raw[1:-1]
115
+ if raw[:1] in {'"', "'"}:
116
+ raise ConfigurationError(
117
+ f"filter expression {expression!r} starts a quoted value but does not close it"
118
+ )
119
+ return raw
120
+
121
+
122
+ def compile_filters(expressions: Sequence[str]) -> tuple[Filter, ...]:
123
+ """Parse every expression once, at a point where a mistake is still local."""
124
+ return tuple(parse_filter(expression) for expression in expressions)
125
+
126
+
127
+ def metadata_fields(expressions: Sequence[str]) -> tuple[str, ...]:
128
+ """The metadata keys ``expressions`` read, in declaration order, without repeats.
129
+
130
+ A chunk only carries the metadata ``chunking.keepMetadata`` names, so a filter on
131
+ a key that is not kept would match nothing. The binder unions this into
132
+ ``keepMetadata`` rather than asking a user to remember the same key twice.
133
+ """
134
+ fields = (parsed.field for parsed in compile_filters(expressions))
135
+ return tuple(dict.fromkeys(field for field in fields if field not in _RESERVED_FIELDS))
136
+
137
+
138
+ def matches(chunk: ChunkLike, condition: Filter) -> bool:
139
+ """Whether ``chunk`` satisfies one comparison.
140
+
141
+ A missing field is a non-match for every operator. ``!=`` therefore means "this
142
+ field is present and differs", not "this field is absent or differs".
143
+ """
144
+ if condition.field == "doc_id":
145
+ actual: str | None = chunk.doc_id
146
+ elif condition.field == "uri":
147
+ actual = chunk.uri
148
+ else:
149
+ actual = chunk.metadata.get(condition.field)
150
+ if actual is None:
151
+ return False
152
+ if condition.operator == "==":
153
+ return actual == condition.value
154
+ if condition.operator == "!=":
155
+ return actual != condition.value
156
+ if condition.operator == "^=":
157
+ return actual.startswith(condition.value)
158
+ if condition.operator == "$=":
159
+ return actual.endswith(condition.value)
160
+ return condition.value in actual
161
+
162
+
163
+ def matches_all(chunk: ChunkLike, filters: Sequence[Filter]) -> bool:
164
+ """Whether ``chunk`` satisfies every filter. An empty list admits everything."""
165
+ return all(matches(chunk, condition) for condition in filters)
@@ -41,6 +41,7 @@ from aid_runtime.retrieval.chunking import chunker_for
41
41
  from aid_runtime.retrieval.citations import RetrievalResult, RetrievedItem, cite
42
42
  from aid_runtime.retrieval.connectors import Connector, SourceDocument, open_connector
43
43
  from aid_runtime.retrieval.embedding import Embedder, EmbeddingBatch, embedder_for
44
+ from aid_runtime.retrieval.filters import Filter, compile_filters, matches_all
44
45
  from aid_runtime.retrieval.hybrid import fuse, lexical_ranking
45
46
  from aid_runtime.retrieval.knowledge_base import KnowledgeBaseClient, knowledge_base_client_for
46
47
  from aid_runtime.retrieval.rerank import Reranker, reranker_for
@@ -154,6 +155,9 @@ class Retriever:
154
155
  self._base_dir = None
155
156
  return
156
157
  self._knowledge_base_client = None
158
+ # Parsed once here so a malformed selector fails at construction, and so the
159
+ # per-query path never re-parses. A syntax error names the grammar.
160
+ self._filters = compile_filters(binding.filters or ())
157
161
  self._embedder = embedder or embedder_for(binding.embedding)
158
162
  self._store = store or create_store(
159
163
  binding.store_kind,
@@ -260,10 +264,11 @@ class Retriever:
260
264
 
261
265
  batch, _ = await self._embed((query,))
262
266
  vector = batch.vectors[0]
263
- candidates = wanted * self._candidate_factor
264
267
  local = self._local
265
- hits = await self.store.search(vector, top_k=candidates, metric=local.index.metric)
266
- ranked = await self._rank(query, hits, candidates)
268
+ filters = self._filters
269
+ hits = await self._search_vector(vector, wanted, local, filters)
270
+ candidates = max(len(hits), wanted * self._candidate_factor)
271
+ ranked = await self._rank(query, hits, candidates, filters)
267
272
  items = _to_items(ranked)
268
273
  if self._reranker is not None:
269
274
  top_n = local.rerank.top_n if local.rerank is not None else wanted
@@ -445,22 +450,53 @@ class Retriever:
445
450
  )
446
451
  return embedded, cost
447
452
 
453
+ async def _search_vector(
454
+ self,
455
+ vector: Sequence[float],
456
+ wanted: int,
457
+ local: RetrieverBinding,
458
+ filters: Sequence[Filter],
459
+ ) -> tuple[SearchHit, ...]:
460
+ """Vector search, widened until ``wanted`` passages survive the filters.
461
+
462
+ A store can only apply ``top_k``, so a selective filter has to be satisfied by
463
+ looking deeper. The limit doubles until enough passages match or the store
464
+ returns fewer rows than were asked for -- the latter is the only signal that
465
+ the corpus is exhausted. With no filters this is one search at the historical
466
+ candidate width, so the unfiltered path is byte-for-byte unchanged.
467
+ """
468
+ limit = max(wanted * self._candidate_factor, 1)
469
+ while True:
470
+ hits = await self.store.search(vector, top_k=limit, metric=local.index.metric)
471
+ kept = tuple(hit for hit in hits if matches_all(hit.record.chunk, filters))
472
+ if len(kept) >= wanted or len(hits) < limit:
473
+ return kept
474
+ limit *= 2
475
+
448
476
  async def _rank(
449
477
  self,
450
478
  query: str,
451
479
  hits: Sequence[SearchHit],
452
480
  candidates: int,
481
+ filters: Sequence[Filter] = (),
453
482
  ) -> tuple[ScoredChunk, ...]:
454
483
  """The candidate ranking: vector only, or fused with a lexical ranking.
455
484
 
456
485
  Fusion is skipped when ``index.hybrid`` is false, and that is the whole
457
486
  meaning of the flag -- not "use a different metric", but "do not consult the
458
487
  lexical ranking at all".
488
+
489
+ The lexical half reads the stored corpus rather than the vector hits, so it is
490
+ filtered too. Ranking the whole corpus and filtering afterwards would let a
491
+ passage outside the selector re-enter through BM25, which is the one way a
492
+ filter could silently match more than it says.
459
493
  """
460
494
  if not self._local.index.hybrid:
461
495
  return tuple(ScoredChunk(chunk=hit.record.chunk, score=hit.score) for hit in hits)
462
496
 
463
497
  corpus = await self.store.corpus()
498
+ if filters:
499
+ corpus = tuple(record for record in corpus if matches_all(record.chunk, filters))
464
500
  by_id: dict[str, StoreRecord] = {record.chunk.chunk_id: record for record in corpus}
465
501
  for hit in hits:
466
502
  by_id.setdefault(hit.record.chunk.chunk_id, hit.record)
@@ -29,6 +29,7 @@ from typing import Any, Literal
29
29
  from pydantic import BaseModel, ConfigDict, Field
30
30
 
31
31
  from aid_runtime.errors import ConfigurationError, FeatureDeferredError
32
+ from aid_runtime.retrieval.filters import metadata_fields
32
33
  from aid_runtime.types import CostProfile
33
34
 
34
35
  __all__ = [
@@ -302,6 +303,7 @@ class RetrieverBinding(BaseModel):
302
303
  index: IndexSpec
303
304
  top_k: int = Field(gt=0)
304
305
  rerank: RerankSpec | None = None
306
+ filters: tuple[str, ...] = ()
305
307
  refresh_mode: RefreshMode = RefreshMode.FULL
306
308
  traits: tuple[str, ...] = ()
307
309
 
@@ -525,6 +527,10 @@ def binding_from_spec(
525
527
  ``store`` names a *stores entry id*. Both are checked here rather than
526
528
  trusted, because a mistyped reference in generated code would otherwise
527
529
  surface as an empty or mis-scored corpus far from its cause.
530
+
531
+ A declared filter also widens ``chunking.keepMetadata``: a chunk carries only the
532
+ metadata that field names, so filtering on a key it omits would match nothing. The
533
+ union is done here so the spec does not have to state the same key twice.
528
534
  """
529
535
  if spec.embed_model != embedding.id:
530
536
  raise ConfigurationError(
@@ -535,13 +541,13 @@ def binding_from_spec(
535
541
  raise ConfigurationError(
536
542
  f"retriever {spec.id!r} names store {spec.store!r} but store {store.id!r} was supplied"
537
543
  )
538
- if spec.filters:
539
- # The spec validator already refuses filters; the runtime checks too,
540
- # because generated code is reachable without the validator having run.
541
- raise FeatureDeferredError(
542
- f"retriever {spec.id!r} declares filters, which spec v0.1 does not implement: a "
543
- "filter would have to be pushed into every store adapter's query"
544
- )
544
+ filters = tuple(spec.filters or ())
545
+ chunking = spec.chunking
546
+ if filters:
547
+ # Parse now: a malformed selector is a configuration fault, and generated
548
+ # code is reachable without the spec validator having run.
549
+ keep = tuple(dict.fromkeys((*chunking.keep_metadata, *metadata_fields(filters))))
550
+ chunking = chunking.model_copy(update={"keep_metadata": keep})
545
551
  pinned = pinned_embedding(embedding, alias=spec.embed_model, dimensions=dimensions)
546
552
  if store.dimensions is not None and store.dimensions != pinned.dimensions:
547
553
  raise ConfigurationError(
@@ -552,7 +558,7 @@ def binding_from_spec(
552
558
  return RetrieverBinding(
553
559
  retriever_id=spec.id,
554
560
  source=spec.source,
555
- chunking=spec.chunking,
561
+ chunking=chunking,
556
562
  embed_model=spec.embed_model,
557
563
  embedding=pinned,
558
564
  store=spec.store,
@@ -561,6 +567,7 @@ def binding_from_spec(
561
567
  index=spec.index,
562
568
  top_k=spec.top_k,
563
569
  rerank=spec.rerank,
570
+ filters=filters,
564
571
  refresh_mode=spec.refresh.mode,
565
572
  traits=spec.traits,
566
573
  )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.125
3
+ Version: 0.1.127
4
4
  Summary: The AID Framework Python runtime: model gateway with pinning and cost budgets, prompt registry, tool executor, OTel GenAI tracing, plain-async pipeline, and an eval harness that gates on statistical regression against a stored baseline.
5
5
  Author: The AID Framework authors
6
6
  License-Expression: Apache-2.0
@@ -1,4 +1,4 @@
1
- aid_runtime/__init__.py,sha256=_EfYBqiBKQS54Tp19FbJyUrRLWM2Khenw0uXYgVXSPE,13238
1
+ aid_runtime/__init__.py,sha256=LOkxLAoCaa0CvE6hWIQRwzzYkk0nU3AV2gMggKax2vM,13238
2
2
  aid_runtime/cache.py,sha256=jhw_EBd9dfWEUzYeibOvIkVBqqiLUjqF5WKEPz9GkhE,6836
3
3
  aid_runtime/concurrency.py,sha256=z0tFQHw35ttFLKfazGBjCMPOLQOnUotE_OPpvR1piH4,2829
4
4
  aid_runtime/control.py,sha256=y6wPn0fqYJv0nVSsjzpzfiaq1Y7zBoMxCpdrEuqkfvg,17529
@@ -41,21 +41,22 @@ aid_runtime/providers/gemini.py,sha256=gM4Kvgz6lnFbHgYYhyVCBTFTcGAKfiNuj7lS1XSld
41
41
  aid_runtime/providers/gemini_wire.py,sha256=ZwIiYuAVihszE0c90-uAbSn6_hdMa2Md4asySIYeQTw,13032
42
42
  aid_runtime/providers/http.py,sha256=c5DLmX1FqtAUO01MqDf0m82x8zHD480LyL-QtTrxnn4,13168
43
43
  aid_runtime/providers/vertex.py,sha256=XdwPuPw2Ce5CGuoEyzY5jVpqtKeTXWOvY_9WegxheEk,9341
44
- aid_runtime/retrieval/__init__.py,sha256=Hwn-Lh7EMJSfYaFsZ4eACm2GI-64ObeZT2Pkzuh_ku0,5893
44
+ aid_runtime/retrieval/__init__.py,sha256=ATZNNT_iQmT_5tke1ARzpscDU0ClXTT7HCKpTXUBuvY,6157
45
45
  aid_runtime/retrieval/chunking.py,sha256=GMJvY1GoIua-FkpCH1S5qNmUrWSaSbl6sBJPCrSDAg4,8296
46
46
  aid_runtime/retrieval/citations.py,sha256=UL9fsxLTzzO0n8tEW3X2O5erJ0hrk08NYMkZ9Pk8Jdg,4287
47
47
  aid_runtime/retrieval/connectors.py,sha256=JNEwq6S8zKX1GdlWe4Gn2Rdon87DWXlG_WNQfZTlN34,4744
48
48
  aid_runtime/retrieval/embedding.py,sha256=Ea7zOZnnX2oGdnKi2AcecxYZkn9KirgJO_xOf7iDDI8,24775
49
+ aid_runtime/retrieval/filters.py,sha256=mEa2Ok20VG5Fxe5GWYAxvhl4HK4HV6FHZ5r0wnr-ZLI,6240
49
50
  aid_runtime/retrieval/gate.py,sha256=3avH1Gwp7iv7mMOskmNbk70Yq85tXwJrKVrQAKKI4Js,4840
50
51
  aid_runtime/retrieval/hybrid.py,sha256=-GIBeI3njT5uaEvSeq2t151Zlv2yOPHOPje4TJLNVyU,5804
51
52
  aid_runtime/retrieval/knowledge_base.py,sha256=xNFTdIdIMvS7Ij9y4niXGrgxAhtsmWe2kOVyR_j9AU4,28360
52
53
  aid_runtime/retrieval/metrics.py,sha256=LN36BIXzpbhkG9grzE0q5wncgXt_Y85-b5jGJ038-3Y,7904
53
54
  aid_runtime/retrieval/pgvector.py,sha256=tahRZQr8xQp7tZ5spgTzlEEMv2HpSx3OLPKjdq_vz0c,11015
54
55
  aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJMc,5114
55
- aid_runtime/retrieval/retriever.py,sha256=t6xhku1GCzE95kWXAgbdJyU3ATGANm9K7XX6sMDG_uQ,21363
56
+ aid_runtime/retrieval/retriever.py,sha256=5pO4muNPm-rn5jQZNJwkk8dwNkQKoaywuCX-tArEj3o,23241
56
57
  aid_runtime/retrieval/stores.py,sha256=mG261rUHZIzB7niiTj_DuUzcNMOd4QYENk5ArgI1iBo,6840
57
- aid_runtime/retrieval/types.py,sha256=eNNIyLYMnfxcPyACoufEMCzSoedPmBM-xY4QrX1ueNM,20042
58
- aid_runtime_python-0.1.125.dist-info/METADATA,sha256=HJBKgvN1FG7r-dUtrAFI6DBFayK4eMYUvE5QVqu63cM,16983
59
- aid_runtime_python-0.1.125.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
60
- aid_runtime_python-0.1.125.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
61
- aid_runtime_python-0.1.125.dist-info/RECORD,,
58
+ aid_runtime/retrieval/types.py,sha256=zZpSY55jqNdZwbnMdy3mrOLMvy6bBpz6TlEo2WIV1zM,20404
59
+ aid_runtime_python-0.1.127.dist-info/METADATA,sha256=-bX-4EOch09Fep6f8HPJLKjgyWgA8XOzfFrpWxAfheA,16983
60
+ aid_runtime_python-0.1.127.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
61
+ aid_runtime_python-0.1.127.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
62
+ aid_runtime_python-0.1.127.dist-info/RECORD,,