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.
- memoryking/__init__.py +3 -0
- memoryking/__main__.py +1328 -0
- memoryking/adapters/__init__.py +1 -0
- memoryking/adapters/adapter_state.py +242 -0
- memoryking/adapters/anchor_schema.sql +7 -0
- memoryking/adapters/atlas.py +441 -0
- memoryking/adapters/browser_commands.py +125 -0
- memoryking/adapters/dashboard.py +510 -0
- memoryking/adapters/dense_search.py +86 -0
- memoryking/adapters/egress_policy.py +244 -0
- memoryking/adapters/egress_schema.sql +13 -0
- memoryking/adapters/embedding.schema.json +302 -0
- memoryking/adapters/embedding_store.py +469 -0
- memoryking/adapters/execution.py +369 -0
- memoryking/adapters/experience.py +423 -0
- memoryking/adapters/experience.schema.json +1508 -0
- memoryking/adapters/experience_records.py +239 -0
- memoryking/adapters/experience_schema.sql +23 -0
- memoryking/adapters/handoff.py +494 -0
- memoryking/adapters/handoff.schema.json +299 -0
- memoryking/adapters/handoff_schema.sql +17 -0
- memoryking/adapters/index_schema.sql +11 -0
- memoryking/adapters/inference.py +454 -0
- memoryking/adapters/inference.schema.json +541 -0
- memoryking/adapters/inspection.py +1128 -0
- memoryking/adapters/inspection.schema.json +568 -0
- memoryking/adapters/knowledge.schema.json +633 -0
- memoryking/adapters/knowledge_schema.sql +37 -0
- memoryking/adapters/knowledge_store.py +800 -0
- memoryking/adapters/legacy_snapshot.py +358 -0
- memoryking/adapters/legacy_tables.py +49 -0
- memoryking/adapters/local_contract.py +45 -0
- memoryking/adapters/local_embeddings.py +189 -0
- memoryking/adapters/local_files.py +242 -0
- memoryking/adapters/local_ipc.py +258 -0
- memoryking/adapters/local_schema.sql +44 -0
- memoryking/adapters/local_store.py +632 -0
- memoryking/adapters/local_wire.schema.json +7672 -0
- memoryking/adapters/models/minilm-l6-v2-onnx.json +57 -0
- memoryking/adapters/models/ms-marco-minilm-l6-v2-onnx.json +57 -0
- memoryking/adapters/optional_schema.sql +43 -0
- memoryking/adapters/plan_dashboard.py +51 -0
- memoryking/adapters/plans.py +253 -0
- memoryking/adapters/postgres_admin.py +300 -0
- memoryking/adapters/postgres_anchor_schema.sql +9 -0
- memoryking/adapters/postgres_counter.sql +14 -0
- memoryking/adapters/postgres_egress_schema.sql +15 -0
- memoryking/adapters/postgres_experience_schema.sql +39 -0
- memoryking/adapters/postgres_index_schema.sql +7 -0
- memoryking/adapters/postgres_optional_schema.sql +71 -0
- memoryking/adapters/postgres_pool.py +77 -0
- memoryking/adapters/postgres_recovery.py +525 -0
- memoryking/adapters/postgres_schema.sql +365 -0
- memoryking/adapters/postgres_sql.py +102 -0
- memoryking/adapters/postgres_store.py +428 -0
- memoryking/adapters/postgres_summary_schema.sql +12 -0
- memoryking/adapters/postgres_trust_schema.sql +20 -0
- memoryking/adapters/processing.schema.json +471 -0
- memoryking/adapters/processing_store.py +346 -0
- memoryking/adapters/projects.py +83 -0
- memoryking/adapters/proposals.py +238 -0
- memoryking/adapters/ranking.py +315 -0
- memoryking/adapters/repository.schema.json +664 -0
- memoryking/adapters/repository_git.py +264 -0
- memoryking/adapters/repository_schema.sql +25 -0
- memoryking/adapters/repository_store.py +960 -0
- memoryking/adapters/retrieval.py +1285 -0
- memoryking/adapters/retrieval.schema.json +553 -0
- memoryking/adapters/retrieval_schema.sql +10 -0
- memoryking/adapters/shared_control.py +40 -0
- memoryking/adapters/shared_dashboard.py +636 -0
- memoryking/adapters/shared_gateway.py +63 -0
- memoryking/adapters/shared_http.py +216 -0
- memoryking/adapters/shared_mcp.py +159 -0
- memoryking/adapters/shared_service.py +124 -0
- memoryking/adapters/stdio.py +193 -0
- memoryking/adapters/stdio.tools.json +6776 -0
- memoryking/adapters/summary_schema.sql +10 -0
- memoryking/adapters/team.py +253 -0
- memoryking/adapters/timeline.py +80 -0
- memoryking/adapters/token_count.py +55 -0
- memoryking/adapters/tokenizers/LICENSE +21 -0
- memoryking/adapters/tokenizers/cl100k_base.tiktoken +100256 -0
- memoryking/adapters/trust.py +123 -0
- memoryking/adapters/trust_schema.sql +13 -0
- memoryking/adapters/web/app.css +1251 -0
- memoryking/adapters/web/app.js +907 -0
- memoryking/adapters/web/brand.js +44 -0
- memoryking/adapters/web/crown-mono.svg +1 -0
- memoryking/adapters/web/crown.svg +8 -0
- memoryking/adapters/web/elephant.png +0 -0
- memoryking/adapters/web/favicon.svg +8 -0
- memoryking/adapters/web/graph-layout.js +52 -0
- memoryking/adapters/web/graph-worker.js +10 -0
- memoryking/adapters/web/graph.js +570 -0
- memoryking/adapters/web/index.html +208 -0
- memoryking/adapters/web/observatory.js +1208 -0
- memoryking/adapters/web/team.js +151 -0
- memoryking/adapters/web/wordmark.svg +1 -0
- memoryking/adapters/working.py +971 -0
- memoryking/adapters/working.schema.json +1717 -0
- memoryking/adapters/working_schema.sql +24 -0
- memoryking/application/__init__.py +1 -0
- memoryking/application/conformance.py +50 -0
- memoryking/application/legacy_import.py +337 -0
- memoryking/application/local_port.py +9 -0
- memoryking/application/storage.py +117 -0
- memoryking/application/store_core.py +1292 -0
- memoryking/backups.py +131 -0
- memoryking/contracts/__init__.py +6 -0
- memoryking/contracts/__main__.py +20 -0
- memoryking/contracts/canonical.py +88 -0
- memoryking/contracts/embedding.schema.json +302 -0
- memoryking/contracts/embedding_generated.py +65 -0
- memoryking/contracts/experience.schema.json +1508 -0
- memoryking/contracts/experience_generated.py +239 -0
- memoryking/contracts/generated.py +122 -0
- memoryking/contracts/handoff.schema.json +299 -0
- memoryking/contracts/handoff_generated.py +69 -0
- memoryking/contracts/inference.schema.json +541 -0
- memoryking/contracts/inference_generated.py +106 -0
- memoryking/contracts/processing.schema.json +471 -0
- memoryking/contracts/processing_generated.py +82 -0
- memoryking/contracts/py.typed +0 -0
- memoryking/contracts/repository.schema.json +664 -0
- memoryking/contracts/repository_generated.py +144 -0
- memoryking/contracts/retrieval.schema.json +553 -0
- memoryking/contracts/retrieval_generated.py +110 -0
- memoryking/contracts/schema.json +696 -0
- memoryking/contracts/validation.py +92 -0
- memoryking/contracts/working.schema.json +1717 -0
- memoryking/contracts/working_generated.py +291 -0
- memoryking/domain/__init__.py +1 -0
- memoryking/domain/anchors.py +97 -0
- memoryking/domain/briefing.py +108 -0
- memoryking/domain/briefing_text.py +222 -0
- memoryking/domain/checkpoint.py +118 -0
- memoryking/domain/compression.py +64 -0
- memoryking/domain/delta.py +129 -0
- memoryking/domain/embeddings.py +90 -0
- memoryking/domain/hints.py +465 -0
- memoryking/domain/http_status.py +45 -0
- memoryking/domain/learning.py +62 -0
- memoryking/domain/local.py +65 -0
- memoryking/domain/plans.py +140 -0
- memoryking/domain/repository.py +118 -0
- memoryking/domain/selectors.py +356 -0
- memoryking/domain/summary.py +88 -0
- memoryking/domain/usage.py +163 -0
- memoryking/embedding_loop.py +98 -0
- memoryking/embedding_worker.py +131 -0
- memoryking/harness.py +882 -0
- memoryking/harness_context.py +376 -0
- memoryking/hooks.py +171 -0
- memoryking/host_hooks.py +454 -0
- memoryking/lean.py +352 -0
- memoryking/memory_tool.py +776 -0
- memoryking/migration.py +194 -0
- memoryking/model_install.py +78 -0
- memoryking/observability.py +101 -0
- memoryking/observability_metrics.py +100 -0
- memoryking/profiles.py +150 -0
- memoryking/providers.py +330 -0
- memoryking/py.typed +0 -0
- memoryking/pytest_plugin.py +69 -0
- memoryking/reference_agent.py +152 -0
- memoryking/repository_worker.py +57 -0
- memoryking/resume_adapter.py +154 -0
- memoryking/sdk.py +302 -0
- memoryking/shared.py +301 -0
- memoryking/shared_sdk.py +101 -0
- memoryking/vault.py +176 -0
- memoryking-0.1.0.dist-info/METADATA +157 -0
- memoryking-0.1.0.dist-info/RECORD +179 -0
- memoryking-0.1.0.dist-info/WHEEL +5 -0
- memoryking-0.1.0.dist-info/entry_points.txt +7 -0
- memoryking-0.1.0.dist-info/licenses/LICENSE +202 -0
- memoryking-0.1.0.dist-info/licenses/NOTICE +12 -0
- memoryking-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,632 @@
|
|
|
1
|
+
"""SQLite implementation of P02. One owner; all policy/content transactions serialize.
|
|
2
|
+
|
|
3
|
+
The SQL here is deliberately adapter-local. Future backends must reproduce the contracts,
|
|
4
|
+
not translate SQLite locking pragmas or assume ORM portability proves correctness.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import secrets
|
|
14
|
+
import sqlite3
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
from collections.abc import Iterator
|
|
18
|
+
from contextlib import contextmanager
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any, Callable, Self
|
|
21
|
+
|
|
22
|
+
from memoryking.adapters.local_files import (
|
|
23
|
+
Control,
|
|
24
|
+
Ownership,
|
|
25
|
+
atomic,
|
|
26
|
+
private_dir,
|
|
27
|
+
private_file,
|
|
28
|
+
sync_dir,
|
|
29
|
+
)
|
|
30
|
+
from memoryking.application.storage import SQLiteDialect
|
|
31
|
+
from memoryking.application.store_core import ( # noqa: F401
|
|
32
|
+
ARTIFACT_BYTES_LIMIT,
|
|
33
|
+
ARTIFACT_LIMIT,
|
|
34
|
+
CAPABILITIES,
|
|
35
|
+
CAPACITY_LIMITS,
|
|
36
|
+
CONCURRENCY_LIMIT,
|
|
37
|
+
INTENT_LIMIT,
|
|
38
|
+
INTENT_SCOPE_LIMIT,
|
|
39
|
+
MAX_ATTEMPTS,
|
|
40
|
+
MAX_COUNTER,
|
|
41
|
+
OPEN_INTENT_STATES,
|
|
42
|
+
QUEUE_LIMIT,
|
|
43
|
+
RETRY_MS,
|
|
44
|
+
USAGE_LIMIT,
|
|
45
|
+
StoreCore,
|
|
46
|
+
identifier,
|
|
47
|
+
uid,
|
|
48
|
+
)
|
|
49
|
+
from memoryking.contracts.canonical import canonical_bytes
|
|
50
|
+
from memoryking.domain.local import (
|
|
51
|
+
Clock,
|
|
52
|
+
Decision,
|
|
53
|
+
LocalError,
|
|
54
|
+
SystemClock,
|
|
55
|
+
temporal_valid,
|
|
56
|
+
)
|
|
57
|
+
from memoryking.observability_metrics import Metrics
|
|
58
|
+
|
|
59
|
+
# Per-tenant capacity bounds. Each has a release path: the daemon drains audit jobs,
|
|
60
|
+
# retained artifacts evict oldest-first, only open intents count, and expired usage rows
|
|
61
|
+
# are pruned. `status` reports utilisation for every entry of CAPACITY_LIMITS.
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def recovery_admin(db: Any, at: int) -> tuple[str, str] | None:
|
|
65
|
+
"""The first tenant-wide grant that holds a currently valid admin capability."""
|
|
66
|
+
for row in db.execute(
|
|
67
|
+
"SELECT tenant,principal,capabilities,starts,expires FROM grants WHERE project='*' ORDER BY tenant,principal"
|
|
68
|
+
).fetchall():
|
|
69
|
+
capabilities = row["capabilities"]
|
|
70
|
+
if isinstance(capabilities, str):
|
|
71
|
+
capabilities = json.loads(capabilities)
|
|
72
|
+
if "admin" in capabilities and temporal_valid(at, row["starts"], row["expires"]):
|
|
73
|
+
return str(row["tenant"]), str(row["principal"])
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def paths(root: Path, control: Path) -> None:
|
|
78
|
+
if root.resolve() == control.resolve() or any(
|
|
79
|
+
a.resolve() in b.resolve().parents for a, b in ((root, control), (control, root))
|
|
80
|
+
):
|
|
81
|
+
raise LocalError("control_must_be_independent")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def connect(root: Path) -> sqlite3.Connection:
|
|
85
|
+
for name in ("store.sqlite", "store.sqlite-wal", "store.sqlite-shm"):
|
|
86
|
+
path = root / name
|
|
87
|
+
if path.exists() or path.is_symlink():
|
|
88
|
+
private_file(path)
|
|
89
|
+
db = sqlite3.connect(root / "store.sqlite", isolation_level=None, check_same_thread=False)
|
|
90
|
+
db.row_factory = sqlite3.Row
|
|
91
|
+
db.execute("PRAGMA foreign_keys=ON")
|
|
92
|
+
db.execute("PRAGMA journal_mode=WAL")
|
|
93
|
+
db.execute("PRAGMA synchronous=FULL")
|
|
94
|
+
db.execute("PRAGMA fullfsync=ON")
|
|
95
|
+
db.execute("PRAGMA checkpoint_fullfsync=ON")
|
|
96
|
+
db.execute("PRAGMA secure_delete=ON")
|
|
97
|
+
return db
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
__all__ = [
|
|
101
|
+
"ARTIFACT_BYTES_LIMIT",
|
|
102
|
+
"ARTIFACT_LIMIT",
|
|
103
|
+
"CAPABILITIES",
|
|
104
|
+
"CAPACITY_LIMITS",
|
|
105
|
+
"CONCURRENCY_LIMIT",
|
|
106
|
+
"INTENT_LIMIT",
|
|
107
|
+
"INTENT_SCOPE_LIMIT",
|
|
108
|
+
"MAX_ATTEMPTS",
|
|
109
|
+
"MAX_COUNTER",
|
|
110
|
+
"OPEN_INTENT_STATES",
|
|
111
|
+
"QUEUE_LIMIT",
|
|
112
|
+
"RETRY_MS",
|
|
113
|
+
"USAGE_LIMIT",
|
|
114
|
+
"LocalStore",
|
|
115
|
+
"StoreCore",
|
|
116
|
+
"connect",
|
|
117
|
+
"identifier",
|
|
118
|
+
"paths",
|
|
119
|
+
"recovery_admin",
|
|
120
|
+
"uid",
|
|
121
|
+
]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
SCHEMA_VERSION = 13 # the SQLite user_version the daemon migrates every store to
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class LocalStore(StoreCore):
|
|
128
|
+
def __init__(
|
|
129
|
+
self,
|
|
130
|
+
root: Path,
|
|
131
|
+
control: Path,
|
|
132
|
+
*,
|
|
133
|
+
clock: Clock | None = None,
|
|
134
|
+
fault: Callable[[str], None] | None = None,
|
|
135
|
+
):
|
|
136
|
+
paths(root, control)
|
|
137
|
+
private_dir(root)
|
|
138
|
+
private_dir(control)
|
|
139
|
+
self.root, self.control_path = root, control
|
|
140
|
+
self.owner = Ownership(root)
|
|
141
|
+
try:
|
|
142
|
+
self.control_owner = Ownership(control)
|
|
143
|
+
except Exception:
|
|
144
|
+
self.owner.close()
|
|
145
|
+
raise
|
|
146
|
+
self.clock = clock or SystemClock()
|
|
147
|
+
self.fault = fault or (lambda _: None)
|
|
148
|
+
self.lock = threading.RLock()
|
|
149
|
+
self.dialect = SQLiteDialect()
|
|
150
|
+
# Per-thread transaction timings, collected only while a traced request runs.
|
|
151
|
+
self.timings = threading.local()
|
|
152
|
+
self.healthy = True
|
|
153
|
+
self.retrieval_cache: dict[str, Any] = {}
|
|
154
|
+
self._last_housekeeping = 0
|
|
155
|
+
self.counters = Metrics()
|
|
156
|
+
# A loaded local embedding model lets briefings embed their own queries.
|
|
157
|
+
self.embedder: Any | None = None
|
|
158
|
+
self.reranker: Any | None = None
|
|
159
|
+
# A scheduled backup policy the daemon checks between requests.
|
|
160
|
+
self.backup_policy: Any | None = None
|
|
161
|
+
# Idle threshold for owner-derived session summaries; 0 disables.
|
|
162
|
+
self.summary_idle_ms = 0
|
|
163
|
+
self._last_summary_scan = 0
|
|
164
|
+
try:
|
|
165
|
+
self.control = Control(control)
|
|
166
|
+
self.anchor = self.control.read_anchor()
|
|
167
|
+
self.db: Any = connect(root)
|
|
168
|
+
self._load()
|
|
169
|
+
serial = int(
|
|
170
|
+
self.db.execute("SELECT value FROM meta WHERE key='commit_serial'").fetchone()[0]
|
|
171
|
+
)
|
|
172
|
+
if serial < self.anchor["commit_serial"]:
|
|
173
|
+
raise LocalError("recovery_required")
|
|
174
|
+
if (
|
|
175
|
+
self.anchor["state"] != "active"
|
|
176
|
+
or self.anchor["incarnation"] != self.incarnation
|
|
177
|
+
or self.anchor["store"] != self.store_id
|
|
178
|
+
):
|
|
179
|
+
raise LocalError("recovery_required")
|
|
180
|
+
for tenant, exposed in self.anchor["frontiers"].items():
|
|
181
|
+
row = self.db.execute(
|
|
182
|
+
"SELECT position FROM tenants WHERE tenant=?", (tenant,)
|
|
183
|
+
).fetchone()
|
|
184
|
+
if row is None or row[0] < exposed:
|
|
185
|
+
raise LocalError("recovery_required")
|
|
186
|
+
self._replay_journal()
|
|
187
|
+
self.last_utc = self.anchor.get("last_utc", 0)
|
|
188
|
+
self.gc()
|
|
189
|
+
except Exception:
|
|
190
|
+
if hasattr(self, "db"):
|
|
191
|
+
self.db.close()
|
|
192
|
+
self.control_owner.close()
|
|
193
|
+
self.owner.close()
|
|
194
|
+
raise
|
|
195
|
+
|
|
196
|
+
def _load(self) -> None:
|
|
197
|
+
# Migrations run in order up to SCHEMA_VERSION.
|
|
198
|
+
version = self.db.execute("PRAGMA user_version").fetchone()[0]
|
|
199
|
+
if version == 1:
|
|
200
|
+
self.db.executescript(Path(__file__).with_name("knowledge_schema.sql").read_text())
|
|
201
|
+
# Next migration is applied below.
|
|
202
|
+
if version in {1, 2}:
|
|
203
|
+
self.db.executescript(Path(__file__).with_name("retrieval_schema.sql").read_text())
|
|
204
|
+
if version in {1, 2, 3}:
|
|
205
|
+
self.db.executescript(Path(__file__).with_name("working_schema.sql").read_text())
|
|
206
|
+
if version in {1, 2, 3, 4}:
|
|
207
|
+
self.db.executescript(Path(__file__).with_name("handoff_schema.sql").read_text())
|
|
208
|
+
if version in {1, 2, 3, 4, 5}:
|
|
209
|
+
self.db.executescript(Path(__file__).with_name("repository_schema.sql").read_text())
|
|
210
|
+
if version in {1, 2, 3, 4, 5, 6}:
|
|
211
|
+
self.db.executescript(Path(__file__).with_name("optional_schema.sql").read_text())
|
|
212
|
+
if version in {1, 2, 3, 4, 5, 6, 7}:
|
|
213
|
+
self.db.executescript(Path(__file__).with_name("experience_schema.sql").read_text())
|
|
214
|
+
if version in {1, 2, 3, 4, 5, 6, 7, 8}:
|
|
215
|
+
self.db.executescript(Path(__file__).with_name("index_schema.sql").read_text())
|
|
216
|
+
if version in {1, 2, 3, 4, 5, 6, 7, 8, 9}:
|
|
217
|
+
self.db.executescript(Path(__file__).with_name("egress_schema.sql").read_text())
|
|
218
|
+
if version in {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}:
|
|
219
|
+
self.db.executescript(Path(__file__).with_name("summary_schema.sql").read_text())
|
|
220
|
+
if version in {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}:
|
|
221
|
+
self.db.executescript(Path(__file__).with_name("trust_schema.sql").read_text())
|
|
222
|
+
if version in {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}:
|
|
223
|
+
self.db.executescript(Path(__file__).with_name("anchor_schema.sql").read_text())
|
|
224
|
+
elif version != SCHEMA_VERSION:
|
|
225
|
+
raise LocalError("schema_unsupported")
|
|
226
|
+
meta = dict(self.db.execute("SELECT key,value FROM meta"))
|
|
227
|
+
self.store_id, self.incarnation = meta["store"], meta["incarnation"]
|
|
228
|
+
if self.store_id != self.control.store:
|
|
229
|
+
raise LocalError("recovery_required")
|
|
230
|
+
|
|
231
|
+
@classmethod
|
|
232
|
+
def initialize(
|
|
233
|
+
cls, root: Path, control: Path, tenant: str = "main", principal: str = "owner"
|
|
234
|
+
) -> Path:
|
|
235
|
+
identifier(tenant)
|
|
236
|
+
identifier(principal)
|
|
237
|
+
paths(root, control)
|
|
238
|
+
if root.exists() or control.exists():
|
|
239
|
+
raise LocalError("initialization_requires_new_directories")
|
|
240
|
+
private_dir(root, create=True)
|
|
241
|
+
private_dir(control, create=True)
|
|
242
|
+
private_dir(root / "blobs", create=True)
|
|
243
|
+
store, incarnation = uid("store"), uid("hist")
|
|
244
|
+
atomic(
|
|
245
|
+
control / "identity.json",
|
|
246
|
+
canonical_bytes({"store": store, "key": secrets.token_hex(32)}),
|
|
247
|
+
)
|
|
248
|
+
atomic(control / "journal", b"")
|
|
249
|
+
atomic(root / "store.sqlite", b"")
|
|
250
|
+
db = connect(root)
|
|
251
|
+
try:
|
|
252
|
+
db.executescript(Path(__file__).with_name("local_schema.sql").read_text())
|
|
253
|
+
db.execute("BEGIN IMMEDIATE")
|
|
254
|
+
db.executemany(
|
|
255
|
+
"INSERT INTO meta VALUES (?,?)",
|
|
256
|
+
[
|
|
257
|
+
("store", store),
|
|
258
|
+
("incarnation", incarnation),
|
|
259
|
+
("journal", "0"),
|
|
260
|
+
("commit_serial", "0"),
|
|
261
|
+
],
|
|
262
|
+
)
|
|
263
|
+
db.execute("INSERT INTO tenants(tenant) VALUES (?)", (tenant,))
|
|
264
|
+
db.execute(
|
|
265
|
+
"INSERT INTO grants VALUES (?,?,?,?,?,?)",
|
|
266
|
+
(tenant, principal, "*", json.dumps(sorted(CAPABILITIES)), None, None),
|
|
267
|
+
)
|
|
268
|
+
db.execute(
|
|
269
|
+
"INSERT INTO projections VALUES (?,?,?,?,?,?)",
|
|
270
|
+
(tenant, incarnation, "audit_probe", "v1", 1, 0),
|
|
271
|
+
)
|
|
272
|
+
db.commit()
|
|
273
|
+
db.executescript(Path(__file__).with_name("knowledge_schema.sql").read_text())
|
|
274
|
+
db.executescript(Path(__file__).with_name("retrieval_schema.sql").read_text())
|
|
275
|
+
db.executescript(Path(__file__).with_name("working_schema.sql").read_text())
|
|
276
|
+
db.executescript(Path(__file__).with_name("handoff_schema.sql").read_text())
|
|
277
|
+
db.executescript(Path(__file__).with_name("repository_schema.sql").read_text())
|
|
278
|
+
db.executescript(Path(__file__).with_name("optional_schema.sql").read_text())
|
|
279
|
+
db.executescript(Path(__file__).with_name("experience_schema.sql").read_text())
|
|
280
|
+
db.executescript(Path(__file__).with_name("index_schema.sql").read_text())
|
|
281
|
+
db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
|
282
|
+
finally:
|
|
283
|
+
db.close()
|
|
284
|
+
controller = Control(control)
|
|
285
|
+
controller.anchor(
|
|
286
|
+
{
|
|
287
|
+
"store": store,
|
|
288
|
+
"incarnation": incarnation,
|
|
289
|
+
"state": "active",
|
|
290
|
+
"frontiers": {},
|
|
291
|
+
"journal_sequence": 0,
|
|
292
|
+
"journal_head": "0" * 64,
|
|
293
|
+
"last_utc": 0,
|
|
294
|
+
"commit_serial": 0,
|
|
295
|
+
}
|
|
296
|
+
)
|
|
297
|
+
token = controller.sign(
|
|
298
|
+
{
|
|
299
|
+
"kind": "credential",
|
|
300
|
+
"store": store,
|
|
301
|
+
"incarnation": incarnation,
|
|
302
|
+
"tenant": tenant,
|
|
303
|
+
"principal": principal,
|
|
304
|
+
}
|
|
305
|
+
)
|
|
306
|
+
atomic(control / "owner.credential", token.encode())
|
|
307
|
+
sync_dir(root)
|
|
308
|
+
sync_dir(control.parent)
|
|
309
|
+
return control / "owner.credential"
|
|
310
|
+
|
|
311
|
+
def close(self) -> None:
|
|
312
|
+
self.db.close()
|
|
313
|
+
self.control_owner.close()
|
|
314
|
+
self.owner.close()
|
|
315
|
+
|
|
316
|
+
def __enter__(self) -> Self:
|
|
317
|
+
return self
|
|
318
|
+
|
|
319
|
+
def __exit__(self, *args: Any) -> None:
|
|
320
|
+
self.close()
|
|
321
|
+
|
|
322
|
+
@contextmanager
|
|
323
|
+
def transaction(self) -> Iterator[Decision]:
|
|
324
|
+
spans = getattr(self.timings, "items", None)
|
|
325
|
+
waited = time.monotonic() if spans is not None else 0.0
|
|
326
|
+
with self.lock:
|
|
327
|
+
acquired = time.monotonic() if spans is not None else 0.0
|
|
328
|
+
try:
|
|
329
|
+
yield from self._transaction()
|
|
330
|
+
finally:
|
|
331
|
+
if spans is not None:
|
|
332
|
+
spans.append(
|
|
333
|
+
{
|
|
334
|
+
"lock_wait_ms": (acquired - waited) * 1000,
|
|
335
|
+
"transaction_ms": (time.monotonic() - acquired) * 1000,
|
|
336
|
+
}
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
def _transaction(self) -> Iterator[Decision]:
|
|
340
|
+
self.owner.check()
|
|
341
|
+
if not self.healthy:
|
|
342
|
+
raise LocalError("recovery_required")
|
|
343
|
+
self.db.execute("BEGIN IMMEDIATE")
|
|
344
|
+
try:
|
|
345
|
+
decision = self._now()
|
|
346
|
+
yield decision
|
|
347
|
+
self.fault("before_commit")
|
|
348
|
+
decision.check(self.clock)
|
|
349
|
+
if (
|
|
350
|
+
int(
|
|
351
|
+
self.db.execute("SELECT value FROM meta WHERE key='commit_serial'").fetchone()[
|
|
352
|
+
0
|
|
353
|
+
]
|
|
354
|
+
)
|
|
355
|
+
>= MAX_COUNTER
|
|
356
|
+
):
|
|
357
|
+
raise LocalError("counter_exhausted")
|
|
358
|
+
self.db.execute(
|
|
359
|
+
"UPDATE meta SET value=CAST(value AS INTEGER)+1 WHERE key='commit_serial'"
|
|
360
|
+
)
|
|
361
|
+
self.db.commit()
|
|
362
|
+
self.fault("after_commit")
|
|
363
|
+
decision.check(self.clock)
|
|
364
|
+
except BaseException:
|
|
365
|
+
try:
|
|
366
|
+
self.db.rollback()
|
|
367
|
+
applied = int(
|
|
368
|
+
self.db.execute("SELECT value FROM meta WHERE key='journal'").fetchone()[0]
|
|
369
|
+
)
|
|
370
|
+
if self.anchor["journal_sequence"] > applied:
|
|
371
|
+
self.healthy = False
|
|
372
|
+
except Exception:
|
|
373
|
+
# Never let cleanup mask the original failure; fail closed instead.
|
|
374
|
+
self.healthy = False
|
|
375
|
+
raise
|
|
376
|
+
|
|
377
|
+
def _expose(self) -> None:
|
|
378
|
+
"""Fsync outside-DB evidence before any acknowledgment/handle leaves the process."""
|
|
379
|
+
with self.lock:
|
|
380
|
+
self._expose_locked()
|
|
381
|
+
|
|
382
|
+
def _expose_locked(self) -> None:
|
|
383
|
+
if not self.healthy:
|
|
384
|
+
raise LocalError("recovery_required")
|
|
385
|
+
try:
|
|
386
|
+
self.fault("before_anchor")
|
|
387
|
+
self.anchor["frontiers"] = dict(self.db.execute("SELECT tenant,position FROM tenants"))
|
|
388
|
+
self.anchor["last_utc"] = self.last_utc
|
|
389
|
+
self.anchor["commit_serial"] = int(
|
|
390
|
+
self.db.execute("SELECT value FROM meta WHERE key='commit_serial'").fetchone()[0]
|
|
391
|
+
)
|
|
392
|
+
self.control.anchor(self.anchor)
|
|
393
|
+
self.fault("after_anchor")
|
|
394
|
+
except BaseException:
|
|
395
|
+
self.healthy = False
|
|
396
|
+
raise
|
|
397
|
+
|
|
398
|
+
def _replay_journal(self) -> None:
|
|
399
|
+
records = self.control.journal(self.anchor)
|
|
400
|
+
self.db.execute("BEGIN IMMEDIATE")
|
|
401
|
+
try:
|
|
402
|
+
for record in records:
|
|
403
|
+
self._apply(record, self.clock.utc_ms())
|
|
404
|
+
self.db.commit()
|
|
405
|
+
except Exception:
|
|
406
|
+
self.db.rollback()
|
|
407
|
+
raise
|
|
408
|
+
if records:
|
|
409
|
+
self.anchor["journal_sequence"] = records[-1]["sequence"]
|
|
410
|
+
self.anchor["journal_head"] = hashlib.sha256(
|
|
411
|
+
self.control.sign(records[-1]).encode()
|
|
412
|
+
).hexdigest()
|
|
413
|
+
self.control.anchor(self.anchor)
|
|
414
|
+
|
|
415
|
+
def gc(self) -> int:
|
|
416
|
+
with self.lock:
|
|
417
|
+
live = {
|
|
418
|
+
(row[0], row[1])
|
|
419
|
+
for row in self.db.execute(
|
|
420
|
+
"SELECT tenant,blob FROM observations WHERE blob IS NOT NULL"
|
|
421
|
+
)
|
|
422
|
+
}
|
|
423
|
+
removed = 0
|
|
424
|
+
for directory in (self.root / "blobs").iterdir():
|
|
425
|
+
private_dir(directory)
|
|
426
|
+
for path in directory.iterdir():
|
|
427
|
+
private_file(path)
|
|
428
|
+
if (directory.name, path.name) not in live:
|
|
429
|
+
path.unlink()
|
|
430
|
+
removed += 1
|
|
431
|
+
sync_dir(directory)
|
|
432
|
+
return removed
|
|
433
|
+
|
|
434
|
+
def backup(self, destination: Path) -> dict[str, Any]:
|
|
435
|
+
"""Offline administrative method; intentionally absent from the agent socket."""
|
|
436
|
+
with self.lock:
|
|
437
|
+
self.owner.check()
|
|
438
|
+
if (
|
|
439
|
+
destination.exists()
|
|
440
|
+
or destination.resolve() in (self.root.resolve(), self.control_path.resolve())
|
|
441
|
+
or any(
|
|
442
|
+
p.resolve() in destination.resolve().parents
|
|
443
|
+
for p in (self.root, self.control_path)
|
|
444
|
+
)
|
|
445
|
+
):
|
|
446
|
+
raise LocalError("backup_requires_new_external_directory")
|
|
447
|
+
private_dir(destination, create=True)
|
|
448
|
+
atomic(destination / "store.sqlite", b"")
|
|
449
|
+
target = sqlite3.connect(destination / "store.sqlite")
|
|
450
|
+
try:
|
|
451
|
+
self.db.backup(target)
|
|
452
|
+
finally:
|
|
453
|
+
target.close()
|
|
454
|
+
with (destination / "store.sqlite").open("rb") as stream:
|
|
455
|
+
os.fsync(stream.fileno())
|
|
456
|
+
private_dir(destination / "blobs", create=True)
|
|
457
|
+
blobs: list[str] = []
|
|
458
|
+
for tenant, digest in self.db.execute(
|
|
459
|
+
"SELECT DISTINCT tenant,blob FROM observations WHERE blob IS NOT NULL"
|
|
460
|
+
):
|
|
461
|
+
relative = f"blobs/{tenant}/{digest}"
|
|
462
|
+
private_dir((destination / relative).parent, create=True)
|
|
463
|
+
raw = (self.root / relative).read_bytes()
|
|
464
|
+
if hashlib.sha256(raw).hexdigest() != digest:
|
|
465
|
+
raise LocalError("blob_corrupt")
|
|
466
|
+
atomic(destination / relative, raw)
|
|
467
|
+
blobs.append(relative)
|
|
468
|
+
manifest = {
|
|
469
|
+
"schema": 8,
|
|
470
|
+
"store": self.store_id,
|
|
471
|
+
"incarnation": self.incarnation,
|
|
472
|
+
"frontiers": dict(self.db.execute("SELECT tenant,position FROM tenants")),
|
|
473
|
+
"database_sha256": hashlib.sha256(
|
|
474
|
+
(destination / "store.sqlite").read_bytes()
|
|
475
|
+
).hexdigest(),
|
|
476
|
+
"blobs": sorted(blobs),
|
|
477
|
+
}
|
|
478
|
+
atomic(destination / "manifest", self.control.sign(manifest).encode())
|
|
479
|
+
sync_dir(destination)
|
|
480
|
+
sync_dir(destination.parent)
|
|
481
|
+
return manifest
|
|
482
|
+
|
|
483
|
+
@classmethod
|
|
484
|
+
def restore(
|
|
485
|
+
cls,
|
|
486
|
+
root: Path,
|
|
487
|
+
control: Path,
|
|
488
|
+
backup: Path,
|
|
489
|
+
*,
|
|
490
|
+
fault: Callable[[str], None] | None = None,
|
|
491
|
+
clock: Clock | None = None,
|
|
492
|
+
lost_anchor_journal_head: str | None = None,
|
|
493
|
+
) -> Path:
|
|
494
|
+
"""Explicit offline fresh-history activation. Missing anchor/journal fails closed."""
|
|
495
|
+
paths(root, control)
|
|
496
|
+
private_dir(root)
|
|
497
|
+
private_dir(control)
|
|
498
|
+
private_dir(backup)
|
|
499
|
+
owner, controller_owner = Ownership(root), None
|
|
500
|
+
hook = fault or (lambda _: None)
|
|
501
|
+
try:
|
|
502
|
+
controller_owner = Ownership(control)
|
|
503
|
+
controller = Control(control)
|
|
504
|
+
if lost_anchor_journal_head is not None:
|
|
505
|
+
if (control / "anchor").exists() or not re.fullmatch(
|
|
506
|
+
r"[a-f0-9]{64}", lost_anchor_journal_head
|
|
507
|
+
):
|
|
508
|
+
raise LocalError("recovery_checkpoint_invalid")
|
|
509
|
+
# Operator supplies the current head from an independently retained
|
|
510
|
+
# checkpoint. Deriving it from this possibly rolled-back journal is unsafe.
|
|
511
|
+
anchor = {
|
|
512
|
+
"store": controller.store,
|
|
513
|
+
"incarnation": "lost",
|
|
514
|
+
"state": "restoring",
|
|
515
|
+
"frontiers": {},
|
|
516
|
+
"commit_serial": 0,
|
|
517
|
+
"last_utc": 0,
|
|
518
|
+
"journal_sequence": 0,
|
|
519
|
+
"journal_head": "0" * 64,
|
|
520
|
+
}
|
|
521
|
+
records = controller.journal(anchor)
|
|
522
|
+
head = (
|
|
523
|
+
hashlib.sha256(controller.sign(records[-1]).encode()).hexdigest()
|
|
524
|
+
if records
|
|
525
|
+
else "0" * 64
|
|
526
|
+
)
|
|
527
|
+
if head != lost_anchor_journal_head:
|
|
528
|
+
raise LocalError("recovery_checkpoint_invalid")
|
|
529
|
+
anchor.update(journal_sequence=len(records), journal_head=head)
|
|
530
|
+
else:
|
|
531
|
+
anchor = controller.read_anchor()
|
|
532
|
+
controller.journal(anchor)
|
|
533
|
+
manifest = controller.verify_document(backup / "manifest")
|
|
534
|
+
if (
|
|
535
|
+
manifest.get("schema") not in {1, 2, 3, 4, 5, 6, 7, 8}
|
|
536
|
+
or manifest.get("store") != controller.store
|
|
537
|
+
):
|
|
538
|
+
raise LocalError("backup_invalid")
|
|
539
|
+
data = (backup / "store.sqlite").read_bytes()
|
|
540
|
+
if hashlib.sha256(data).hexdigest() != manifest["database_sha256"]:
|
|
541
|
+
raise LocalError("backup_invalid")
|
|
542
|
+
for relative in manifest["blobs"]:
|
|
543
|
+
if not re.fullmatch(r"blobs/[A-Za-z0-9_-]{1,96}/[a-f0-9]{64}", relative):
|
|
544
|
+
raise LocalError("backup_invalid")
|
|
545
|
+
if (
|
|
546
|
+
hashlib.sha256((backup / relative).read_bytes()).hexdigest()
|
|
547
|
+
!= relative.rsplit("/", 1)[1]
|
|
548
|
+
):
|
|
549
|
+
raise LocalError("backup_invalid")
|
|
550
|
+
anchor["state"] = "restoring"
|
|
551
|
+
anchor["reconciliation_required"] = True
|
|
552
|
+
anchor["history_loss"] = lost_anchor_journal_head is not None
|
|
553
|
+
controller.anchor(anchor)
|
|
554
|
+
hook("restore_fenced")
|
|
555
|
+
for suffix in ("-wal", "-shm"):
|
|
556
|
+
(root / ("store.sqlite" + suffix)).unlink(missing_ok=True)
|
|
557
|
+
atomic(root / "store.sqlite", data)
|
|
558
|
+
for relative in manifest["blobs"]:
|
|
559
|
+
private_dir((root / relative).parent, create=True)
|
|
560
|
+
atomic(root / relative, (backup / relative).read_bytes())
|
|
561
|
+
# Build an unavailable instance under the already-held ownership locks.
|
|
562
|
+
recovery = cls.__new__(cls)
|
|
563
|
+
recovery.root, recovery.control_path = root, control
|
|
564
|
+
recovery.owner, recovery.control_owner = owner, controller_owner
|
|
565
|
+
recovery.control, recovery.anchor = controller, anchor
|
|
566
|
+
recovery.clock, recovery.lock = clock or SystemClock(), threading.RLock()
|
|
567
|
+
recovery.db = connect(root)
|
|
568
|
+
try:
|
|
569
|
+
recovery._load()
|
|
570
|
+
recovery._replay_journal()
|
|
571
|
+
recovery.incarnation = uid("hist")
|
|
572
|
+
recovery.db.execute("BEGIN IMMEDIATE")
|
|
573
|
+
recovery.db.execute(
|
|
574
|
+
"UPDATE meta SET value=? WHERE key='incarnation'", (recovery.incarnation,)
|
|
575
|
+
)
|
|
576
|
+
recovery.db.execute("UPDATE retries SET result=NULL")
|
|
577
|
+
recovery.db.execute("DELETE FROM receipts")
|
|
578
|
+
recovery.db.execute(
|
|
579
|
+
"UPDATE rendered_artifacts SET state='retired',body=NULL,request_json=NULL,diagnostics=NULL,dependencies='[]'"
|
|
580
|
+
)
|
|
581
|
+
recovery.db.execute(
|
|
582
|
+
"UPDATE checkpoints SET state='retired',body=NULL,dependencies='[]'"
|
|
583
|
+
)
|
|
584
|
+
recovery.db.execute("UPDATE handoffs SET state='retired'")
|
|
585
|
+
recovery._retire_optional()
|
|
586
|
+
for (tenant,) in recovery.db.execute("SELECT tenant FROM tenants").fetchall():
|
|
587
|
+
recovery._reindex(tenant)
|
|
588
|
+
recovery.db.commit()
|
|
589
|
+
recovery.db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
|
590
|
+
recovery.gc()
|
|
591
|
+
hook("restore_before_activation")
|
|
592
|
+
anchor.update(
|
|
593
|
+
{
|
|
594
|
+
"state": "active",
|
|
595
|
+
"incarnation": recovery.incarnation,
|
|
596
|
+
"frontiers": dict(
|
|
597
|
+
recovery.db.execute("SELECT tenant,position FROM tenants")
|
|
598
|
+
),
|
|
599
|
+
"last_utc": recovery.clock.utc_ms(),
|
|
600
|
+
"commit_serial": int(
|
|
601
|
+
recovery.db.execute(
|
|
602
|
+
"SELECT value FROM meta WHERE key='commit_serial'"
|
|
603
|
+
).fetchone()[0]
|
|
604
|
+
),
|
|
605
|
+
}
|
|
606
|
+
)
|
|
607
|
+
# Only the independent OS owner can recover administrative credentials,
|
|
608
|
+
# and only a grant that currently carries admin rights may receive one.
|
|
609
|
+
admin = recovery_admin(recovery.db, recovery.clock.utc_ms())
|
|
610
|
+
if admin is None:
|
|
611
|
+
raise LocalError("recovery_admin_missing")
|
|
612
|
+
token = recovery._token("credential", tenant=admin[0], principal=admin[1])
|
|
613
|
+
atomic(control / "owner.credential", token.encode())
|
|
614
|
+
controller.anchor(anchor)
|
|
615
|
+
finally:
|
|
616
|
+
recovery.db.close()
|
|
617
|
+
return control / "owner.credential"
|
|
618
|
+
finally:
|
|
619
|
+
owner.close()
|
|
620
|
+
if controller_owner:
|
|
621
|
+
controller_owner.close()
|
|
622
|
+
|
|
623
|
+
def _retire_optional(self) -> None:
|
|
624
|
+
"""A restored history cannot reuse projected vectors, leases or adapter bases."""
|
|
625
|
+
self.db.execute("UPDATE ranking_state SET configuration=NULL,version=version+1")
|
|
626
|
+
self.db.execute("DELETE FROM adapter_bases")
|
|
627
|
+
self.db.execute("DELETE FROM embedding_items")
|
|
628
|
+
self.db.execute("DELETE FROM embedding_jobs")
|
|
629
|
+
self.db.execute(
|
|
630
|
+
"UPDATE embedding_partitions SET incarnation=?,state='disabled',generation=1,scheduled=0,frontier=0",
|
|
631
|
+
(self.incarnation,),
|
|
632
|
+
)
|