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,428 @@
1
+ """Request-bound PostgreSQL storage using the reviewed relational service operations.
2
+
3
+ SQL, gates, pool lifecycle and recovery evidence are native shared implementations.
4
+ A store is bound to one signed tenant/principal; transport must never reuse it for
5
+ another authenticated identity. All final decisions run on the primary.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import threading
12
+ import time
13
+ from collections.abc import Iterator
14
+ from contextlib import contextmanager
15
+ from pathlib import Path
16
+ from typing import Any, Callable
17
+
18
+ from memoryking.adapters.local_files import private_dir, private_file, sync_dir
19
+ from memoryking.adapters.local_store import (
20
+ CAPABILITIES,
21
+ MAX_COUNTER,
22
+ LocalStore,
23
+ identifier,
24
+ paths,
25
+ uid,
26
+ )
27
+ from memoryking.adapters.postgres_sql import PostgresSQL
28
+ from memoryking.adapters.shared_control import SharedControl
29
+ from memoryking.application.storage import PostgresDialect
30
+ from memoryking.application.store_core import StoreCore
31
+ from memoryking.domain.local import Clock, Decision, LocalError, SystemClock
32
+ from memoryking.observability_metrics import Metrics
33
+
34
+
35
+ class PostgresStore(StoreCore):
36
+ control: SharedControl
37
+
38
+ def dense_exact(
39
+ self, statement: str, parameters: tuple[Any, ...], request: dict[str, Any], limit: int
40
+ ) -> dict[str, Any] | None:
41
+ """Explicit optional pgvector engine, with a materialized eligibility boundary.
42
+
43
+ No approximate index exists. Float32 cosine can differ by a rounding unit
44
+ from the portable integer-vector calculation; the receipt names the engine.
45
+ """
46
+ import json
47
+
48
+ extension = self.db.execute(
49
+ "SELECT e.extversion,n.nspname FROM pg_catalog.pg_extension e JOIN pg_catalog.pg_namespace n ON e.extnamespace=n.oid WHERE e.extname='vector'"
50
+ ).fetchone()
51
+ if extension is None or tuple(extension) != ("0.8.7", "memoryking_vector"):
52
+ return None
53
+ prefix = "WITH eligible AS MATERIALIZED (" + statement + ") "
54
+ count = self.db.execute(prefix + "SELECT count(*) FROM eligible", parameters).fetchone()[0]
55
+ if count > limit:
56
+ return {"availability": "scan_limit", "candidate_limit_reached": True}
57
+ rows = self.db.execute(
58
+ prefix
59
+ + ", scored AS (SELECT observation,LEAST(1000000,GREATEST(-1000000,ROUND((1-(vector_json::memoryking_vector.vector OPERATOR(memoryking_vector.<=>) ?::memoryking_vector.vector))*1000000)))::bigint AS score FROM eligible) SELECT observation,score FROM scored WHERE score>=? ORDER BY score DESC,observation LIMIT 257",
60
+ (
61
+ *parameters,
62
+ json.dumps(request["vector"]),
63
+ request.get("minimum_similarity_ppm", 200000),
64
+ ),
65
+ ).fetchall()
66
+ return {
67
+ "scores": {row["observation"]: row["score"] for row in rows[:256]},
68
+ "eligible_vectors": count,
69
+ "candidate_limit_reached": len(rows) > 256,
70
+ }
71
+
72
+ def __init__(
73
+ self,
74
+ pool: Any,
75
+ root: Path,
76
+ control: Path,
77
+ tenant: str,
78
+ credential: str,
79
+ *,
80
+ clock: Clock | None = None,
81
+ fault: Callable[[str], None] | None = None,
82
+ release_only: bool = False,
83
+ audience: str = "memoryking-shared",
84
+ request_deadline: float | None = None,
85
+ ):
86
+ """`request_deadline` is a monotonic instant: checkout, the checkout checks and
87
+ every statement in this store's transactions stop at it, so a saturated pool or
88
+ a slow query fails as `service_busy` or `service_unavailable` within the caller's
89
+ own budget instead of past it."""
90
+ identifier(tenant)
91
+ paths(root, control)
92
+ private_dir(root)
93
+ private_dir(control)
94
+ private_dir(control / tenant)
95
+ self.root, self.control_path = root, control / tenant
96
+ self.control = SharedControl(self.control_path)
97
+ self.anchor = self.control.read_anchor()
98
+ self.store_id, self.incarnation = self.control.store, self.anchor["incarnation"]
99
+ self.tenant = tenant
100
+ self.audience = identifier(audience)
101
+ self.credential = credential
102
+ identity = self._decode(credential, "credential")
103
+ if identity.get("tenant") != tenant:
104
+ raise LocalError("denied")
105
+ self.principal = identifier(identity["principal"])
106
+ self.clock = clock or SystemClock()
107
+ self.fault = fault or (lambda _: None)
108
+ self.lock = threading.RLock()
109
+ self.dialect = PostgresDialect()
110
+ self.healthy = True
111
+ self.retrieval_cache: dict[str, Any] = {}
112
+ self._last_housekeeping = 0
113
+ self.counters = Metrics()
114
+ self.timings = threading.local()
115
+ self.embedder: Any | None = None
116
+ self.reranker: Any | None = None
117
+ self.last_utc = self.anchor["last_utc"]
118
+ self.release_only = release_only
119
+ self.active = False
120
+ self.metrics: list[dict[str, float]] = []
121
+ self.committed: dict[str, Any] | None = None
122
+ self.pool = pool
123
+ self.request_deadline = request_deadline
124
+ from memoryking.adapters.postgres_pool import acquire, check
125
+
126
+ remaining = None if request_deadline is None else request_deadline - time.monotonic()
127
+ if remaining is not None and remaining <= 0:
128
+ raise LocalError("service_busy")
129
+ self.connection = acquire(pool, timeout=remaining)
130
+ try:
131
+ if request_deadline is not None:
132
+ remaining_ms = max(1, int((request_deadline - time.monotonic()) * 1000))
133
+ self.connection.execute(
134
+ "SELECT set_config('statement_timeout',%s,false)", (str(remaining_ms),)
135
+ )
136
+ # getconn() does not run the pool's checkout check callback.
137
+ check(self.connection)
138
+ version = self.connection.execute(
139
+ "SELECT value FROM memoryking.shared_meta WHERE key='schema'"
140
+ ).fetchone()
141
+ if version is None or version[0] != "8":
142
+ raise LocalError("schema_unsupported")
143
+ self.db = PostgresSQL(self.connection, lambda: self.active)
144
+ except BaseException as exc:
145
+ pool.putconn(self.connection)
146
+ if request_deadline is not None and (
147
+ time.monotonic() >= request_deadline or getattr(exc, "sqlstate", None) == "57014"
148
+ ):
149
+ raise LocalError("service_unavailable") from exc
150
+ raise
151
+
152
+ def close(self) -> None:
153
+ if self.connection is not None:
154
+ self.connection.rollback()
155
+ self.pool.putconn(self.connection)
156
+ self.connection = None
157
+
158
+ def _auth(self, token: str, capability: str, project: str, at: int) -> dict[str, Any]:
159
+ identity = self._decode(token, "credential")
160
+ if identity.get("tenant") != self.tenant or identity.get("principal") != self.principal:
161
+ raise LocalError("denied")
162
+ delegation = identity.get("delegation")
163
+ if delegation:
164
+ if (
165
+ project != delegation["project"]
166
+ or capability not in delegation["capabilities"]
167
+ or at >= delegation["expires"]
168
+ ):
169
+ raise LocalError("denied")
170
+ parent = self._token("credential", tenant=self.tenant, principal=delegation["by"])
171
+ StoreCore._auth(self, parent, capability, project, at)
172
+ return super()._auth(token, capability, project, at)
173
+
174
+ def _token(self, kind: str, **fields: Any) -> str:
175
+ if kind == "credential":
176
+ fields["audience"] = self.audience
177
+ return super()._token(kind, **fields)
178
+
179
+ def _decode(self, token: str, kind: str) -> dict[str, Any]:
180
+ identity = super()._decode(token, kind)
181
+ if kind == "credential" and identity.get("audience") != self.audience:
182
+ raise LocalError("credential_audience_mismatch")
183
+ return identity
184
+
185
+ def _subject_auth(self, token: str, capability: str, project: str, at: int) -> dict[str, Any]:
186
+ identity = self._decode(token, "credential")
187
+ if identity.get("tenant") != self.tenant:
188
+ raise LocalError("denied")
189
+ if identity.get("principal") == self.principal:
190
+ return self._auth(self.credential, capability, project, at)
191
+ return LocalStore._auth(self, token, capability, project, at)
192
+
193
+ def _context_details(
194
+ self, who: dict[str, Any], capabilities: set[str], project: str, at: int
195
+ ) -> dict[str, Any]:
196
+ allowed = []
197
+ for capability in sorted(capabilities):
198
+ try:
199
+ self._auth(self.credential, capability, project, at)
200
+ allowed.append(capability)
201
+ except LocalError:
202
+ pass
203
+ return {"capabilities": allowed, "delegation_chain": who.get("delegation_chain", [])}
204
+
205
+ def delegate(self, principal: str, project: str, capabilities: list[str], ttl_ms: int) -> str:
206
+ identifier(principal)
207
+ identifier(project)
208
+ if (
209
+ not capabilities
210
+ or not set(capabilities) <= CAPABILITIES - {"admin"}
211
+ or not isinstance(ttl_ms, int)
212
+ or isinstance(ttl_ms, bool)
213
+ or not 1 <= ttl_ms <= 3600000
214
+ ):
215
+ raise LocalError("invalid_delegation")
216
+ with self.transaction() as decision:
217
+ actor = self._decode(self.credential, "credential")
218
+ if actor.get("delegation"):
219
+ raise LocalError("delegation_depth_exceeded")
220
+ subject = self._token("credential", tenant=self.tenant, principal=principal)
221
+ for capability in capabilities:
222
+ self._auth(self.credential, capability, project, decision.evaluated_ms)
223
+ LocalStore._auth(self, subject, capability, project, decision.evaluated_ms)
224
+ delegation = {
225
+ "id": uid("delegation"),
226
+ "by": self.principal,
227
+ "project": project,
228
+ "capabilities": sorted(set(capabilities)),
229
+ "expires": decision.evaluated_ms + ttl_ms,
230
+ }
231
+ token = self._token(
232
+ "credential",
233
+ tenant=self.tenant,
234
+ principal=principal,
235
+ delegation=delegation,
236
+ delegation_chain=[delegation["id"]],
237
+ )
238
+ self._expose()
239
+ return token
240
+
241
+ def _settings(self) -> None:
242
+ self.connection.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED")
243
+ self.connection.execute("SET LOCAL search_path=memoryking,pg_catalog")
244
+ remaining_ms = (
245
+ 5000
246
+ if self.request_deadline is None
247
+ else min(5000, int((self.request_deadline - time.monotonic()) * 1000))
248
+ )
249
+ if remaining_ms <= 0:
250
+ raise LocalError("service_busy")
251
+ for setting in ("lock_timeout", "statement_timeout"):
252
+ self.connection.execute("SELECT set_config(%s,%s,true)", (setting, str(remaining_ms)))
253
+ self.connection.execute("SELECT set_config('memoryking.tenant',%s,true)", (self.tenant,))
254
+ self.connection.execute(
255
+ "SELECT set_config('memoryking.principal',%s,true)", (self.principal,)
256
+ )
257
+
258
+ def _validate_anchor(self) -> list[dict[str, Any]]:
259
+ with self.control.locked():
260
+ self.anchor = self.control.read_anchor()
261
+ records = self.control.journal(self.anchor)
262
+ meta = dict(self.db.execute("SELECT key,value FROM meta"))
263
+ position = self.db.execute(
264
+ "SELECT position FROM tenants WHERE tenant=?", (self.tenant,)
265
+ ).fetchone()
266
+ if (
267
+ self.anchor["state"] != "active"
268
+ or meta.get("store") != self.store_id
269
+ or meta.get("incarnation") != self.incarnation
270
+ or self.anchor["incarnation"] != self.incarnation
271
+ or int(meta["commit_serial"]) < self.anchor["commit_serial"]
272
+ or position is None
273
+ or position[0] < self.anchor["frontiers"].get(self.tenant, 0)
274
+ ):
275
+ raise LocalError("recovery_required")
276
+ self.last_utc = max(self.last_utc, self.anchor["last_utc"])
277
+ return [record for record in records if record["sequence"] > int(meta["journal"])]
278
+
279
+ @contextmanager
280
+ def transaction(self) -> Iterator[Decision]:
281
+ with self.lock:
282
+ if not self.healthy or self.active or self.connection is None:
283
+ raise LocalError("recovery_required")
284
+ started = time.monotonic()
285
+ locked: float | None = None
286
+ clock_started: float | None = None
287
+ clock_locked: float | None = None
288
+ committed_ok = False
289
+ try:
290
+ with self.connection.transaction():
291
+ self._settings()
292
+ self.active = True
293
+ mode = "SHARE" if self.release_only else "UPDATE"
294
+ row = self.connection.execute(
295
+ f"SELECT tenant FROM memoryking.tenant_gates WHERE tenant=%s FOR {mode}",
296
+ (self.tenant,),
297
+ ).fetchone()
298
+ if row is None:
299
+ raise LocalError("denied")
300
+ locked = time.monotonic()
301
+ pending = self._validate_anchor()
302
+ if pending and self.release_only:
303
+ raise LocalError("journal_replay_required")
304
+ decision = self._now()
305
+ for record in pending:
306
+ self._apply(record, decision.evaluated_ms)
307
+ if pending:
308
+ with self.control.locked():
309
+ anchor = self.control.read_anchor()
310
+ anchor["journal_sequence"] = pending[-1]["sequence"]
311
+ anchor["journal_head"] = hashlib.sha256(
312
+ self.control.sign(pending[-1]).encode()
313
+ ).hexdigest()
314
+ self.control.anchor(anchor)
315
+ self.anchor = anchor
316
+ yield decision
317
+ self.fault("before_commit")
318
+ decision.check(self.clock)
319
+ clock_started = time.monotonic()
320
+ serial = self.connection.execute(
321
+ "SELECT memoryking.next_commit_serial(%s,%s)", (self.tenant, MAX_COUNTER)
322
+ ).fetchone()
323
+ if serial is None or serial[0] is None:
324
+ raise LocalError("counter_exhausted")
325
+ clock_locked = time.monotonic()
326
+ position = self.db.execute(
327
+ "SELECT position FROM tenants WHERE tenant=?", (self.tenant,)
328
+ ).fetchone()[0]
329
+ decision.check(self.clock)
330
+ committed = {
331
+ "commit_serial": int(serial[0]),
332
+ "position": position,
333
+ "last_utc": self.last_utc,
334
+ }
335
+ self.committed = committed
336
+ committed_ok = True
337
+ self.fault("after_commit")
338
+ decision.check(self.clock)
339
+ finally:
340
+ self.active = False
341
+ metric = {
342
+ "transaction_ms": (time.monotonic() - started) * 1000,
343
+ "committed": float(committed_ok),
344
+ }
345
+ if locked is not None:
346
+ metric["gate_wait_ms"] = (locked - started) * 1000
347
+ if clock_started is not None and clock_locked is not None:
348
+ metric["clock_wait_ms"] = (clock_locked - clock_started) * 1000
349
+ self.metrics.append(metric)
350
+ spans = getattr(self.timings, "items", None)
351
+ if spans is not None:
352
+ spans.append(
353
+ {
354
+ "lock_wait_ms": metric.get("gate_wait_ms", 0.0),
355
+ "transaction_ms": metric["transaction_ms"],
356
+ }
357
+ )
358
+
359
+ def _event(self, tenant: str, kind: str, subject: str, at: int, actor: str = "system") -> int:
360
+ if self.release_only or tenant != self.tenant:
361
+ raise LocalError("exclusive_gate_required")
362
+ return super()._event(tenant, kind, subject, at, actor)
363
+
364
+ def _journal(self, action: dict[str, Any]) -> dict[str, Any]:
365
+ if self.release_only or action["tenant"] != self.tenant:
366
+ raise LocalError("exclusive_gate_required")
367
+ with self.control.locked():
368
+ self.anchor = self.control.read_anchor()
369
+ return super()._journal(action)
370
+
371
+ def _expose(self) -> None:
372
+ if not self.healthy or self.committed is None:
373
+ raise LocalError("recovery_required")
374
+ started = time.monotonic()
375
+ try:
376
+ with self.control.locked():
377
+ anchor = self.control.read_anchor()
378
+ if anchor["state"] != "active" or anchor["incarnation"] != self.incarnation:
379
+ raise LocalError("history_changed")
380
+ self.fault("before_anchor")
381
+ anchor["frontiers"][self.tenant] = max(
382
+ anchor["frontiers"].get(self.tenant, 0), self.committed["position"]
383
+ )
384
+ for key in ("commit_serial", "last_utc"):
385
+ anchor[key] = max(anchor[key], self.committed[key])
386
+ self.control.anchor(anchor)
387
+ self.anchor = anchor
388
+ self.fault("after_anchor")
389
+ if self.metrics:
390
+ self.metrics[-1]["anchor_ms"] = (time.monotonic() - started) * 1000
391
+ except BaseException:
392
+ self.healthy = False
393
+ raise
394
+
395
+ def gc(self) -> int:
396
+ # The exclusive gate prevents deleting a durable staging blob before adoption.
397
+ if self.release_only:
398
+ raise LocalError("exclusive_gate_required")
399
+ with self.transaction():
400
+ live = {
401
+ row[0]
402
+ for row in self.db.execute(
403
+ "SELECT blob FROM observations WHERE tenant=? AND blob IS NOT NULL",
404
+ (self.tenant,),
405
+ )
406
+ }
407
+ directory = self.root / "blobs" / self.tenant
408
+ removed = 0
409
+ if directory.exists():
410
+ private_dir(directory)
411
+ for path in directory.iterdir():
412
+ private_file(path)
413
+ if path.name not in live:
414
+ path.unlink()
415
+ removed += 1
416
+ sync_dir(directory)
417
+ return removed
418
+
419
+ def backup(self, destination: Path) -> dict[str, Any]:
420
+ raise LocalError("shared_backup_command_required")
421
+
422
+ @classmethod
423
+ def restore(cls, *args: Any, **kwargs: Any) -> Any:
424
+ raise LocalError("shared_restore_command_required")
425
+
426
+ @classmethod
427
+ def initialize(cls, *args: Any, **kwargs: Any) -> Any:
428
+ raise LocalError("shared_migration_command_required")
@@ -0,0 +1,12 @@
1
+ CREATE TABLE IF NOT EXISTS session_summaries (
2
+ tenant TEXT NOT NULL REFERENCES tenants, id TEXT NOT NULL, project TEXT NOT NULL,
3
+ task TEXT NOT NULL, stream TEXT NOT NULL, checkpoint TEXT NOT NULL, revision BIGINT NOT NULL,
4
+ principal TEXT NOT NULL, incarnation TEXT NOT NULL, method TEXT NOT NULL, text TEXT NOT NULL,
5
+ readers TEXT NOT NULL, created BIGINT NOT NULL, expires BIGINT NOT NULL,
6
+ PRIMARY KEY(tenant,id));
7
+ CREATE INDEX IF NOT EXISTS session_summaries_checkpoint ON session_summaries(tenant,checkpoint,created);
8
+ ALTER TABLE session_summaries ENABLE ROW LEVEL SECURITY;
9
+ ALTER TABLE session_summaries FORCE ROW LEVEL SECURITY;
10
+ CREATE POLICY tenant_isolation ON session_summaries
11
+ USING (tenant = current_setting('memoryking.tenant',true))
12
+ WITH CHECK (tenant = current_setting('memoryking.tenant',true));
@@ -0,0 +1,20 @@
1
+ CREATE TABLE IF NOT EXISTS source_trust (
2
+ tenant TEXT NOT NULL REFERENCES tenants, project TEXT NOT NULL, source TEXT NOT NULL,
3
+ level TEXT NOT NULL, decided_by TEXT NOT NULL, decided BIGINT NOT NULL,
4
+ PRIMARY KEY(tenant,project,source));
5
+ ALTER TABLE source_trust ENABLE ROW LEVEL SECURITY;
6
+ ALTER TABLE source_trust FORCE ROW LEVEL SECURITY;
7
+ CREATE POLICY tenant_isolation ON source_trust
8
+ USING (tenant = current_setting('memoryking.tenant',true))
9
+ WITH CHECK (tenant = current_setting('memoryking.tenant',true));
10
+ CREATE TABLE IF NOT EXISTS observation_holds (
11
+ tenant TEXT NOT NULL REFERENCES tenants, id TEXT NOT NULL, project TEXT NOT NULL,
12
+ reason TEXT NOT NULL, held BIGINT NOT NULL, state TEXT NOT NULL,
13
+ released_by TEXT, released BIGINT,
14
+ PRIMARY KEY(tenant,id));
15
+ CREATE INDEX IF NOT EXISTS observation_holds_open ON observation_holds(tenant,project,state,held);
16
+ ALTER TABLE observation_holds ENABLE ROW LEVEL SECURITY;
17
+ ALTER TABLE observation_holds FORCE ROW LEVEL SECURITY;
18
+ CREATE POLICY tenant_isolation ON observation_holds
19
+ USING (tenant = current_setting('memoryking.tenant',true))
20
+ WITH CHECK (tenant = current_setting('memoryking.tenant',true));