aid-runtime-python 0.1.124__tar.gz → 0.1.126__tar.gz

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.
Files changed (115) hide show
  1. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/PKG-INFO +2 -2
  2. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/README.md +1 -1
  3. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/pyproject.toml +1 -1
  4. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/__init__.py +1 -1
  5. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/retrieval/__init__.py +14 -0
  6. aid_runtime_python-0.1.126/src/aid_runtime/retrieval/filters.py +165 -0
  7. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/retrieval/pgvector.py +21 -0
  8. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/retrieval/retriever.py +74 -12
  9. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/retrieval/stores.py +25 -0
  10. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/retrieval/types.py +21 -9
  11. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime_python.egg-info/PKG-INFO +2 -2
  12. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime_python.egg-info/SOURCES.txt +2 -0
  13. aid_runtime_python-0.1.126/tests/test_retrieval_filters.py +261 -0
  14. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_retrieval_gate.py +85 -6
  15. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_retrieval_stores.py +56 -2
  16. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_retrieval_types.py +40 -6
  17. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/setup.cfg +0 -0
  18. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/agents/__init__.py +0 -0
  19. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/agents/chat_model.py +0 -0
  20. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/agents/deep_agents.py +0 -0
  21. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/agents/engine.py +0 -0
  22. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/agents/guardrails.py +0 -0
  23. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/agents/ir.py +0 -0
  24. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/agents/loop.py +0 -0
  25. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/agents/managed.py +0 -0
  26. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/agents/memory.py +0 -0
  27. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/agents/policy.py +0 -0
  28. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/agents/state.py +0 -0
  29. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/cache.py +0 -0
  30. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/concurrency.py +0 -0
  31. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/control.py +0 -0
  32. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/cost.py +0 -0
  33. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/decisions.py +0 -0
  34. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/errors.py +0 -0
  35. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/evals/__init__.py +0 -0
  36. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/evals/dataset.py +0 -0
  37. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/evals/gate.py +0 -0
  38. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/evals/metrics.py +0 -0
  39. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/evals/predicate.py +0 -0
  40. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/evals/runner.py +0 -0
  41. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/gateway.py +0 -0
  42. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/local_trace.py +0 -0
  43. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/pipeline.py +0 -0
  44. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/prompts.py +0 -0
  45. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/providers/__init__.py +0 -0
  46. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/providers/anthropic.py +0 -0
  47. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/providers/base.py +0 -0
  48. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/providers/bedrock.py +0 -0
  49. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/providers/fake.py +0 -0
  50. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/providers/gemini.py +0 -0
  51. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/providers/gemini_wire.py +0 -0
  52. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/providers/http.py +0 -0
  53. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/providers/vertex.py +0 -0
  54. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/py.typed +0 -0
  55. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/retrieval/chunking.py +0 -0
  56. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/retrieval/citations.py +0 -0
  57. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/retrieval/connectors.py +0 -0
  58. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/retrieval/embedding.py +0 -0
  59. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/retrieval/gate.py +0 -0
  60. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/retrieval/hybrid.py +0 -0
  61. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/retrieval/knowledge_base.py +0 -0
  62. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/retrieval/metrics.py +0 -0
  63. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/retrieval/rerank.py +0 -0
  64. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/steps.py +0 -0
  65. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/structured.py +0 -0
  66. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/tools.py +0 -0
  67. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/tracing.py +0 -0
  68. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime/types.py +0 -0
  69. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime_python.egg-info/dependency_links.txt +0 -0
  70. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime_python.egg-info/requires.txt +0 -0
  71. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/src/aid_runtime_python.egg-info/top_level.txt +0 -0
  72. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_agents_budget.py +0 -0
  73. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_agents_deep_agents.py +0 -0
  74. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_agents_hitl.py +0 -0
  75. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_agents_loop.py +0 -0
  76. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_agents_memory.py +0 -0
  77. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_anthropic_provider.py +0 -0
  78. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_bedrock_provider.py +0 -0
  79. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_cache.py +0 -0
  80. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_concurrency.py +0 -0
  81. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_control.py +0 -0
  82. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_cost.py +0 -0
  83. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_dataset.py +0 -0
  84. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_decisions.py +0 -0
  85. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_evals.py +0 -0
  86. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_evals_assert_gate.py +0 -0
  87. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_evals_decision.py +0 -0
  88. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_evals_gate.py +0 -0
  89. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_evals_predicate.py +0 -0
  90. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_gateway.py +0 -0
  91. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_gemini_provider.py +0 -0
  92. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_guardrails.py +0 -0
  93. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_guardrails_managed.py +0 -0
  94. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_guardrails_model_armor.py +0 -0
  95. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_http_provider.py +0 -0
  96. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_local_trace.py +0 -0
  97. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_package.py +0 -0
  98. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_pipeline.py +0 -0
  99. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_prompts.py +0 -0
  100. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_retrieval_chunking.py +0 -0
  101. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_retrieval_citations.py +0 -0
  102. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_retrieval_connectors.py +0 -0
  103. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_retrieval_embedding.py +0 -0
  104. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_retrieval_hybrid.py +0 -0
  105. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_retrieval_knowledge_base.py +0 -0
  106. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_retrieval_metrics.py +0 -0
  107. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_retrieval_rerank.py +0 -0
  108. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_steps.py +0 -0
  109. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_streaming.py +0 -0
  110. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_structured.py +0 -0
  111. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_tool_permissions.py +0 -0
  112. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_tools.py +0 -0
  113. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_tracing.py +0 -0
  114. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_types.py +0 -0
  115. {aid_runtime_python-0.1.124 → aid_runtime_python-0.1.126}/tests/test_vertex_provider.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.124
3
+ Version: 0.1.126
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
@@ -273,7 +273,7 @@ These are refused explicitly rather than approximated — each raises `FeatureDe
273
273
 
274
274
  - `ModelGateway.stream` — the transport is request/response only, and no provider advertises
275
275
  `Capability.STREAMING`.
276
- - Retrieval: non-file sources, `semantic` chunking, `incremental` refresh, retriever `filters`, a hosted
276
+ - Retrieval: non-file sources, `semantic` chunking, retriever `filters`, a hosted
277
277
  reranker, and the `qdrant` / `pinecone` / `weaviate` / `custom` store kinds.
278
278
  - Escalation routing and third-party orchestration frameworks.
279
279
 
@@ -239,7 +239,7 @@ These are refused explicitly rather than approximated — each raises `FeatureDe
239
239
 
240
240
  - `ModelGateway.stream` — the transport is request/response only, and no provider advertises
241
241
  `Capability.STREAMING`.
242
- - Retrieval: non-file sources, `semantic` chunking, `incremental` refresh, retriever `filters`, a hosted
242
+ - Retrieval: non-file sources, `semantic` chunking, retriever `filters`, a hosted
243
243
  reranker, and the `qdrant` / `pinecone` / `weaviate` / `custom` store kinds.
244
244
  - Escalation routing and third-party orchestration frameworks.
245
245
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "aid-runtime-python"
7
- version = "0.1.124"
7
+ version = "0.1.126"
8
8
  description = "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."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -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.124"
313
+ __version__ = "0.1.126"
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)
@@ -77,6 +77,10 @@ _CORPUS = (
77
77
  "SELECT chunk_id, doc_id, uri, chunk_index, start_offset, end_offset, body, metadata, "
78
78
  "embedding FROM aid_chunks ORDER BY chunk_id"
79
79
  )
80
+ _CHUNK_IDS = "SELECT chunk_id FROM aid_chunks ORDER BY chunk_id"
81
+ # `= ANY(%(chunk_ids)s)` binds a Python list as one array parameter, so a reconciliation
82
+ # that names thousands of stale chunks still sends one statement rather than one per id.
83
+ _DELETE = "DELETE FROM aid_chunks WHERE chunk_id = ANY(%(chunk_ids)s)"
80
84
  # `<=>` is cosine distance, `<#>` is negative inner product and `<->` is L2 distance.
81
85
  # Each is rewritten into "higher is better" so callers see one orientation, matching
82
86
  # `stores.similarity`. The tie-break on `chunk_id` matches the in-memory adapter too:
@@ -212,6 +216,23 @@ class PgVectorStore:
212
216
  rows = await cursor.fetchall()
213
217
  return tuple(self._record(row) for row in rows)
214
218
 
219
+ async def chunk_ids(self) -> tuple[str, ...]:
220
+ connection = await self._connect()
221
+ async with connection.cursor() as cursor:
222
+ await cursor.execute(_CHUNK_IDS)
223
+ rows = await cursor.fetchall()
224
+ return tuple(row[0] for row in rows)
225
+
226
+ async def delete(self, chunk_ids: Sequence[str]) -> int:
227
+ if not chunk_ids:
228
+ return 0
229
+ connection = await self._connect()
230
+ async with connection.cursor() as cursor:
231
+ await cursor.execute(_DELETE, {"chunk_ids": list(chunk_ids)})
232
+ removed = int(cursor.rowcount)
233
+ await connection.commit()
234
+ return max(removed, 0)
235
+
215
236
  async def aclose(self) -> None:
216
237
  if self._closed:
217
238
  return
@@ -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
@@ -78,6 +79,12 @@ class IngestReport(BaseModel):
78
79
  ingests of identical input compare equal without depending on the order the
79
80
  filesystem happened to yield. ``cost_usd`` is what *this* ingest charged, not the
80
81
  ledger's running total, so ingesting twice reads as two separate spends.
82
+
83
+ ``written`` counts chunks upserted and ``reused`` counts chunks an incremental
84
+ ingest found already stored and therefore did not embed; ``written + reused`` is
85
+ ``chunks``. ``removed`` counts chunks deleted because their document no longer
86
+ yields them. All three are zero-or-more, and all but ``written`` are zero for a
87
+ ``full`` refresh, which never reads the index and never deletes from it.
81
88
  """
82
89
 
83
90
  model_config = ConfigDict(frozen=True, extra="forbid")
@@ -89,6 +96,8 @@ class IngestReport(BaseModel):
89
96
  tokens: int = Field(ge=0)
90
97
  cost_usd: float = Field(ge=0.0)
91
98
  chunk_ids: tuple[str, ...]
99
+ reused: int = Field(default=0, ge=0)
100
+ removed: int = Field(default=0, ge=0)
92
101
 
93
102
  @property
94
103
  def is_empty(self) -> bool:
@@ -145,13 +154,10 @@ class Retriever:
145
154
  self._connector = None
146
155
  self._base_dir = None
147
156
  return
148
- if binding.refresh_mode is not RefreshMode.FULL:
149
- raise FeatureDeferredError(
150
- f"refresh mode {binding.refresh_mode.value!r} is declared but not implemented: "
151
- "spec v0.1 reindexes the whole source, and incremental refresh needs change "
152
- "detection the runtime does not have"
153
- )
154
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 ())
155
161
  self._embedder = embedder or embedder_for(binding.embedding)
156
162
  self._store = store or create_store(
157
163
  binding.store_kind,
@@ -185,6 +191,18 @@ class Retriever:
185
191
  upserts on them, so ingesting the same input twice replaces rather than
186
192
  duplicates. Re-ingesting is therefore a legitimate way to refresh a corpus.
187
193
 
194
+ ``refresh.mode`` decides what the second run redoes. ``full`` -- the default --
195
+ embeds and upserts every chunk and never reads or deletes from the index, so
196
+ dropping a document from the source leaves its vectors behind. ``incremental``
197
+ instead reconciles the index with the source: a chunk the store already holds
198
+ keeps its vector, a stored chunk the source no longer yields is deleted, and
199
+ only new chunks are embedded.
200
+
201
+ Incremental therefore treats what it is given as the *whole* corpus, whether
202
+ that came from the connector or from an explicit ``documents`` argument. Passing
203
+ a subset of the corpus in incremental mode deletes the rest, exactly as narrowing
204
+ the source glob would; the mode is a reconciliation, not a merge.
205
+
188
206
  Refused for a managed retriever. The engine ingests from its own data source, so
189
207
  a local ingest would write vectors the retriever never reads -- work that costs
190
208
  money and changes nothing, which is the worst kind of silent success.
@@ -195,16 +213,26 @@ class Retriever:
195
213
  "which ingests from its data source inside the engine; there is no local "
196
214
  "index to fill, and writing one would be read by nothing"
197
215
  )
198
- source_documents = tuple(documents) if documents is not None else await self._read_source()
199
216
  local = self._local
217
+ incremental = local.refresh_mode is RefreshMode.INCREMENTAL
218
+ source_documents = tuple(documents) if documents is not None else await self._read_source()
200
219
  chunker = chunker_for(local.chunking)
201
220
  chunks = [chunk for document in source_documents for chunk in chunker.chunk(document)]
202
221
 
222
+ to_embed = chunks
223
+ removed = 0
224
+ if incremental:
225
+ stored = set(await self.store.chunk_ids())
226
+ current = {chunk.chunk_id for chunk in chunks}
227
+ if stale := sorted(stored - current):
228
+ removed = await self.store.delete(stale)
229
+ to_embed = [chunk for chunk in chunks if chunk.chunk_id not in stored]
230
+
203
231
  records: list[StoreRecord] = []
204
232
  tokens = 0
205
233
  cost = 0.0
206
- for start in range(0, len(chunks), _BATCH_SIZE):
207
- batch = chunks[start : start + _BATCH_SIZE]
234
+ for start in range(0, len(to_embed), _BATCH_SIZE):
235
+ batch = to_embed[start : start + _BATCH_SIZE]
208
236
  embedded, batch_cost = await self._embed(tuple(chunk.text for chunk in batch))
209
237
  tokens += embedded.usage.input_tokens
210
238
  cost += batch_cost
@@ -219,6 +247,8 @@ class Retriever:
219
247
  documents=len(source_documents),
220
248
  chunks=len(chunks),
221
249
  written=written,
250
+ reused=len(chunks) - len(to_embed),
251
+ removed=removed,
222
252
  tokens=tokens,
223
253
  cost_usd=cost,
224
254
  chunk_ids=tuple(sorted(chunk.chunk_id for chunk in chunks)),
@@ -234,10 +264,11 @@ class Retriever:
234
264
 
235
265
  batch, _ = await self._embed((query,))
236
266
  vector = batch.vectors[0]
237
- candidates = wanted * self._candidate_factor
238
267
  local = self._local
239
- hits = await self.store.search(vector, top_k=candidates, metric=local.index.metric)
240
- 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)
241
272
  items = _to_items(ranked)
242
273
  if self._reranker is not None:
243
274
  top_n = local.rerank.top_n if local.rerank is not None else wanted
@@ -419,22 +450,53 @@ class Retriever:
419
450
  )
420
451
  return embedded, cost
421
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
+
422
476
  async def _rank(
423
477
  self,
424
478
  query: str,
425
479
  hits: Sequence[SearchHit],
426
480
  candidates: int,
481
+ filters: Sequence[Filter] = (),
427
482
  ) -> tuple[ScoredChunk, ...]:
428
483
  """The candidate ranking: vector only, or fused with a lexical ranking.
429
484
 
430
485
  Fusion is skipped when ``index.hybrid`` is false, and that is the whole
431
486
  meaning of the flag -- not "use a different metric", but "do not consult the
432
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.
433
493
  """
434
494
  if not self._local.index.hybrid:
435
495
  return tuple(ScoredChunk(chunk=hit.record.chunk, score=hit.score) for hit in hits)
436
496
 
437
497
  corpus = await self.store.corpus()
498
+ if filters:
499
+ corpus = tuple(record for record in corpus if matches_all(record.chunk, filters))
438
500
  by_id: dict[str, StoreRecord] = {record.chunk.chunk_id: record for record in corpus}
439
501
  for hit in hits:
440
502
  by_id.setdefault(hit.record.chunk.chunk_id, hit.record)
@@ -92,6 +92,21 @@ class VectorStore(Protocol):
92
92
  """
93
93
  ...
94
94
 
95
+ async def chunk_ids(self) -> tuple[str, ...]:
96
+ """Every stored chunk id, sorted.
97
+
98
+ Separate from :meth:`corpus` because an incremental ingest needs only
99
+ identity: it compares this set with the ids the source currently yields, and
100
+ fetching every vector to learn a key would cost what the mode exists to save.
101
+ """
102
+
103
+ async def delete(self, chunk_ids: Sequence[str]) -> int:
104
+ """Remove records by ``chunk_id``. Returns the number actually removed.
105
+
106
+ Deleting an absent id is not an error -- a caller reconciling an index with a
107
+ source may name a chunk another run already removed.
108
+ """
109
+
95
110
  async def aclose(self) -> None: ...
96
111
 
97
112
 
@@ -134,6 +149,16 @@ class InMemoryVectorStore:
134
149
  async def corpus(self) -> tuple[StoreRecord, ...]:
135
150
  return tuple(self._records[chunk_id] for chunk_id in sorted(self._records))
136
151
 
152
+ async def chunk_ids(self) -> tuple[str, ...]:
153
+ return tuple(sorted(self._records))
154
+
155
+ async def delete(self, chunk_ids: Sequence[str]) -> int:
156
+ removed = 0
157
+ for chunk_id in chunk_ids:
158
+ if self._records.pop(chunk_id, None) is not None:
159
+ removed += 1
160
+ return removed
161
+
137
162
  async def aclose(self) -> None:
138
163
  self._closed = True
139
164
 
@@ -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__ = [
@@ -119,7 +120,12 @@ class StoreKind(StrEnum):
119
120
 
120
121
 
121
122
  class RefreshMode(StrEnum):
122
- """``retriever.refresh.mode``. Only ``FULL`` is implemented."""
123
+ """``retriever.refresh.mode``.
124
+
125
+ ``FULL`` re-embeds the whole source every run. ``INCREMENTAL`` reconciles the index
126
+ with the source: unchanged chunks keep their vectors, stale ones are deleted, and
127
+ only new ones are embedded.
128
+ """
123
129
 
124
130
  FULL = "full"
125
131
  INCREMENTAL = "incremental"
@@ -297,6 +303,7 @@ class RetrieverBinding(BaseModel):
297
303
  index: IndexSpec
298
304
  top_k: int = Field(gt=0)
299
305
  rerank: RerankSpec | None = None
306
+ filters: tuple[str, ...] = ()
300
307
  refresh_mode: RefreshMode = RefreshMode.FULL
301
308
  traits: tuple[str, ...] = ()
302
309
 
@@ -520,6 +527,10 @@ def binding_from_spec(
520
527
  ``store`` names a *stores entry id*. Both are checked here rather than
521
528
  trusted, because a mistyped reference in generated code would otherwise
522
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.
523
534
  """
524
535
  if spec.embed_model != embedding.id:
525
536
  raise ConfigurationError(
@@ -530,13 +541,13 @@ def binding_from_spec(
530
541
  raise ConfigurationError(
531
542
  f"retriever {spec.id!r} names store {spec.store!r} but store {store.id!r} was supplied"
532
543
  )
533
- if spec.filters:
534
- # The spec validator already refuses filters; the runtime checks too,
535
- # because generated code is reachable without the validator having run.
536
- raise FeatureDeferredError(
537
- f"retriever {spec.id!r} declares filters, which spec v0.1 does not implement: a "
538
- "filter would have to be pushed into every store adapter's query"
539
- )
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})
540
551
  pinned = pinned_embedding(embedding, alias=spec.embed_model, dimensions=dimensions)
541
552
  if store.dimensions is not None and store.dimensions != pinned.dimensions:
542
553
  raise ConfigurationError(
@@ -547,7 +558,7 @@ def binding_from_spec(
547
558
  return RetrieverBinding(
548
559
  retriever_id=spec.id,
549
560
  source=spec.source,
550
- chunking=spec.chunking,
561
+ chunking=chunking,
551
562
  embed_model=spec.embed_model,
552
563
  embedding=pinned,
553
564
  store=spec.store,
@@ -556,6 +567,7 @@ def binding_from_spec(
556
567
  index=spec.index,
557
568
  top_k=spec.top_k,
558
569
  rerank=spec.rerank,
570
+ filters=filters,
559
571
  refresh_mode=spec.refresh.mode,
560
572
  traits=spec.traits,
561
573
  )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.124
3
+ Version: 0.1.126
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
@@ -273,7 +273,7 @@ These are refused explicitly rather than approximated — each raises `FeatureDe
273
273
 
274
274
  - `ModelGateway.stream` — the transport is request/response only, and no provider advertises
275
275
  `Capability.STREAMING`.
276
- - Retrieval: non-file sources, `semantic` chunking, `incremental` refresh, retriever `filters`, a hosted
276
+ - Retrieval: non-file sources, `semantic` chunking, retriever `filters`, a hosted
277
277
  reranker, and the `qdrant` / `pinecone` / `weaviate` / `custom` store kinds.
278
278
  - Escalation routing and third-party orchestration frameworks.
279
279
 
@@ -48,6 +48,7 @@ src/aid_runtime/retrieval/chunking.py
48
48
  src/aid_runtime/retrieval/citations.py
49
49
  src/aid_runtime/retrieval/connectors.py
50
50
  src/aid_runtime/retrieval/embedding.py
51
+ src/aid_runtime/retrieval/filters.py
51
52
  src/aid_runtime/retrieval/gate.py
52
53
  src/aid_runtime/retrieval/hybrid.py
53
54
  src/aid_runtime/retrieval/knowledge_base.py
@@ -94,6 +95,7 @@ tests/test_retrieval_chunking.py
94
95
  tests/test_retrieval_citations.py
95
96
  tests/test_retrieval_connectors.py
96
97
  tests/test_retrieval_embedding.py
98
+ tests/test_retrieval_filters.py
97
99
  tests/test_retrieval_gate.py
98
100
  tests/test_retrieval_hybrid.py
99
101
  tests/test_retrieval_knowledge_base.py