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,88 @@
|
|
|
1
|
+
"""Deterministic "where this left off" summaries from a checkpoint and recent activity.
|
|
2
|
+
|
|
3
|
+
The extractive summary quotes only the checkpoint body, which its readers may already see,
|
|
4
|
+
and counts or names recent observations and open operations without quoting them. It
|
|
5
|
+
is a convenience for a returning agent or an operator, never new evidence: every fact
|
|
6
|
+
in it is in the checkpoint, and the checkpoint stays the record.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
SUMMARY_LIMIT = 1200
|
|
14
|
+
METHOD = "extractive-v1"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _clip(text: str, limit: int) -> str:
|
|
18
|
+
text = " ".join(str(text).split())
|
|
19
|
+
if len(text) <= limit:
|
|
20
|
+
return text
|
|
21
|
+
cut = text[: limit - 1].rsplit(" ", 1)[0]
|
|
22
|
+
return (cut or text[: limit - 1]) + "…"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _sentence(text: str) -> str:
|
|
26
|
+
text = _clip(text, 320).rstrip()
|
|
27
|
+
return text if text.endswith((".", "!", "?", "…")) else text + "."
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def compose(
|
|
31
|
+
checkpoint: dict[str, Any],
|
|
32
|
+
observations: list[dict[str, Any]],
|
|
33
|
+
operations: list[dict[str, Any]],
|
|
34
|
+
) -> str:
|
|
35
|
+
"""Three sentences: where it stands, what was learned or tried, what comes next."""
|
|
36
|
+
objective = _clip(checkpoint.get("objective") or "the task", 160)
|
|
37
|
+
state = checkpoint.get("current_state") or ""
|
|
38
|
+
first = f"Working on {objective}: {state}" if state else f"Working on {objective}."
|
|
39
|
+
parts: list[str] = []
|
|
40
|
+
findings = checkpoint.get("findings") or []
|
|
41
|
+
failed = checkpoint.get("failed_attempts") or []
|
|
42
|
+
verification = checkpoint.get("verification") or []
|
|
43
|
+
if findings:
|
|
44
|
+
latest = findings[-1].get("text", "")
|
|
45
|
+
parts.append(
|
|
46
|
+
f"{len(findings)} finding{'s' if len(findings) != 1 else ''}, most recently: "
|
|
47
|
+
+ _clip(latest, 200)
|
|
48
|
+
)
|
|
49
|
+
if failed:
|
|
50
|
+
latest = failed[-1]
|
|
51
|
+
parts.append(
|
|
52
|
+
f"{len(failed)} failed attempt{'s' if len(failed) != 1 else ''}, do not repeat "
|
|
53
|
+
+ _clip(latest.get("action", ""), 120)
|
|
54
|
+
+ (f" ({_clip(latest.get('outcome', ''), 120)})" if latest.get("outcome") else "")
|
|
55
|
+
)
|
|
56
|
+
pending = [v for v in verification if v.get("result") not in {"passed", "pass"}]
|
|
57
|
+
if verification:
|
|
58
|
+
parts.append(
|
|
59
|
+
f"{len(verification) - len(pending)} of {len(verification)} verifications passed"
|
|
60
|
+
)
|
|
61
|
+
if observations:
|
|
62
|
+
sources = sorted({str(o.get("source", "unknown")) for o in observations})
|
|
63
|
+
parts.append(
|
|
64
|
+
f"{len(observations)} observation{'s' if len(observations) != 1 else ''} recorded "
|
|
65
|
+
f"since the checkpoint (from {', '.join(sources[:4])}"
|
|
66
|
+
+ (", …" if len(sources) > 4 else "")
|
|
67
|
+
+ ")"
|
|
68
|
+
)
|
|
69
|
+
second = _sentence("; ".join(parts)) if parts else "Nothing has been tried or recorded yet."
|
|
70
|
+
next_actions = checkpoint.get("next_actions") or []
|
|
71
|
+
blockers = checkpoint.get("blockers") or []
|
|
72
|
+
open_ops = [o for o in operations if o.get("reconciliation_required")]
|
|
73
|
+
tail: list[str] = []
|
|
74
|
+
if next_actions:
|
|
75
|
+
tail.append("Next: " + _clip(next_actions[0], 240))
|
|
76
|
+
if blockers:
|
|
77
|
+
tail.append(
|
|
78
|
+
f"{len(blockers)} blocker{'s' if len(blockers) != 1 else ''}: "
|
|
79
|
+
+ _clip(blockers[0].get("text", ""), 160)
|
|
80
|
+
)
|
|
81
|
+
if open_ops:
|
|
82
|
+
tail.append(
|
|
83
|
+
f"{len(open_ops)} uncertain operation{'s' if len(open_ops) != 1 else ''} to reconcile before repeating"
|
|
84
|
+
)
|
|
85
|
+
if pending:
|
|
86
|
+
tail.append(f"{len(pending)} verification{'s' if len(pending) != 1 else ''} still pending")
|
|
87
|
+
third = _sentence("; ".join(tail)) if tail else "No next action was recorded."
|
|
88
|
+
return _clip(" ".join((_sentence(first), second, third)), SUMMARY_LIMIT)
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""All-attempt token/cost accounting; unknown observations never become zero."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
from dataclasses import asdict, dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from memoryking.domain.local import LocalError
|
|
10
|
+
|
|
11
|
+
STAGES = frozenset(
|
|
12
|
+
{
|
|
13
|
+
"capture_extraction",
|
|
14
|
+
"compression",
|
|
15
|
+
"query_embedding",
|
|
16
|
+
"embedding_backfill",
|
|
17
|
+
"query_expansion",
|
|
18
|
+
"reranking",
|
|
19
|
+
"context_input",
|
|
20
|
+
"agent_output",
|
|
21
|
+
"handoff_reconstruction",
|
|
22
|
+
"retry",
|
|
23
|
+
"recovery",
|
|
24
|
+
}
|
|
25
|
+
)
|
|
26
|
+
STATUSES = frozenset({"started", "succeeded", "failed", "unknown"})
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class UsageRecord:
|
|
31
|
+
attempt: str
|
|
32
|
+
provider: str
|
|
33
|
+
fingerprint: str
|
|
34
|
+
stage: str
|
|
35
|
+
status: str
|
|
36
|
+
input_tokens: int | None
|
|
37
|
+
cached_input_tokens: int | None
|
|
38
|
+
output_tokens: int | None
|
|
39
|
+
cost_microusd: int | None
|
|
40
|
+
duration_ms: int
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def uncached_input_tokens(self) -> int | None:
|
|
44
|
+
if self.input_tokens is None or self.cached_input_tokens is None:
|
|
45
|
+
return None
|
|
46
|
+
return self.input_tokens - self.cached_input_tokens
|
|
47
|
+
|
|
48
|
+
def validate(self) -> None:
|
|
49
|
+
if self.stage not in STAGES or self.status not in STATUSES:
|
|
50
|
+
raise LocalError("usage_record_invalid")
|
|
51
|
+
if any(
|
|
52
|
+
not value or len(value) > 256
|
|
53
|
+
for value in (self.attempt, self.provider, self.fingerprint)
|
|
54
|
+
):
|
|
55
|
+
raise LocalError("usage_record_invalid")
|
|
56
|
+
for value in (
|
|
57
|
+
self.input_tokens,
|
|
58
|
+
self.cached_input_tokens,
|
|
59
|
+
self.output_tokens,
|
|
60
|
+
self.cost_microusd,
|
|
61
|
+
self.duration_ms,
|
|
62
|
+
):
|
|
63
|
+
if value is not None and (
|
|
64
|
+
type(value) is not int or not 0 <= value <= 9_007_199_254_740_991
|
|
65
|
+
):
|
|
66
|
+
raise LocalError("usage_record_invalid")
|
|
67
|
+
if self.duration_ms is None or (
|
|
68
|
+
self.input_tokens is not None
|
|
69
|
+
and self.cached_input_tokens is not None
|
|
70
|
+
and self.cached_input_tokens > self.input_tokens
|
|
71
|
+
):
|
|
72
|
+
raise LocalError("usage_record_invalid")
|
|
73
|
+
|
|
74
|
+
def document(self) -> dict[str, Any]:
|
|
75
|
+
self.validate()
|
|
76
|
+
return asdict(self)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def summarize(records: list[UsageRecord], successful_tasks: int) -> dict[str, Any]:
|
|
80
|
+
"""The caller supplies observed task outcomes; a successful API call is not a task.
|
|
81
|
+
|
|
82
|
+
Input tokens include cached tokens. Failed calls, retries and background work
|
|
83
|
+
remain in the numerator. Ratios stay exact integer pairs, not false precision.
|
|
84
|
+
"""
|
|
85
|
+
if (
|
|
86
|
+
type(successful_tasks) is not int
|
|
87
|
+
or not 0 <= successful_tasks <= 9_007_199_254_740_991
|
|
88
|
+
or len(records) > 100000
|
|
89
|
+
):
|
|
90
|
+
raise LocalError("usage_cohort_invalid")
|
|
91
|
+
seen: set[str] = set()
|
|
92
|
+
groups: dict[tuple[str, str], list[UsageRecord]] = defaultdict(list)
|
|
93
|
+
for record in records:
|
|
94
|
+
record.validate()
|
|
95
|
+
if record.attempt in seen:
|
|
96
|
+
raise LocalError("usage_attempt_duplicate")
|
|
97
|
+
seen.add(record.attempt)
|
|
98
|
+
groups[(record.provider, record.fingerprint)].append(record)
|
|
99
|
+
|
|
100
|
+
def total(items: list[UsageRecord], name: str) -> dict[str, int | None]:
|
|
101
|
+
values = [getattr(record, name) for record in items]
|
|
102
|
+
known = sum(value for value in values if value is not None)
|
|
103
|
+
if known > 9_007_199_254_740_991:
|
|
104
|
+
raise LocalError("usage_cohort_limit")
|
|
105
|
+
unknown = sum(value is None for value in values)
|
|
106
|
+
return {
|
|
107
|
+
"total": None if unknown else known,
|
|
108
|
+
"known_lower_bound": known,
|
|
109
|
+
"unknown_attempts": unknown,
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
def aggregate(items: list[UsageRecord]) -> dict[str, Any]:
|
|
113
|
+
inputs, outputs = total(items, "input_tokens"), total(items, "output_tokens")
|
|
114
|
+
known = int(inputs["known_lower_bound"] or 0) + int(outputs["known_lower_bound"] or 0)
|
|
115
|
+
if known > 9_007_199_254_740_991:
|
|
116
|
+
raise LocalError("usage_cohort_limit")
|
|
117
|
+
unknown = sum(
|
|
118
|
+
record.input_tokens is None or record.output_tokens is None for record in items
|
|
119
|
+
)
|
|
120
|
+
return {
|
|
121
|
+
"attempts": len(items),
|
|
122
|
+
"statuses": {
|
|
123
|
+
status: sum(i.status == status for i in items) for status in sorted(STATUSES)
|
|
124
|
+
},
|
|
125
|
+
"input_tokens": inputs,
|
|
126
|
+
"cached_input_tokens": total(items, "cached_input_tokens"),
|
|
127
|
+
"uncached_input_tokens": total(items, "uncached_input_tokens"),
|
|
128
|
+
"output_tokens": outputs,
|
|
129
|
+
"cost_microusd": total(items, "cost_microusd"),
|
|
130
|
+
"total_tokens": None if unknown else known,
|
|
131
|
+
"known_token_lower_bound": known,
|
|
132
|
+
"unknown_token_attempts": unknown,
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
result = aggregate(records)
|
|
136
|
+
result.update(
|
|
137
|
+
scope="all_observed_attempts_including_failures_and_background",
|
|
138
|
+
successful_tasks=successful_tasks,
|
|
139
|
+
tokens_per_successful_task={
|
|
140
|
+
"numerator": result["total_tokens"],
|
|
141
|
+
"denominator": successful_tasks,
|
|
142
|
+
"known_lower_bound_numerator": result["known_token_lower_bound"],
|
|
143
|
+
"status": "undefined_no_success"
|
|
144
|
+
if not successful_tasks
|
|
145
|
+
else "unknown_usage"
|
|
146
|
+
if result["unknown_token_attempts"]
|
|
147
|
+
else "observed",
|
|
148
|
+
},
|
|
149
|
+
providers=[
|
|
150
|
+
{
|
|
151
|
+
"provider": provider,
|
|
152
|
+
"fingerprint": model,
|
|
153
|
+
**aggregate(items),
|
|
154
|
+
"stages": {
|
|
155
|
+
stage: aggregate([i for i in items if i.stage == stage])
|
|
156
|
+
for stage in sorted({i.stage for i in items})
|
|
157
|
+
},
|
|
158
|
+
}
|
|
159
|
+
for (provider, model), items in sorted(groups.items())
|
|
160
|
+
],
|
|
161
|
+
transport_bytes="separate_metric_not_model_tokens",
|
|
162
|
+
)
|
|
163
|
+
return result
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Run the embedding worker inside the daemon for every configured partition.
|
|
2
|
+
|
|
3
|
+
With `serve --embedding-model DIR` the daemon loads the pinned local model once, embeds
|
|
4
|
+
each query it briefs on, and completes the indexing jobs of every experimental partition
|
|
5
|
+
through the same authorized claim and complete path an external worker uses. The loop
|
|
6
|
+
talks to the daemon's own socket with the owner credential it already holds, so nothing
|
|
7
|
+
runs outside the ordinary authorization checks.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import threading
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from memoryking.domain.local import LocalError
|
|
17
|
+
from memoryking.observability import event, failure
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class EmbeddingLoop:
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
store: Any,
|
|
24
|
+
socket: Path,
|
|
25
|
+
credential_file: Path,
|
|
26
|
+
provider: Any,
|
|
27
|
+
*,
|
|
28
|
+
interval: float = 3.0,
|
|
29
|
+
batch: int = 50,
|
|
30
|
+
):
|
|
31
|
+
self.store, self.socket, self.credential_file = store, socket, credential_file
|
|
32
|
+
self.provider, self.interval, self.batch = provider, interval, batch
|
|
33
|
+
self.clients: dict[str, Any] = {}
|
|
34
|
+
self.stopping = threading.Event()
|
|
35
|
+
self.thread = threading.Thread(target=self.run, name="memoryking-embeddings", daemon=True)
|
|
36
|
+
self.completed = 0
|
|
37
|
+
|
|
38
|
+
def start(self) -> None:
|
|
39
|
+
self.thread.start()
|
|
40
|
+
|
|
41
|
+
def stop(self) -> None:
|
|
42
|
+
self.stopping.set()
|
|
43
|
+
self.thread.join(timeout=10)
|
|
44
|
+
|
|
45
|
+
def projects(self) -> list[str]:
|
|
46
|
+
with self.store.lock:
|
|
47
|
+
rows = self.store.db.execute(
|
|
48
|
+
"SELECT DISTINCT project FROM embedding_partitions WHERE state='experimental' AND incarnation=? AND fingerprint=? ORDER BY project",
|
|
49
|
+
(self.store.incarnation, self.provider.fingerprint),
|
|
50
|
+
).fetchall()
|
|
51
|
+
return [row[0] for row in rows]
|
|
52
|
+
|
|
53
|
+
def client(self, project: str) -> Any:
|
|
54
|
+
from memoryking.sdk import LocalClient
|
|
55
|
+
|
|
56
|
+
if project not in self.clients:
|
|
57
|
+
self.clients[project] = LocalClient(self.socket, self.credential_file, project)
|
|
58
|
+
return self.clients[project]
|
|
59
|
+
|
|
60
|
+
def tick(self) -> int:
|
|
61
|
+
from memoryking.embedding_worker import run_once
|
|
62
|
+
|
|
63
|
+
done = 0
|
|
64
|
+
for project in self.projects():
|
|
65
|
+
try:
|
|
66
|
+
client = self.client(project)
|
|
67
|
+
while done < self.batch and not self.stopping.is_set():
|
|
68
|
+
result = run_once(client, self.provider)
|
|
69
|
+
if result.get("status") == "idle":
|
|
70
|
+
break
|
|
71
|
+
if (
|
|
72
|
+
result.get("status") not in {"complete", "indexed", "ok"}
|
|
73
|
+
and "error" in result
|
|
74
|
+
):
|
|
75
|
+
event(
|
|
76
|
+
"embeddings", "attempt_failed", project=project, error=result["error"]
|
|
77
|
+
)
|
|
78
|
+
if result.get("status") == "reconciliation_required":
|
|
79
|
+
break
|
|
80
|
+
done += 1
|
|
81
|
+
except LocalError as exc:
|
|
82
|
+
if exc.code in {"history_changed", "context_changed"}:
|
|
83
|
+
self.clients.pop(project, None)
|
|
84
|
+
event("embeddings", "paused", project=project, error=exc.code)
|
|
85
|
+
except OSError as exc:
|
|
86
|
+
failure("embeddings", exc, project=project)
|
|
87
|
+
self.completed += done
|
|
88
|
+
return done
|
|
89
|
+
|
|
90
|
+
def run(self) -> None:
|
|
91
|
+
event("embeddings", "ready", fingerprint=self.provider.fingerprint[:12])
|
|
92
|
+
while not self.stopping.is_set():
|
|
93
|
+
try:
|
|
94
|
+
if self.tick() == 0:
|
|
95
|
+
self.stopping.wait(self.interval)
|
|
96
|
+
except Exception as exc: # the loop must outlive any single failure
|
|
97
|
+
failure("embeddings", exc)
|
|
98
|
+
self.stopping.wait(self.interval)
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""One bounded local CPU embedding attempt through the authenticated SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from time import monotonic, time
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from memoryking.adapters.local_embeddings import LocalOnnxEmbedding
|
|
12
|
+
from memoryking.contracts.canonical import canonical_hash
|
|
13
|
+
from memoryking.domain.local import LocalError
|
|
14
|
+
from memoryking.sdk import LocalClient
|
|
15
|
+
from memoryking.shared_sdk import SharedClient
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def run_once(client: LocalClient, provider: LocalOnnxEmbedding) -> dict[str, Any]:
|
|
19
|
+
"""Load the model before calling. Never dispatch twice on one release/lease.
|
|
20
|
+
|
|
21
|
+
Authorization is evaluated by the server at claim, with a five-second
|
|
22
|
+
start deadline. Local CPU inference may finish afterward; commit checks the
|
|
23
|
+
current source, permissions, generation and 30-second lease again.
|
|
24
|
+
"""
|
|
25
|
+
if type(provider) is not LocalOnnxEmbedding:
|
|
26
|
+
raise LocalError("embedding_provider_unsupported")
|
|
27
|
+
|
|
28
|
+
def command(action: str, **args: Any) -> dict[str, Any]:
|
|
29
|
+
return client.embedding(
|
|
30
|
+
{
|
|
31
|
+
"version": 1,
|
|
32
|
+
"incarnation": client.binding[-1],
|
|
33
|
+
"action": action,
|
|
34
|
+
"args": {"project": client.project, **args},
|
|
35
|
+
}
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
start, utc_start = monotonic(), time()
|
|
39
|
+
job = command("claim", fingerprint=provider.fingerprint)
|
|
40
|
+
if job["job"] is None:
|
|
41
|
+
return {"status": "idle", "frontier": job["frontier"], "ready": job["ready"]}
|
|
42
|
+
input_tokens: int | None = 0
|
|
43
|
+
try:
|
|
44
|
+
if (
|
|
45
|
+
job["fingerprint"] != provider.fingerprint
|
|
46
|
+
or job["dimensions"] != provider.dimensions
|
|
47
|
+
or job["input_hash"] != canonical_hash(job["input"])
|
|
48
|
+
or job["egress"] != "local_cpu_only"
|
|
49
|
+
):
|
|
50
|
+
raise LocalError("embedding_release_invalid")
|
|
51
|
+
elapsed, utc = monotonic() - start, time()
|
|
52
|
+
if elapsed < 0 or utc < utc_start or utc * 1000 < job["evaluated_ms"]:
|
|
53
|
+
raise LocalError("clock_untrusted")
|
|
54
|
+
if abs((utc - utc_start) - elapsed) > 1:
|
|
55
|
+
raise LocalError("clock_untrusted")
|
|
56
|
+
if elapsed >= 5 or utc * 1000 >= job["deadline_ms"]:
|
|
57
|
+
raise LocalError("embedding_dispatch_expired")
|
|
58
|
+
# Unknown once inference starts: an exception is never zero token usage.
|
|
59
|
+
input_tokens = None
|
|
60
|
+
batch = provider.embed([job["input"]])
|
|
61
|
+
batch.validate(provider.fingerprint, provider.dimensions, [job["input"]])
|
|
62
|
+
input_tokens = batch.input_tokens
|
|
63
|
+
except Exception as exc:
|
|
64
|
+
reason = "provider_failure" if input_tokens is None else "interrupted"
|
|
65
|
+
try:
|
|
66
|
+
result = command(
|
|
67
|
+
"fail",
|
|
68
|
+
lease=job["lease"],
|
|
69
|
+
reason=reason,
|
|
70
|
+
input_tokens=input_tokens,
|
|
71
|
+
duration_ms=min(600000, int((monotonic() - start) * 1000)),
|
|
72
|
+
)
|
|
73
|
+
except LocalError as failure:
|
|
74
|
+
return {"status": "reconciliation_required", "error": failure.code}
|
|
75
|
+
return {
|
|
76
|
+
"status": "attempt_failed",
|
|
77
|
+
"job_status": result["status"],
|
|
78
|
+
"error": exc.code if isinstance(exc, LocalError) else "embedding_provider_failure",
|
|
79
|
+
"usage_attempt": result["usage_attempt"],
|
|
80
|
+
}
|
|
81
|
+
# An ambiguous completion is not a reason to run inference or mutate again.
|
|
82
|
+
# Its durable started usage remains unknown until explicitly reconciled.
|
|
83
|
+
try:
|
|
84
|
+
return command(
|
|
85
|
+
"complete",
|
|
86
|
+
lease=job["lease"],
|
|
87
|
+
fingerprint=batch.fingerprint,
|
|
88
|
+
input_hash=batch.input_hashes[0],
|
|
89
|
+
vector=batch.vectors[0],
|
|
90
|
+
input_tokens=input_tokens,
|
|
91
|
+
truncated=batch.truncated[0],
|
|
92
|
+
duration_ms=min(600000, int((monotonic() - start) * 1000)),
|
|
93
|
+
)
|
|
94
|
+
except LocalError as exc:
|
|
95
|
+
return {"status": "reconciliation_required", "error": exc.code}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def main() -> None:
|
|
99
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
100
|
+
source = parser.add_mutually_exclusive_group(required=True)
|
|
101
|
+
source.add_argument("--socket", type=Path)
|
|
102
|
+
source.add_argument("--shared-url")
|
|
103
|
+
parser.add_argument("--tenant")
|
|
104
|
+
parser.add_argument("--ca-file", type=Path)
|
|
105
|
+
parser.add_argument("--credential", type=Path, required=True)
|
|
106
|
+
parser.add_argument("--project", required=True)
|
|
107
|
+
parser.add_argument("--model", type=Path, required=True)
|
|
108
|
+
args = parser.parse_args()
|
|
109
|
+
if args.shared_url and not args.tenant:
|
|
110
|
+
parser.error("--tenant is required with --shared-url")
|
|
111
|
+
try:
|
|
112
|
+
provider = LocalOnnxEmbedding(args.model)
|
|
113
|
+
client = (
|
|
114
|
+
SharedClient(
|
|
115
|
+
args.shared_url,
|
|
116
|
+
args.tenant,
|
|
117
|
+
args.credential,
|
|
118
|
+
args.project,
|
|
119
|
+
ca_file=args.ca_file,
|
|
120
|
+
)
|
|
121
|
+
if args.shared_url
|
|
122
|
+
else LocalClient(args.socket, args.credential, args.project)
|
|
123
|
+
)
|
|
124
|
+
print(json.dumps(run_once(client, provider), sort_keys=True))
|
|
125
|
+
except LocalError as exc:
|
|
126
|
+
print(json.dumps({"error": exc.code}))
|
|
127
|
+
raise SystemExit(1) from exc
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
if __name__ == "__main__":
|
|
131
|
+
main()
|