aid-runtime-python 0.1.123__py3-none-any.whl → 0.1.125__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.123"
313
+ __version__ = "0.1.125"
314
314
 
315
315
  __all__ = [
316
316
  "ANTHROPIC_VERSION",
@@ -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
@@ -78,6 +78,12 @@ class IngestReport(BaseModel):
78
78
  ingests of identical input compare equal without depending on the order the
79
79
  filesystem happened to yield. ``cost_usd`` is what *this* ingest charged, not the
80
80
  ledger's running total, so ingesting twice reads as two separate spends.
81
+
82
+ ``written`` counts chunks upserted and ``reused`` counts chunks an incremental
83
+ ingest found already stored and therefore did not embed; ``written + reused`` is
84
+ ``chunks``. ``removed`` counts chunks deleted because their document no longer
85
+ yields them. All three are zero-or-more, and all but ``written`` are zero for a
86
+ ``full`` refresh, which never reads the index and never deletes from it.
81
87
  """
82
88
 
83
89
  model_config = ConfigDict(frozen=True, extra="forbid")
@@ -89,6 +95,8 @@ class IngestReport(BaseModel):
89
95
  tokens: int = Field(ge=0)
90
96
  cost_usd: float = Field(ge=0.0)
91
97
  chunk_ids: tuple[str, ...]
98
+ reused: int = Field(default=0, ge=0)
99
+ removed: int = Field(default=0, ge=0)
92
100
 
93
101
  @property
94
102
  def is_empty(self) -> bool:
@@ -145,12 +153,6 @@ class Retriever:
145
153
  self._connector = None
146
154
  self._base_dir = None
147
155
  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
156
  self._knowledge_base_client = None
155
157
  self._embedder = embedder or embedder_for(binding.embedding)
156
158
  self._store = store or create_store(
@@ -185,6 +187,18 @@ class Retriever:
185
187
  upserts on them, so ingesting the same input twice replaces rather than
186
188
  duplicates. Re-ingesting is therefore a legitimate way to refresh a corpus.
187
189
 
190
+ ``refresh.mode`` decides what the second run redoes. ``full`` -- the default --
191
+ embeds and upserts every chunk and never reads or deletes from the index, so
192
+ dropping a document from the source leaves its vectors behind. ``incremental``
193
+ instead reconciles the index with the source: a chunk the store already holds
194
+ keeps its vector, a stored chunk the source no longer yields is deleted, and
195
+ only new chunks are embedded.
196
+
197
+ Incremental therefore treats what it is given as the *whole* corpus, whether
198
+ that came from the connector or from an explicit ``documents`` argument. Passing
199
+ a subset of the corpus in incremental mode deletes the rest, exactly as narrowing
200
+ the source glob would; the mode is a reconciliation, not a merge.
201
+
188
202
  Refused for a managed retriever. The engine ingests from its own data source, so
189
203
  a local ingest would write vectors the retriever never reads -- work that costs
190
204
  money and changes nothing, which is the worst kind of silent success.
@@ -195,16 +209,26 @@ class Retriever:
195
209
  "which ingests from its data source inside the engine; there is no local "
196
210
  "index to fill, and writing one would be read by nothing"
197
211
  )
198
- source_documents = tuple(documents) if documents is not None else await self._read_source()
199
212
  local = self._local
213
+ incremental = local.refresh_mode is RefreshMode.INCREMENTAL
214
+ source_documents = tuple(documents) if documents is not None else await self._read_source()
200
215
  chunker = chunker_for(local.chunking)
201
216
  chunks = [chunk for document in source_documents for chunk in chunker.chunk(document)]
202
217
 
218
+ to_embed = chunks
219
+ removed = 0
220
+ if incremental:
221
+ stored = set(await self.store.chunk_ids())
222
+ current = {chunk.chunk_id for chunk in chunks}
223
+ if stale := sorted(stored - current):
224
+ removed = await self.store.delete(stale)
225
+ to_embed = [chunk for chunk in chunks if chunk.chunk_id not in stored]
226
+
203
227
  records: list[StoreRecord] = []
204
228
  tokens = 0
205
229
  cost = 0.0
206
- for start in range(0, len(chunks), _BATCH_SIZE):
207
- batch = chunks[start : start + _BATCH_SIZE]
230
+ for start in range(0, len(to_embed), _BATCH_SIZE):
231
+ batch = to_embed[start : start + _BATCH_SIZE]
208
232
  embedded, batch_cost = await self._embed(tuple(chunk.text for chunk in batch))
209
233
  tokens += embedded.usage.input_tokens
210
234
  cost += batch_cost
@@ -219,6 +243,8 @@ class Retriever:
219
243
  documents=len(source_documents),
220
244
  chunks=len(chunks),
221
245
  written=written,
246
+ reused=len(chunks) - len(to_embed),
247
+ removed=removed,
222
248
  tokens=tokens,
223
249
  cost_usd=cost,
224
250
  chunk_ids=tuple(sorted(chunk.chunk_id for chunk in chunks)),
@@ -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
 
@@ -119,7 +119,12 @@ class StoreKind(StrEnum):
119
119
 
120
120
 
121
121
  class RefreshMode(StrEnum):
122
- """``retriever.refresh.mode``. Only ``FULL`` is implemented."""
122
+ """``retriever.refresh.mode``.
123
+
124
+ ``FULL`` re-embeds the whole source every run. ``INCREMENTAL`` reconciles the index
125
+ with the source: unchanged chunks keep their vectors, stale ones are deleted, and
126
+ only new ones are embedded.
127
+ """
123
128
 
124
129
  FULL = "full"
125
130
  INCREMENTAL = "incremental"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.123
3
+ Version: 0.1.125
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
 
@@ -1,4 +1,4 @@
1
- aid_runtime/__init__.py,sha256=SAeSFGl9d5de2XUB7IwLVZG8U2GIDa44TADgP08PpTU,13238
1
+ aid_runtime/__init__.py,sha256=_EfYBqiBKQS54Tp19FbJyUrRLWM2Khenw0uXYgVXSPE,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
@@ -50,12 +50,12 @@ aid_runtime/retrieval/gate.py,sha256=3avH1Gwp7iv7mMOskmNbk70Yq85tXwJrKVrQAKKI4Js
50
50
  aid_runtime/retrieval/hybrid.py,sha256=-GIBeI3njT5uaEvSeq2t151Zlv2yOPHOPje4TJLNVyU,5804
51
51
  aid_runtime/retrieval/knowledge_base.py,sha256=xNFTdIdIMvS7Ij9y4niXGrgxAhtsmWe2kOVyR_j9AU4,28360
52
52
  aid_runtime/retrieval/metrics.py,sha256=LN36BIXzpbhkG9grzE0q5wncgXt_Y85-b5jGJ038-3Y,7904
53
- aid_runtime/retrieval/pgvector.py,sha256=kdE6Gdk9JhR6-QxN353CmuNYMLyr5eBvnQl4krLzLew,10040
53
+ aid_runtime/retrieval/pgvector.py,sha256=tahRZQr8xQp7tZ5spgTzlEEMv2HpSx3OLPKjdq_vz0c,11015
54
54
  aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJMc,5114
55
- aid_runtime/retrieval/retriever.py,sha256=5I8BocFaJ292cqh9-Gz2NRB4OwBHa-pitAB6--5ARBE,19890
56
- aid_runtime/retrieval/stores.py,sha256=VEi68AaMHcQjdAbWOHflp3jCl1_1db71rIzZjTouLlo,5857
57
- aid_runtime/retrieval/types.py,sha256=bke4W2q8ecGFvF2tj8y1tfFq8EtGb6iiPVbT-l02a98,19860
58
- aid_runtime_python-0.1.123.dist-info/METADATA,sha256=dgMj5tivYk4-q4IhcKgt7MfeDDcxQlYd5pW3eUtdU80,17006
59
- aid_runtime_python-0.1.123.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
60
- aid_runtime_python-0.1.123.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
61
- aid_runtime_python-0.1.123.dist-info/RECORD,,
55
+ aid_runtime/retrieval/retriever.py,sha256=t6xhku1GCzE95kWXAgbdJyU3ATGANm9K7XX6sMDG_uQ,21363
56
+ 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,,