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,454 @@
|
|
|
1
|
+
"""Exact-request authorization for the trusted, local-only reference dispatcher."""
|
|
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.egress_policy import (
|
|
13
|
+
LOCAL_MODEL,
|
|
14
|
+
LOCAL_PROVIDER,
|
|
15
|
+
LOCAL_REVISION,
|
|
16
|
+
ProviderPolicy,
|
|
17
|
+
rank,
|
|
18
|
+
)
|
|
19
|
+
from memoryking.adapters.local_store import RETRY_MS, identifier, uid
|
|
20
|
+
from memoryking.adapters.retrieval import Retrieval
|
|
21
|
+
from memoryking.application.store_core import StoreCore
|
|
22
|
+
from memoryking.contracts.canonical import canonical_bytes, canonical_hash
|
|
23
|
+
from memoryking.domain.local import Decision, LocalError, Released
|
|
24
|
+
|
|
25
|
+
VALIDATOR = Draft202012Validator(
|
|
26
|
+
json.loads(Path(__file__).with_name("inference.schema.json").read_text())
|
|
27
|
+
)
|
|
28
|
+
EGRESS_REVISION = LOCAL_REVISION
|
|
29
|
+
AUDIT_GROUP_LIMIT = 4096 # records one millisecond can hold in a single listing
|
|
30
|
+
AUDIT_PAGE = 64
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Inference:
|
|
34
|
+
"""A credential with inference capability attests trusted host provenance.
|
|
35
|
+
|
|
36
|
+
The server verifies byte coverage and every referenced MemoryKing artifact. It
|
|
37
|
+
cannot infer whether an arbitrary host lied about a derived segment's origins.
|
|
38
|
+
The ordinary model-facing tools deliberately cannot invoke this surface.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, store: StoreCore):
|
|
42
|
+
self.s, self.db = store, store.db
|
|
43
|
+
self.r = Retrieval(store)
|
|
44
|
+
|
|
45
|
+
def _binding(self, credential: str, binding: dict[str, Any], at: int) -> dict[str, Any]:
|
|
46
|
+
"""Authorize the caller and check the binding against the store's current state."""
|
|
47
|
+
project = binding["project"]
|
|
48
|
+
who = self.s._auth(credential, "inference", project, at)
|
|
49
|
+
self.s._auth(credential, "read", project, at)
|
|
50
|
+
epochs = self.db.execute(
|
|
51
|
+
"SELECT policy_epoch,purge_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
|
|
52
|
+
).fetchone()
|
|
53
|
+
expected = {
|
|
54
|
+
"store": self.s.store_id,
|
|
55
|
+
"tenant": who["tenant"],
|
|
56
|
+
"principal": who["principal"],
|
|
57
|
+
"project": project,
|
|
58
|
+
"incarnation": self.s.incarnation,
|
|
59
|
+
"authorization_epoch": epochs[0],
|
|
60
|
+
"purge_epoch": epochs[1],
|
|
61
|
+
"delegation_chain": who.get("delegation_chain", []),
|
|
62
|
+
"egress_policy_revision": self.s.egress_revision(),
|
|
63
|
+
}
|
|
64
|
+
if any(binding[key] != value for key, value in expected.items()):
|
|
65
|
+
raise LocalError("inference_context_changed")
|
|
66
|
+
return who
|
|
67
|
+
|
|
68
|
+
def _provider(self, request: dict[str, Any]) -> ProviderPolicy | None:
|
|
69
|
+
"""The policy entry a request may leave through; None for the local recorder."""
|
|
70
|
+
if request["provider"] == LOCAL_PROVIDER:
|
|
71
|
+
if request["model"] != LOCAL_MODEL:
|
|
72
|
+
raise LocalError("egress_provider_denied")
|
|
73
|
+
return None
|
|
74
|
+
policy = self.s.egress_policy
|
|
75
|
+
entry: ProviderPolicy | None = (
|
|
76
|
+
policy.provider(request["provider"]) if policy is not None else None
|
|
77
|
+
)
|
|
78
|
+
if entry is None or not entry.allows(request["model"]):
|
|
79
|
+
raise LocalError("egress_provider_denied")
|
|
80
|
+
if len(canonical_bytes(request)) > entry.max_request_bytes:
|
|
81
|
+
raise LocalError("inference_request_limit")
|
|
82
|
+
return entry
|
|
83
|
+
|
|
84
|
+
def _classification(self, tenant: str, dependencies: list[dict[str, str]]) -> str:
|
|
85
|
+
"""The highest classification among the observations a receipt depended on.
|
|
86
|
+
|
|
87
|
+
A claim is traced to its evidence observations; working-state and procedure
|
|
88
|
+
dependencies carry no classification of their own and count as internal.
|
|
89
|
+
"""
|
|
90
|
+
highest = "public"
|
|
91
|
+
for dep in dependencies:
|
|
92
|
+
if dep["kind"] == "observation":
|
|
93
|
+
rows = self.db.execute(
|
|
94
|
+
"SELECT classification FROM observations WHERE tenant=? AND id=?",
|
|
95
|
+
(tenant, dep["id"]),
|
|
96
|
+
).fetchall()
|
|
97
|
+
elif dep["kind"] == "revision":
|
|
98
|
+
rows = self.db.execute(
|
|
99
|
+
"SELECT o.classification FROM evidence_spans e JOIN observations o ON o.tenant=e.tenant AND o.id=e.observation WHERE e.tenant=? AND e.revision=?",
|
|
100
|
+
(tenant, dep["id"]),
|
|
101
|
+
).fetchall()
|
|
102
|
+
else:
|
|
103
|
+
rows = []
|
|
104
|
+
found = [row[0] for row in rows] or ["internal"]
|
|
105
|
+
highest = max([highest, *found], key=rank)
|
|
106
|
+
return highest
|
|
107
|
+
|
|
108
|
+
def _validate(
|
|
109
|
+
self, credential: str, args: dict[str, Any], at: int
|
|
110
|
+
) -> tuple[dict[str, Any], ProviderPolicy | None, str]:
|
|
111
|
+
who = self._binding(credential, args["binding"], at)
|
|
112
|
+
project = args["binding"]["project"]
|
|
113
|
+
request, manifest = args["request"], args["manifest"]
|
|
114
|
+
if len(canonical_bytes(request)) > 98304:
|
|
115
|
+
raise LocalError("inference_request_limit")
|
|
116
|
+
provider = self._provider(request)
|
|
117
|
+
classification = "public"
|
|
118
|
+
checked: dict[str, bytes] = {}
|
|
119
|
+
for parts, proofs, handles in (
|
|
120
|
+
(request["messages"], manifest["segments"], False),
|
|
121
|
+
(request["state_handles"], manifest["handles"], True),
|
|
122
|
+
):
|
|
123
|
+
if len(parts) != len(proofs):
|
|
124
|
+
raise LocalError("inference_manifest_incomplete")
|
|
125
|
+
for part, proof in zip(parts, proofs, strict=True):
|
|
126
|
+
data = canonical_bytes(part) if handles else part["content"].encode()
|
|
127
|
+
if hashlib.sha256(data).hexdigest() != proof["sha256"]:
|
|
128
|
+
raise LocalError("inference_hash_mismatch")
|
|
129
|
+
artifacts, hosts = proof["artifacts"], proof["host_authorizations"]
|
|
130
|
+
if not artifacts and not hosts:
|
|
131
|
+
raise LocalError("inference_provenance_unknown")
|
|
132
|
+
if handles and proof["origin"] != "derived":
|
|
133
|
+
raise LocalError("inference_provenance_unknown")
|
|
134
|
+
for host in hosts:
|
|
135
|
+
if at >= host["expires_ms"]:
|
|
136
|
+
raise LocalError("host_authorization_expired")
|
|
137
|
+
classification = max(classification, host["classification"], key=rank)
|
|
138
|
+
for artifact in artifacts:
|
|
139
|
+
receipt_id = artifact["receipt"]
|
|
140
|
+
if receipt_id not in checked:
|
|
141
|
+
try:
|
|
142
|
+
row = self.r._artifact(who, project, receipt_id, at)
|
|
143
|
+
except LocalError as exc:
|
|
144
|
+
raise LocalError("inference_dependency_unavailable") from exc
|
|
145
|
+
checked[receipt_id] = bytes(row["body"])
|
|
146
|
+
classification = max(
|
|
147
|
+
classification,
|
|
148
|
+
self._classification(who["tenant"], json.loads(row["dependencies"])),
|
|
149
|
+
key=rank,
|
|
150
|
+
)
|
|
151
|
+
if hashlib.sha256(checked[receipt_id]).hexdigest() != artifact["sha256"]:
|
|
152
|
+
raise LocalError("inference_hash_mismatch")
|
|
153
|
+
if proof["origin"] == "host" and (
|
|
154
|
+
artifacts or len(hosts) != 1 or hosts[0]["source_hash"] != proof["sha256"]
|
|
155
|
+
):
|
|
156
|
+
raise LocalError("inference_provenance_unknown")
|
|
157
|
+
if proof["origin"] == "memory" and (
|
|
158
|
+
hosts or len(artifacts) != 1 or checked[artifacts[0]["receipt"]] != data
|
|
159
|
+
):
|
|
160
|
+
raise LocalError("inference_hash_mismatch")
|
|
161
|
+
# The ceiling is enforced here, before any permit exists, so a restricted source
|
|
162
|
+
# can never be cited in a request the daemon authorizes for a remote provider.
|
|
163
|
+
if provider is not None and rank(classification) > rank(provider.max_classification):
|
|
164
|
+
raise LocalError("egress_classification_denied")
|
|
165
|
+
return who, provider, classification
|
|
166
|
+
|
|
167
|
+
def execute(self, credential: str, command: dict[str, Any]) -> Released:
|
|
168
|
+
if len(canonical_bytes(command)) > 131072 or not VALIDATOR.is_valid(command):
|
|
169
|
+
raise LocalError("invalid_request")
|
|
170
|
+
action, args = command["action"], command["args"]
|
|
171
|
+
receipt = uid("rcpt")
|
|
172
|
+
with self.s.transaction() as decision:
|
|
173
|
+
at = decision.evaluated_ms
|
|
174
|
+
if action in {"report", "audit"}:
|
|
175
|
+
raw, released, who, identifier, status = self._account(
|
|
176
|
+
credential, action, args, at, decision, receipt
|
|
177
|
+
)
|
|
178
|
+
self._receipt(who, receipt, raw, released, at, None)
|
|
179
|
+
position = self.s._event(
|
|
180
|
+
who["tenant"], "egress_" + status, identifier, at, who["principal"]
|
|
181
|
+
)
|
|
182
|
+
self.s._enqueue(who["tenant"], position, None, who["principal"])
|
|
183
|
+
self.s.fault("after_validation")
|
|
184
|
+
released.check(self.s.clock)
|
|
185
|
+
self.s._expose()
|
|
186
|
+
return Released(raw, released, self.s.clock, receipt)
|
|
187
|
+
who, provider, classification = self._validate(credential, args, at)
|
|
188
|
+
hashes = {
|
|
189
|
+
key + "_hash": canonical_hash(args[key])
|
|
190
|
+
for key in ("binding", "request", "manifest")
|
|
191
|
+
}
|
|
192
|
+
self.db.execute(
|
|
193
|
+
"DELETE FROM retries WHERE namespace='inference-v1' AND expires<=?", (at,)
|
|
194
|
+
)
|
|
195
|
+
if action == "authorize":
|
|
196
|
+
count = self.db.execute(
|
|
197
|
+
"SELECT count(*) FROM retries WHERE tenant=? AND namespace='inference-v1'",
|
|
198
|
+
(who["tenant"],),
|
|
199
|
+
).fetchone()[0]
|
|
200
|
+
if count >= 1024:
|
|
201
|
+
raise LocalError("inference_capacity")
|
|
202
|
+
identifier = uid("permit")
|
|
203
|
+
fields = {
|
|
204
|
+
"id": identifier,
|
|
205
|
+
"tenant": who["tenant"],
|
|
206
|
+
"principal": who["principal"],
|
|
207
|
+
"evaluated_ms": at,
|
|
208
|
+
"deadline_ms": decision.deadline_ms,
|
|
209
|
+
**hashes,
|
|
210
|
+
}
|
|
211
|
+
permit = self.s._token("inference-permit", **fields)
|
|
212
|
+
self.db.execute(
|
|
213
|
+
"INSERT INTO retries VALUES (?,?,?,?,?,?,?,?,?,?)",
|
|
214
|
+
(
|
|
215
|
+
who["tenant"],
|
|
216
|
+
self.s.incarnation,
|
|
217
|
+
"inference-v1",
|
|
218
|
+
who["principal"],
|
|
219
|
+
"permit",
|
|
220
|
+
identifier,
|
|
221
|
+
canonical_hash(fields),
|
|
222
|
+
'{"state":"prepared"}',
|
|
223
|
+
None,
|
|
224
|
+
decision.deadline_ms,
|
|
225
|
+
),
|
|
226
|
+
)
|
|
227
|
+
result = {"permit": permit, "status": "authorized", **fields}
|
|
228
|
+
released = decision
|
|
229
|
+
elif action == "consume":
|
|
230
|
+
token = self.s._decode(args["permit"], "inference-permit")
|
|
231
|
+
if (token["tenant"], token["principal"]) != (
|
|
232
|
+
who["tenant"],
|
|
233
|
+
who["principal"],
|
|
234
|
+
) or any(token[key] != value for key, value in hashes.items()):
|
|
235
|
+
raise LocalError("inference_permit_mismatch")
|
|
236
|
+
if at < token["evaluated_ms"] or at >= token["deadline_ms"]:
|
|
237
|
+
raise LocalError("inference_permit_expired")
|
|
238
|
+
key = (
|
|
239
|
+
who["tenant"],
|
|
240
|
+
self.s.incarnation,
|
|
241
|
+
"inference-v1",
|
|
242
|
+
who["principal"],
|
|
243
|
+
"permit",
|
|
244
|
+
token["id"],
|
|
245
|
+
)
|
|
246
|
+
row = self.db.execute(
|
|
247
|
+
"SELECT result FROM retries WHERE tenant=? AND incarnation=? AND namespace=? AND principal=? AND operation=? AND key=?",
|
|
248
|
+
key,
|
|
249
|
+
).fetchone()
|
|
250
|
+
if row is None or row["result"] != '{"state":"prepared"}':
|
|
251
|
+
raise LocalError("inference_permit_consumed")
|
|
252
|
+
self.db.execute(
|
|
253
|
+
"UPDATE retries SET result=? WHERE tenant=? AND incarnation=? AND namespace=? AND principal=? AND operation=? AND key=?",
|
|
254
|
+
('{"state":"consumed"}', *key),
|
|
255
|
+
)
|
|
256
|
+
identifier = token["id"]
|
|
257
|
+
result = {
|
|
258
|
+
"status": "consumed",
|
|
259
|
+
"id": identifier,
|
|
260
|
+
"evaluated_ms": token["evaluated_ms"],
|
|
261
|
+
"deadline_ms": token["deadline_ms"],
|
|
262
|
+
**hashes,
|
|
263
|
+
}
|
|
264
|
+
if provider is not None:
|
|
265
|
+
# The audit record is the fact of departure; the host completes it
|
|
266
|
+
# with a report, and a host that dies leaves it pending, truthfully.
|
|
267
|
+
policy = self.s.egress_policy
|
|
268
|
+
self.db.execute(
|
|
269
|
+
"INSERT INTO egress_audit VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
|
270
|
+
(
|
|
271
|
+
who["tenant"],
|
|
272
|
+
identifier,
|
|
273
|
+
who["principal"],
|
|
274
|
+
args["binding"]["project"],
|
|
275
|
+
self.s.incarnation,
|
|
276
|
+
provider.name,
|
|
277
|
+
args["request"]["model"],
|
|
278
|
+
provider.host,
|
|
279
|
+
str(policy.revision) if policy is not None else EGRESS_REVISION,
|
|
280
|
+
hashes["request_hash"],
|
|
281
|
+
hashes["manifest_hash"],
|
|
282
|
+
json.dumps(args["manifest"], separators=(",", ":"), sort_keys=True),
|
|
283
|
+
classification,
|
|
284
|
+
len(canonical_bytes(args["request"])),
|
|
285
|
+
at,
|
|
286
|
+
token["deadline_ms"],
|
|
287
|
+
"pending",
|
|
288
|
+
None,
|
|
289
|
+
None,
|
|
290
|
+
None,
|
|
291
|
+
None,
|
|
292
|
+
None,
|
|
293
|
+
at + RETRY_MS,
|
|
294
|
+
),
|
|
295
|
+
)
|
|
296
|
+
result["audit"] = identifier
|
|
297
|
+
released = Decision(at, decision.monotonic_ms, token["deadline_ms"])
|
|
298
|
+
else:
|
|
299
|
+
identifier = uid("validation")
|
|
300
|
+
result = {
|
|
301
|
+
"status": "validated",
|
|
302
|
+
"id": identifier,
|
|
303
|
+
"evaluated_ms": at,
|
|
304
|
+
"deadline_ms": decision.deadline_ms,
|
|
305
|
+
**hashes,
|
|
306
|
+
}
|
|
307
|
+
released = decision
|
|
308
|
+
raw = canonical_bytes({**result, "receipt": receipt})
|
|
309
|
+
epochs = (args["binding"]["authorization_epoch"], args["binding"]["purge_epoch"])
|
|
310
|
+
self._receipt(who, receipt, raw, released, at, epochs)
|
|
311
|
+
position = self.s._event(
|
|
312
|
+
who["tenant"], "inference_" + result["status"], identifier, at, who["principal"]
|
|
313
|
+
)
|
|
314
|
+
self.s._enqueue(who["tenant"], position, None, who["principal"])
|
|
315
|
+
self.s.fault("after_validation")
|
|
316
|
+
released.check(self.s.clock)
|
|
317
|
+
self.s._expose()
|
|
318
|
+
return Released(raw, released, self.s.clock, receipt)
|
|
319
|
+
|
|
320
|
+
def _receipt(
|
|
321
|
+
self,
|
|
322
|
+
who: dict[str, Any],
|
|
323
|
+
receipt: str,
|
|
324
|
+
raw: bytes,
|
|
325
|
+
released: Decision,
|
|
326
|
+
at: int,
|
|
327
|
+
epochs: tuple[int, int] | None,
|
|
328
|
+
) -> None:
|
|
329
|
+
if epochs is None:
|
|
330
|
+
epochs = self.db.execute(
|
|
331
|
+
"SELECT policy_epoch,purge_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
|
|
332
|
+
).fetchone()
|
|
333
|
+
self.db.execute(
|
|
334
|
+
"INSERT INTO receipts VALUES (?,?,?,?,?,?,?,?,?,?)",
|
|
335
|
+
(
|
|
336
|
+
who["tenant"],
|
|
337
|
+
receipt,
|
|
338
|
+
who["principal"],
|
|
339
|
+
self.s.incarnation,
|
|
340
|
+
at,
|
|
341
|
+
released.deadline_ms,
|
|
342
|
+
*epochs,
|
|
343
|
+
hashlib.sha256(raw).hexdigest(),
|
|
344
|
+
"[]",
|
|
345
|
+
),
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
def _account(
|
|
349
|
+
self,
|
|
350
|
+
credential: str,
|
|
351
|
+
action: str,
|
|
352
|
+
args: dict[str, Any],
|
|
353
|
+
at: int,
|
|
354
|
+
decision: Decision,
|
|
355
|
+
receipt: str,
|
|
356
|
+
) -> tuple[bytes, Decision, dict[str, Any], str, str]:
|
|
357
|
+
"""Complete an audit record (`report`) or list a project's records (`audit`)."""
|
|
358
|
+
if action == "report":
|
|
359
|
+
who = self._binding(credential, args["binding"], at)
|
|
360
|
+
row = self.db.execute(
|
|
361
|
+
"SELECT status FROM egress_audit WHERE tenant=? AND id=? AND principal=? AND project=?",
|
|
362
|
+
(who["tenant"], args["permit"], who["principal"], args["binding"]["project"]),
|
|
363
|
+
).fetchone()
|
|
364
|
+
if row is None:
|
|
365
|
+
raise LocalError("egress_audit_missing")
|
|
366
|
+
if row["status"] != "pending":
|
|
367
|
+
raise LocalError("egress_audit_reported")
|
|
368
|
+
usage = args["usage"] or {}
|
|
369
|
+
self.db.execute(
|
|
370
|
+
"UPDATE egress_audit SET status=?,wire_hash=?,response_hash=?,input_tokens=?,output_tokens=?,reported=? WHERE tenant=? AND id=?",
|
|
371
|
+
(
|
|
372
|
+
args["status"],
|
|
373
|
+
args["wire_hash"],
|
|
374
|
+
args["response_hash"],
|
|
375
|
+
usage.get("input_tokens"),
|
|
376
|
+
usage.get("output_tokens"),
|
|
377
|
+
at,
|
|
378
|
+
who["tenant"],
|
|
379
|
+
args["permit"],
|
|
380
|
+
),
|
|
381
|
+
)
|
|
382
|
+
result = {"status": "reported", "permit": args["permit"], "outcome": args["status"]}
|
|
383
|
+
raw = canonical_bytes({**result, "receipt": receipt})
|
|
384
|
+
return raw, decision, who, args["permit"], args["status"]
|
|
385
|
+
project = identifier(args["project"])
|
|
386
|
+
who = self.s._auth(credential, "inference", project, at)
|
|
387
|
+
self.s._auth(credential, "read", project, at)
|
|
388
|
+
params: list[Any] = [who["tenant"], project, at]
|
|
389
|
+
cursor = ""
|
|
390
|
+
if args["before"] is not None:
|
|
391
|
+
cursor = " AND evaluated<?"
|
|
392
|
+
params.append(args["before"])
|
|
393
|
+
rows = self.db.execute(
|
|
394
|
+
"SELECT * FROM egress_audit WHERE tenant=? AND project=? AND expires>?"
|
|
395
|
+
+ cursor
|
|
396
|
+
+ " ORDER BY evaluated DESC,id DESC LIMIT ?",
|
|
397
|
+
(*params, AUDIT_PAGE + 1),
|
|
398
|
+
).fetchall()
|
|
399
|
+
# A page ends on a whole millisecond: records sharing the boundary instant move
|
|
400
|
+
# to the next page together, so an integer `before` cursor never drops any.
|
|
401
|
+
next_before = None
|
|
402
|
+
if len(rows) > AUDIT_PAGE:
|
|
403
|
+
boundary = rows[AUDIT_PAGE]["evaluated"]
|
|
404
|
+
shown = [row for row in rows[:AUDIT_PAGE] if row["evaluated"] > boundary]
|
|
405
|
+
if shown:
|
|
406
|
+
rows, next_before = shown, boundary + 1
|
|
407
|
+
else:
|
|
408
|
+
# One millisecond holds more than a page: return that whole group.
|
|
409
|
+
rows = self.db.execute(
|
|
410
|
+
"SELECT * FROM egress_audit WHERE tenant=? AND project=? AND expires>? AND evaluated=? ORDER BY id DESC LIMIT ?",
|
|
411
|
+
(who["tenant"], project, at, boundary, AUDIT_GROUP_LIMIT),
|
|
412
|
+
).fetchall()
|
|
413
|
+
next_before = boundary
|
|
414
|
+
items = []
|
|
415
|
+
for row in rows:
|
|
416
|
+
manifest = json.loads(row["manifest"])
|
|
417
|
+
receipts = sorted(
|
|
418
|
+
{
|
|
419
|
+
a["receipt"]
|
|
420
|
+
for proof in [*manifest["segments"], *manifest["handles"]]
|
|
421
|
+
for a in proof["artifacts"]
|
|
422
|
+
}
|
|
423
|
+
)
|
|
424
|
+
items.append(
|
|
425
|
+
{
|
|
426
|
+
"permit": row["id"],
|
|
427
|
+
"principal": row["principal"],
|
|
428
|
+
"provider": row["provider"],
|
|
429
|
+
"model": row["model"],
|
|
430
|
+
"host": row["host"],
|
|
431
|
+
"policy_revision": row["policy_revision"],
|
|
432
|
+
"status": row["status"],
|
|
433
|
+
"classification": row["classification"],
|
|
434
|
+
"request_bytes": row["request_bytes"],
|
|
435
|
+
"request_hash": row["request_hash"],
|
|
436
|
+
"manifest_hash": row["manifest_hash"],
|
|
437
|
+
"wire_hash": row["wire_hash"],
|
|
438
|
+
"response_hash": row["response_hash"],
|
|
439
|
+
"input_tokens": row["input_tokens"],
|
|
440
|
+
"output_tokens": row["output_tokens"],
|
|
441
|
+
"segments": len(manifest["segments"]),
|
|
442
|
+
"receipts": receipts,
|
|
443
|
+
"evaluated_ms": row["evaluated"],
|
|
444
|
+
"reported_ms": row["reported"],
|
|
445
|
+
"expires_ms": row["expires"],
|
|
446
|
+
}
|
|
447
|
+
)
|
|
448
|
+
result = {
|
|
449
|
+
"status": "listed",
|
|
450
|
+
"items": items,
|
|
451
|
+
"next_before": next_before,
|
|
452
|
+
"policy_revision": self.s.egress_revision(),
|
|
453
|
+
}
|
|
454
|
+
return canonical_bytes({**result, "receipt": receipt}), decision, who, "listing", "listed"
|