memoryking 0.1.0__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.
Files changed (179) hide show
  1. memoryking/__init__.py +3 -0
  2. memoryking/__main__.py +1328 -0
  3. memoryking/adapters/__init__.py +1 -0
  4. memoryking/adapters/adapter_state.py +242 -0
  5. memoryking/adapters/anchor_schema.sql +7 -0
  6. memoryking/adapters/atlas.py +441 -0
  7. memoryking/adapters/browser_commands.py +125 -0
  8. memoryking/adapters/dashboard.py +510 -0
  9. memoryking/adapters/dense_search.py +86 -0
  10. memoryking/adapters/egress_policy.py +244 -0
  11. memoryking/adapters/egress_schema.sql +13 -0
  12. memoryking/adapters/embedding.schema.json +302 -0
  13. memoryking/adapters/embedding_store.py +469 -0
  14. memoryking/adapters/execution.py +369 -0
  15. memoryking/adapters/experience.py +423 -0
  16. memoryking/adapters/experience.schema.json +1508 -0
  17. memoryking/adapters/experience_records.py +239 -0
  18. memoryking/adapters/experience_schema.sql +23 -0
  19. memoryking/adapters/handoff.py +494 -0
  20. memoryking/adapters/handoff.schema.json +299 -0
  21. memoryking/adapters/handoff_schema.sql +17 -0
  22. memoryking/adapters/index_schema.sql +11 -0
  23. memoryking/adapters/inference.py +454 -0
  24. memoryking/adapters/inference.schema.json +541 -0
  25. memoryking/adapters/inspection.py +1128 -0
  26. memoryking/adapters/inspection.schema.json +568 -0
  27. memoryking/adapters/knowledge.schema.json +633 -0
  28. memoryking/adapters/knowledge_schema.sql +37 -0
  29. memoryking/adapters/knowledge_store.py +800 -0
  30. memoryking/adapters/legacy_snapshot.py +358 -0
  31. memoryking/adapters/legacy_tables.py +49 -0
  32. memoryking/adapters/local_contract.py +45 -0
  33. memoryking/adapters/local_embeddings.py +189 -0
  34. memoryking/adapters/local_files.py +242 -0
  35. memoryking/adapters/local_ipc.py +258 -0
  36. memoryking/adapters/local_schema.sql +44 -0
  37. memoryking/adapters/local_store.py +632 -0
  38. memoryking/adapters/local_wire.schema.json +7672 -0
  39. memoryking/adapters/models/minilm-l6-v2-onnx.json +57 -0
  40. memoryking/adapters/models/ms-marco-minilm-l6-v2-onnx.json +57 -0
  41. memoryking/adapters/optional_schema.sql +43 -0
  42. memoryking/adapters/plan_dashboard.py +51 -0
  43. memoryking/adapters/plans.py +253 -0
  44. memoryking/adapters/postgres_admin.py +300 -0
  45. memoryking/adapters/postgres_anchor_schema.sql +9 -0
  46. memoryking/adapters/postgres_counter.sql +14 -0
  47. memoryking/adapters/postgres_egress_schema.sql +15 -0
  48. memoryking/adapters/postgres_experience_schema.sql +39 -0
  49. memoryking/adapters/postgres_index_schema.sql +7 -0
  50. memoryking/adapters/postgres_optional_schema.sql +71 -0
  51. memoryking/adapters/postgres_pool.py +77 -0
  52. memoryking/adapters/postgres_recovery.py +525 -0
  53. memoryking/adapters/postgres_schema.sql +365 -0
  54. memoryking/adapters/postgres_sql.py +102 -0
  55. memoryking/adapters/postgres_store.py +428 -0
  56. memoryking/adapters/postgres_summary_schema.sql +12 -0
  57. memoryking/adapters/postgres_trust_schema.sql +20 -0
  58. memoryking/adapters/processing.schema.json +471 -0
  59. memoryking/adapters/processing_store.py +346 -0
  60. memoryking/adapters/projects.py +83 -0
  61. memoryking/adapters/proposals.py +238 -0
  62. memoryking/adapters/ranking.py +315 -0
  63. memoryking/adapters/repository.schema.json +664 -0
  64. memoryking/adapters/repository_git.py +264 -0
  65. memoryking/adapters/repository_schema.sql +25 -0
  66. memoryking/adapters/repository_store.py +960 -0
  67. memoryking/adapters/retrieval.py +1285 -0
  68. memoryking/adapters/retrieval.schema.json +553 -0
  69. memoryking/adapters/retrieval_schema.sql +10 -0
  70. memoryking/adapters/shared_control.py +40 -0
  71. memoryking/adapters/shared_dashboard.py +636 -0
  72. memoryking/adapters/shared_gateway.py +63 -0
  73. memoryking/adapters/shared_http.py +216 -0
  74. memoryking/adapters/shared_mcp.py +159 -0
  75. memoryking/adapters/shared_service.py +124 -0
  76. memoryking/adapters/stdio.py +193 -0
  77. memoryking/adapters/stdio.tools.json +6776 -0
  78. memoryking/adapters/summary_schema.sql +10 -0
  79. memoryking/adapters/team.py +253 -0
  80. memoryking/adapters/timeline.py +80 -0
  81. memoryking/adapters/token_count.py +55 -0
  82. memoryking/adapters/tokenizers/LICENSE +21 -0
  83. memoryking/adapters/tokenizers/cl100k_base.tiktoken +100256 -0
  84. memoryking/adapters/trust.py +123 -0
  85. memoryking/adapters/trust_schema.sql +13 -0
  86. memoryking/adapters/web/app.css +1251 -0
  87. memoryking/adapters/web/app.js +907 -0
  88. memoryking/adapters/web/brand.js +44 -0
  89. memoryking/adapters/web/crown-mono.svg +1 -0
  90. memoryking/adapters/web/crown.svg +8 -0
  91. memoryking/adapters/web/elephant.png +0 -0
  92. memoryking/adapters/web/favicon.svg +8 -0
  93. memoryking/adapters/web/graph-layout.js +52 -0
  94. memoryking/adapters/web/graph-worker.js +10 -0
  95. memoryking/adapters/web/graph.js +570 -0
  96. memoryking/adapters/web/index.html +208 -0
  97. memoryking/adapters/web/observatory.js +1208 -0
  98. memoryking/adapters/web/team.js +151 -0
  99. memoryking/adapters/web/wordmark.svg +1 -0
  100. memoryking/adapters/working.py +971 -0
  101. memoryking/adapters/working.schema.json +1717 -0
  102. memoryking/adapters/working_schema.sql +24 -0
  103. memoryking/application/__init__.py +1 -0
  104. memoryking/application/conformance.py +50 -0
  105. memoryking/application/legacy_import.py +337 -0
  106. memoryking/application/local_port.py +9 -0
  107. memoryking/application/storage.py +117 -0
  108. memoryking/application/store_core.py +1292 -0
  109. memoryking/backups.py +131 -0
  110. memoryking/contracts/__init__.py +6 -0
  111. memoryking/contracts/__main__.py +20 -0
  112. memoryking/contracts/canonical.py +88 -0
  113. memoryking/contracts/embedding.schema.json +302 -0
  114. memoryking/contracts/embedding_generated.py +65 -0
  115. memoryking/contracts/experience.schema.json +1508 -0
  116. memoryking/contracts/experience_generated.py +239 -0
  117. memoryking/contracts/generated.py +122 -0
  118. memoryking/contracts/handoff.schema.json +299 -0
  119. memoryking/contracts/handoff_generated.py +69 -0
  120. memoryking/contracts/inference.schema.json +541 -0
  121. memoryking/contracts/inference_generated.py +106 -0
  122. memoryking/contracts/processing.schema.json +471 -0
  123. memoryking/contracts/processing_generated.py +82 -0
  124. memoryking/contracts/py.typed +0 -0
  125. memoryking/contracts/repository.schema.json +664 -0
  126. memoryking/contracts/repository_generated.py +144 -0
  127. memoryking/contracts/retrieval.schema.json +553 -0
  128. memoryking/contracts/retrieval_generated.py +110 -0
  129. memoryking/contracts/schema.json +696 -0
  130. memoryking/contracts/validation.py +92 -0
  131. memoryking/contracts/working.schema.json +1717 -0
  132. memoryking/contracts/working_generated.py +291 -0
  133. memoryking/domain/__init__.py +1 -0
  134. memoryking/domain/anchors.py +97 -0
  135. memoryking/domain/briefing.py +108 -0
  136. memoryking/domain/briefing_text.py +222 -0
  137. memoryking/domain/checkpoint.py +118 -0
  138. memoryking/domain/compression.py +64 -0
  139. memoryking/domain/delta.py +129 -0
  140. memoryking/domain/embeddings.py +90 -0
  141. memoryking/domain/hints.py +465 -0
  142. memoryking/domain/http_status.py +45 -0
  143. memoryking/domain/learning.py +62 -0
  144. memoryking/domain/local.py +65 -0
  145. memoryking/domain/plans.py +140 -0
  146. memoryking/domain/repository.py +118 -0
  147. memoryking/domain/selectors.py +356 -0
  148. memoryking/domain/summary.py +88 -0
  149. memoryking/domain/usage.py +163 -0
  150. memoryking/embedding_loop.py +98 -0
  151. memoryking/embedding_worker.py +131 -0
  152. memoryking/harness.py +882 -0
  153. memoryking/harness_context.py +376 -0
  154. memoryking/hooks.py +171 -0
  155. memoryking/host_hooks.py +454 -0
  156. memoryking/lean.py +352 -0
  157. memoryking/memory_tool.py +776 -0
  158. memoryking/migration.py +194 -0
  159. memoryking/model_install.py +78 -0
  160. memoryking/observability.py +101 -0
  161. memoryking/observability_metrics.py +100 -0
  162. memoryking/profiles.py +150 -0
  163. memoryking/providers.py +330 -0
  164. memoryking/py.typed +0 -0
  165. memoryking/pytest_plugin.py +69 -0
  166. memoryking/reference_agent.py +152 -0
  167. memoryking/repository_worker.py +57 -0
  168. memoryking/resume_adapter.py +154 -0
  169. memoryking/sdk.py +302 -0
  170. memoryking/shared.py +301 -0
  171. memoryking/shared_sdk.py +101 -0
  172. memoryking/vault.py +176 -0
  173. memoryking-0.1.0.dist-info/METADATA +157 -0
  174. memoryking-0.1.0.dist-info/RECORD +179 -0
  175. memoryking-0.1.0.dist-info/WHEEL +5 -0
  176. memoryking-0.1.0.dist-info/entry_points.txt +7 -0
  177. memoryking-0.1.0.dist-info/licenses/LICENSE +202 -0
  178. memoryking-0.1.0.dist-info/licenses/NOTICE +12 -0
  179. memoryking-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,469 @@
1
+ """Durable, opt-in embedding projection jobs under the existing release gate."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from jsonschema import Draft202012Validator
11
+
12
+ from memoryking.adapters.local_embeddings import MODEL, model_manifest
13
+ from memoryking.adapters.local_store import MAX_COUNTER, RETRY_MS, USAGE_LIMIT, uid
14
+ from memoryking.adapters.retrieval import Retrieval
15
+ from memoryking.application.store_core import StoreCore
16
+ from memoryking.contracts.canonical import canonical_bytes, canonical_hash
17
+ from memoryking.domain.embeddings import EmbeddingBatch, fingerprint
18
+ from memoryking.domain.local import LocalError, Released
19
+
20
+ VALIDATOR = Draft202012Validator(
21
+ json.loads(Path(__file__).with_name("embedding.schema.json").read_text())
22
+ )
23
+
24
+
25
+ class Embeddings:
26
+ def __init__(self, store: StoreCore):
27
+ self.s, self.db, self.r = store, store.db, Retrieval(store)
28
+
29
+ def execute(self, credential: str, command: dict[str, Any]) -> Released:
30
+ if len(canonical_bytes(command)) > 131072 or not VALIDATOR.is_valid(command):
31
+ raise LocalError("invalid_request")
32
+ if command["incarnation"] != self.s.incarnation:
33
+ raise LocalError("history_changed")
34
+ action, args = command["action"], command["args"]
35
+ receipt = uid("rcpt")
36
+ with self.s.transaction() as decision:
37
+ at = decision.evaluated_ms
38
+ who = self.s._auth(
39
+ credential, "admin" if action == "configure" else "jobs", args["project"], at
40
+ )
41
+ self.s._auth(credential, "read", args["project"], at)
42
+ if action == "configure":
43
+ result = self.configure(who, command, at)
44
+ elif action == "claim":
45
+ result = self.claim(who, args, at)
46
+ elif action in {"complete", "fail"}:
47
+ result = self.finish(who, args, action == "complete", at)
48
+ else:
49
+ part = self.partition(who, args)
50
+ result = self.status(part)
51
+ epochs = self.db.execute(
52
+ "SELECT policy_epoch,purge_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
53
+ ).fetchone()
54
+ result.update(
55
+ receipt=receipt,
56
+ evaluated_ms=at,
57
+ deadline_ms=decision.deadline_ms,
58
+ incarnation=self.s.incarnation,
59
+ )
60
+ raw = canonical_bytes(result)
61
+ self.db.execute(
62
+ "INSERT INTO receipts VALUES (?,?,?,?,?,?,?,?,?,?)",
63
+ (
64
+ who["tenant"],
65
+ receipt,
66
+ who["principal"],
67
+ self.s.incarnation,
68
+ at,
69
+ decision.deadline_ms,
70
+ *epochs,
71
+ hashlib.sha256(raw).hexdigest(),
72
+ json.dumps([result["observation"]] if "observation" in result else []),
73
+ ),
74
+ )
75
+ self.s.fault("after_validation")
76
+ self.s._expose()
77
+ return Released(raw, decision, self.s.clock, receipt)
78
+
79
+ def partition(self, who: dict[str, Any], args: dict[str, Any]) -> Any:
80
+ row = self.db.execute(
81
+ "SELECT * FROM embedding_partitions WHERE tenant=? AND project=? AND fingerprint=?",
82
+ (who["tenant"], args["project"], args["fingerprint"]),
83
+ ).fetchone()
84
+ if row is None:
85
+ raise LocalError("embedding_partition_unavailable")
86
+ if row["incarnation"] != self.s.incarnation:
87
+ raise LocalError("history_changed")
88
+ return row
89
+
90
+ def status(self, row: Any) -> dict[str, Any]:
91
+ source = self.db.execute(
92
+ "SELECT position FROM tenants WHERE tenant=?", (row["tenant"],)
93
+ ).fetchone()[0]
94
+ return {
95
+ "fingerprint": row["fingerprint"],
96
+ "dimensions": row["dimensions"],
97
+ "generation": row["generation"],
98
+ "state": row["state"],
99
+ "source_position": source,
100
+ "scheduled_position": row["scheduled"],
101
+ "frontier": row["frontier"],
102
+ "ready": row["state"] == "experimental" and row["frontier"] >= source,
103
+ "activation": "explicit_experiment_only",
104
+ "indexed_kind": "observation_prefix",
105
+ "input_byte_limit": 16384,
106
+ "input_token_limit": 256,
107
+ }
108
+
109
+ def configure(self, who: dict[str, Any], command: dict[str, Any], at: int) -> dict[str, Any]:
110
+ args = command["args"]
111
+ if args["model"] != MODEL:
112
+ raise LocalError("embedding_model_unsupported")
113
+ lookup = (
114
+ who["tenant"],
115
+ self.s.incarnation,
116
+ "embedding-config-v1",
117
+ who["principal"],
118
+ "configure",
119
+ command["key"],
120
+ )
121
+ previous = self.db.execute(
122
+ "SELECT * FROM retries WHERE tenant=? AND incarnation=? AND namespace=? AND principal=? AND operation=? AND key=?",
123
+ lookup,
124
+ ).fetchone()
125
+ if previous:
126
+ if previous["hash"] != canonical_hash(command):
127
+ raise LocalError("idempotency_conflict")
128
+ if previous["result"] is None or at >= previous["expires"]:
129
+ raise LocalError("idempotency_result_expired")
130
+ return {**json.loads(previous["result"]), "replayed": True}
131
+ configuration = model_manifest()
132
+ fp = fingerprint(configuration)
133
+ key = (who["tenant"], args["project"], fp)
134
+ row = self.db.execute(
135
+ "SELECT * FROM embedding_partitions WHERE tenant=? AND project=? AND fingerprint=?", key
136
+ ).fetchone()
137
+ generation = row["generation"] if row else 0
138
+ if args["expected_generation"] != generation:
139
+ raise LocalError("embedding_generation_conflict")
140
+ if generation >= MAX_COUNTER:
141
+ raise LocalError("counter_exhausted")
142
+ if (
143
+ row is None
144
+ and self.db.execute(
145
+ "SELECT count(*) FROM embedding_partitions WHERE tenant=?", (who["tenant"],)
146
+ ).fetchone()[0]
147
+ >= 16
148
+ ):
149
+ raise LocalError("embedding_partition_limit")
150
+ for table in ("embedding_jobs", "embedding_items"):
151
+ self.db.execute(
152
+ f"DELETE FROM {table} WHERE tenant=? AND project=? AND fingerprint=?", key
153
+ )
154
+ self.db.execute(
155
+ "INSERT INTO embedding_partitions VALUES (?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(tenant,project,fingerprint) DO UPDATE SET incarnation=excluded.incarnation,generation=excluded.generation,configuration=excluded.configuration,state=excluded.state,scheduled=0,frontier=0",
156
+ (
157
+ *key,
158
+ self.s.incarnation,
159
+ generation + 1,
160
+ configuration["dimensions"],
161
+ json.dumps(configuration),
162
+ args["state"],
163
+ 0,
164
+ 0,
165
+ at,
166
+ ),
167
+ )
168
+ position = self.s._event(who["tenant"], "embedding_configure", fp, at, who["principal"])
169
+ self.s._enqueue(who["tenant"], position, None, who["principal"])
170
+ result = {
171
+ "fingerprint": fp,
172
+ "dimensions": configuration["dimensions"],
173
+ "generation": generation + 1,
174
+ "state": args["state"],
175
+ "source_position": position,
176
+ "replayed": False,
177
+ }
178
+ self.db.execute(
179
+ "INSERT INTO retries VALUES (?,?,?,?,?,?,?,?,?,?)",
180
+ (*lookup, canonical_hash(command), json.dumps(result), None, at + RETRY_MS),
181
+ )
182
+ return result
183
+
184
+ def schedule(self, part: Any, at: int) -> None:
185
+ key = (part["tenant"], part["project"], part["fingerprint"], part["generation"])
186
+ pending = self.db.execute(
187
+ "SELECT count(*) FROM embedding_jobs WHERE tenant=? AND project=? AND fingerprint=? AND generation=? AND state NOT IN ('complete','noop')",
188
+ key,
189
+ ).fetchone()[0]
190
+ room = max(0, min(256, 1000 - pending))
191
+ rows = self.db.execute(
192
+ "SELECT e.position,o.id,o.revision,o.blob,o.deleted FROM events e LEFT JOIN observations o ON e.tenant=o.tenant AND e.subject=o.id AND o.project=? WHERE e.tenant=? AND e.position>? ORDER BY e.position LIMIT ?",
193
+ (part["project"], part["tenant"], part["scheduled"], room),
194
+ ).fetchall()
195
+ epoch = self.db.execute(
196
+ "SELECT purge_epoch FROM tenants WHERE tenant=?", (part["tenant"],)
197
+ ).fetchone()[0]
198
+ for row in rows:
199
+ observation = row["id"] if row["id"] and not row["deleted"] else None
200
+ self.db.execute(
201
+ "INSERT INTO embedding_jobs VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
202
+ (
203
+ *key,
204
+ row["position"],
205
+ observation,
206
+ row["revision"] if observation else 0,
207
+ row["blob"] if observation else None,
208
+ self.s.incarnation,
209
+ "pending" if observation else "noop",
210
+ 0,
211
+ 0,
212
+ 0,
213
+ at,
214
+ None,
215
+ epoch,
216
+ ),
217
+ )
218
+ if rows:
219
+ self.db.execute(
220
+ "UPDATE embedding_partitions SET scheduled=? WHERE tenant=? AND project=? AND fingerprint=?",
221
+ (rows[-1]["position"], *key[:3]),
222
+ )
223
+ self.advance(part)
224
+
225
+ def advance(self, part: Any) -> None:
226
+ key = (part["tenant"], part["project"], part["fingerprint"], part["generation"])
227
+ fresh = self.db.execute(
228
+ "SELECT frontier,scheduled FROM embedding_partitions WHERE tenant=? AND project=? AND fingerprint=?",
229
+ key[:3],
230
+ ).fetchone()
231
+ frontier = fresh["frontier"]
232
+ rows = self.db.execute(
233
+ "SELECT position,state FROM embedding_jobs WHERE tenant=? AND project=? AND fingerprint=? AND generation=? AND position>? ORDER BY position LIMIT 1256",
234
+ (*key, frontier),
235
+ ).fetchall()
236
+ for row in rows:
237
+ if row["position"] != frontier + 1 or row["state"] not in {"complete", "noop"}:
238
+ break
239
+ frontier += 1
240
+ self.db.execute(
241
+ "UPDATE embedding_partitions SET frontier=? WHERE tenant=? AND project=? AND fingerprint=?",
242
+ (frontier, *key[:3]),
243
+ )
244
+ self.db.execute(
245
+ "DELETE FROM embedding_jobs WHERE tenant=? AND project=? AND fingerprint=? AND generation=? AND position<?",
246
+ (*key, max(0, frontier - 256)),
247
+ )
248
+
249
+ def source(self, who: dict[str, Any], row: Any, at: int) -> str:
250
+ observation = self.db.execute(
251
+ "SELECT * FROM observations WHERE tenant=? AND id=? AND project=?",
252
+ (who["tenant"], row["observation"], row["project"]),
253
+ ).fetchone()
254
+ if observation is None or not self.s._visible(who, observation, at):
255
+ raise LocalError("embedding_source_unavailable")
256
+ if (
257
+ observation["revision"] != row["source_revision"]
258
+ or observation["blob"] != row["blob_hash"]
259
+ ):
260
+ raise LocalError("stale_source")
261
+ return self.r._blob(observation)[:16384].decode("utf-8", errors="ignore")
262
+
263
+ def claim(self, who: dict[str, Any], args: dict[str, Any], at: int) -> dict[str, Any]:
264
+ part = self.partition(who, args)
265
+ if part["state"] != "experimental":
266
+ raise LocalError("embedding_disabled")
267
+ self.schedule(part, at)
268
+ self.db.execute(
269
+ "UPDATE embedding_jobs SET state='dead',fence=fence+1 WHERE tenant=? AND state='leased' AND lease_until<=? AND attempts>=5",
270
+ (who["tenant"], at),
271
+ )
272
+ if (
273
+ self.db.execute(
274
+ "SELECT count(*) FROM embedding_jobs WHERE tenant=? AND state='leased' AND lease_until>?",
275
+ (who["tenant"], at),
276
+ ).fetchone()[0]
277
+ >= 4
278
+ ):
279
+ raise LocalError("concurrency_limit")
280
+ row = self.db.execute(
281
+ "SELECT j.* FROM embedding_jobs j JOIN observations o ON j.tenant=o.tenant AND j.observation=o.id WHERE j.tenant=? AND j.project=? AND j.fingerprint=? AND j.generation=? AND o.deleted=0 AND (o.readers='null' OR EXISTS(SELECT 1 FROM json_each(o.readers) WHERE value=?)) AND j.attempts<5 AND ((j.state='pending' AND j.available<=?) OR (j.state='leased' AND j.lease_until<=?)) ORDER BY j.position LIMIT 1",
282
+ (
283
+ who["tenant"],
284
+ args["project"],
285
+ args["fingerprint"],
286
+ part["generation"],
287
+ who["principal"],
288
+ at,
289
+ at,
290
+ ),
291
+ ).fetchone()
292
+ if row is None:
293
+ return {"job": None, **self.status(self.partition(who, args))}
294
+ if (
295
+ self.db.execute(
296
+ "SELECT count(*) FROM processing_usage WHERE tenant=?", (who["tenant"],)
297
+ ).fetchone()[0]
298
+ >= USAGE_LIMIT
299
+ ):
300
+ # Only rows past their retention are released; recent attempts are never
301
+ # silently discarded to make room.
302
+ self.db.execute(
303
+ "DELETE FROM processing_usage WHERE tenant=? AND expires<=?", (who["tenant"], at)
304
+ )
305
+ if (
306
+ self.db.execute(
307
+ "SELECT count(*) FROM processing_usage WHERE tenant=?", (who["tenant"],)
308
+ ).fetchone()[0]
309
+ >= USAGE_LIMIT
310
+ ):
311
+ raise LocalError("usage_retention_limit")
312
+ text = self.source(who, row, at)
313
+ key = (
314
+ who["tenant"],
315
+ args["project"],
316
+ args["fingerprint"],
317
+ part["generation"],
318
+ row["position"],
319
+ )
320
+ epoch = self.db.execute(
321
+ "SELECT purge_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
322
+ ).fetchone()[0]
323
+ self.db.execute(
324
+ "UPDATE embedding_jobs SET state='leased',fence=fence+1,attempts=attempts+1,lease_until=?,principal=?,purge_epoch=? WHERE tenant=? AND project=? AND fingerprint=? AND generation=? AND position=?",
325
+ (at + 30000, who["principal"], epoch, *key),
326
+ )
327
+ attempt = uid("usage")
328
+ self.db.execute(
329
+ "INSERT INTO processing_usage VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
330
+ (
331
+ who["tenant"],
332
+ attempt,
333
+ args["project"],
334
+ who["principal"],
335
+ self.s.incarnation,
336
+ "local-onnx",
337
+ args["fingerprint"],
338
+ "embedding_backfill",
339
+ "started",
340
+ None,
341
+ 0,
342
+ 0,
343
+ 0,
344
+ 0,
345
+ canonical_hash(text),
346
+ None,
347
+ json.dumps([{"kind": "observation", "id": row["observation"]}]),
348
+ at,
349
+ at + RETRY_MS,
350
+ ),
351
+ )
352
+ lease = self.s._token(
353
+ "embedding_lease",
354
+ tenant=who["tenant"],
355
+ principal=who["principal"],
356
+ project=args["project"],
357
+ fingerprint=args["fingerprint"],
358
+ generation=part["generation"],
359
+ position=row["position"],
360
+ fence=row["fence"] + 1,
361
+ attempt=attempt,
362
+ input_hash=canonical_hash(text),
363
+ )
364
+ return {
365
+ "job": row["position"],
366
+ "lease": lease,
367
+ "lease_until_ms": at + 30000,
368
+ "input": text,
369
+ "input_hash": canonical_hash(text),
370
+ "fingerprint": args["fingerprint"],
371
+ "dimensions": part["dimensions"],
372
+ "observation": row["observation"],
373
+ "blob_hash": row["blob_hash"],
374
+ "start_byte": 0,
375
+ "end_byte": len(text.encode()),
376
+ "egress": "local_cpu_only",
377
+ }
378
+
379
+ def finish(
380
+ self, who: dict[str, Any], args: dict[str, Any], complete: bool, at: int
381
+ ) -> dict[str, Any]:
382
+ token = self.s._decode(args["lease"], "embedding_lease")
383
+ if (
384
+ any(token[k] != who[k] for k in ("tenant", "principal"))
385
+ or token["project"] != args["project"]
386
+ ):
387
+ raise LocalError("denied")
388
+ part = self.partition(
389
+ who, {"project": args["project"], "fingerprint": token["fingerprint"]}
390
+ )
391
+ key = (
392
+ who["tenant"],
393
+ args["project"],
394
+ token["fingerprint"],
395
+ token["generation"],
396
+ token["position"],
397
+ )
398
+ row = self.db.execute(
399
+ "SELECT * FROM embedding_jobs WHERE tenant=? AND project=? AND fingerprint=? AND generation=? AND position=?",
400
+ key,
401
+ ).fetchone()
402
+ if (
403
+ row is None
404
+ or row["state"] != "leased"
405
+ or row["fence"] != token["fence"]
406
+ or row["lease_until"] <= at
407
+ or part["generation"] != token["generation"]
408
+ or part["state"] != "experimental"
409
+ ):
410
+ raise LocalError("stale_lease")
411
+ text = self.source(who, row, at)
412
+ epoch = self.db.execute(
413
+ "SELECT purge_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
414
+ ).fetchone()[0]
415
+ if epoch != row["purge_epoch"] or canonical_hash(text) != token["input_hash"]:
416
+ raise LocalError("stale_source")
417
+ output_hash = None
418
+ if complete:
419
+ batch = EmbeddingBatch(
420
+ args["fingerprint"],
421
+ part["dimensions"],
422
+ [args["vector"]],
423
+ [args["input_hash"]],
424
+ args["input_tokens"],
425
+ [args["truncated"]],
426
+ )
427
+ batch.validate(token["fingerprint"], part["dimensions"], [text])
428
+ output_hash = canonical_hash(args["vector"])
429
+ self.db.execute(
430
+ "INSERT INTO embedding_items VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(tenant,project,fingerprint,generation,observation) DO UPDATE SET incarnation=excluded.incarnation,source_revision=excluded.source_revision,blob_hash=excluded.blob_hash,input_hash=excluded.input_hash,vector_json=excluded.vector_json,start_byte=excluded.start_byte,end_byte=excluded.end_byte,input_tokens=excluded.input_tokens,truncated=excluded.truncated,position=excluded.position",
431
+ (
432
+ *key[:4],
433
+ row["observation"],
434
+ self.s.incarnation,
435
+ row["source_revision"],
436
+ row["blob_hash"],
437
+ args["input_hash"],
438
+ json.dumps(args["vector"]),
439
+ 0,
440
+ len(text.encode()),
441
+ args["input_tokens"],
442
+ int(args["truncated"]),
443
+ row["position"],
444
+ ),
445
+ )
446
+ state = "complete" if complete else "dead" if row["attempts"] >= 5 else "pending"
447
+ self.db.execute(
448
+ "UPDATE embedding_jobs SET state=?,fence=fence+1,available=? WHERE tenant=? AND project=? AND fingerprint=? AND generation=? AND position=?",
449
+ (state, at + min(60000, 2 ** row["attempts"] * 1000), *key),
450
+ )
451
+ self.db.execute(
452
+ "UPDATE processing_usage SET status=?,input_tokens=?,duration_ms=?,output_hash=? WHERE tenant=? AND id=? AND principal=?",
453
+ (
454
+ "succeeded" if complete else "failed",
455
+ args["input_tokens"],
456
+ args["duration_ms"],
457
+ output_hash,
458
+ who["tenant"],
459
+ token["attempt"],
460
+ who["principal"],
461
+ ),
462
+ )
463
+ self.advance(part)
464
+ return {
465
+ "status": state,
466
+ "fingerprint": token["fingerprint"],
467
+ "observation": row["observation"],
468
+ "usage_attempt": token["attempt"],
469
+ }