Add guarded Living Weights controller with graph and HTTP safety checks

This commit is contained in:
ashhart
2026-11-14 16:35:01 +00:00
committed by Ash
parent d6c4cce602
commit 6cf6d504c6
15 changed files with 1571 additions and 0 deletions
@@ -0,0 +1,28 @@
{
"schema_version": 1,
"model": "local-model",
"asserted_by_user": true,
"source": "User-approved fictional lab handbook, revision 1",
"facts": [
{
"subject": "Quillmoor Labs",
"relation": "headquarters",
"answer": "Sheffield",
"text": "Quillmoor Labs is headquartered in Sheffield.",
"evidence": "This is a fictional example. The operator attests to the claim, not the controller.",
"questions": [
"Where is Quillmoor Labs headquartered?",
"What city is the headquarters of Quillmoor Labs in?",
"Which city contains Quillmoor Labs headquarters?"
],
"near_misses": [
"Where is the Quillmoor Labs marketing team based?",
"Where is the unrelated Brackenforth Labs headquartered?"
]
}
],
"anchors": [
"What is two plus three?",
"Name the capital of Japan."
]
}
+80
View File
@@ -0,0 +1,80 @@
# Living Weights v2: guarded learning controller (experimental)
This change adds a dependency-free Python orchestration/evaluation layer for the **existing native Living Weights pocket learner**. It does not replace or generalize the native model weight trainer and does **not** make dense, MoE, hybrid or unsupported TensorFold models trainable. The boundary is deliberately explicit: the orchestration/quality contract is architecture-independent, whereas the model's actual parameter update and safe persistence remain the responsibility of `--slide`.
## Why this exists
Native TensorFold can write learned facts into safetensors, persist them across restarts, and delete selected facts. Its documented failure modes include paraphrase misses, near-subject leakage, interference and shrinking accuracy as fact count grows. The controller adds source attestation, positive/negative/anchor probing, regression checks against earlier committed facts, local write serialization, conflict rejection, durable receipts, and conservative native delete on a failed post-training gate. These are **additional checks**, not a substitute for the native learner's own held-out checks.
## How to run
Use an already running, authenticated TensorFold server, started with `--slide` and a copied supported checkpoint. Never teach a Hugging Face cache snapshot directly. Native hardware/model support is still constrained as documented in `docs/living-weights.md`.
```sh
PYTHONPATH=tools python3 -m living_weights_v2 plan docs/living-weights-v2-manifest.example.json
PYTHONPATH=tools python3 -m living_weights_v2 teach docs/living-weights-v2-manifest.example.json \
--base-url http://127.0.0.1:8080 --api-key-file "$HOME/models/slide-key"
PYTHONPATH=tools python3 -m living_weights_v2 evaluate docs/living-weights-v2-manifest.example.json \
--api-key-file "$HOME/models/slide-key"
PYTHONPATH=tools python3 -m living_weights_v2 status
PYTHONPATH=tools python3 -m unittest discover -s tests -p 'test_living_weights_v2*.py' -v
```
The example is fictional. Edit it for a real, user-approved lesson and correct probes. `asserted_by_user` means approval of the supplied claim; the tool does not automatically verify a document, URL, or third-party claim. The manifest hash is a provenance fingerprint, not a content authenticity signature.
The read-only `evaluate` command uses standard `/v1/models` and `/v1/chat/completions`, and can probe any endpoint implementing both routes. It has no weight-training capability and scores conservative affirmative answer presence rather than semantic correctness.
The controller expects one atomic statement per `facts[]` item and sends it separately to the current native `/v1/slide/learn` endpoint. Long documents must be decomposed into individually approved claims first. A native learner may extract more than one fact from a statement; the controller then refuses to certify ownership, stops and marks recovery required.
## Transaction and safety model
1. Check the server model list, native fact graph, already committed facts, and local unresolved writes.
2. Reject a contradictory subject/relation, repeated known fact, and graph entries left `deleting`.
3. Probe positive questions, hard negatives, unrelated anchors on the current model.
4. If all positive answers are already correct, report `already_answers` without writing any weights. This is *not* evidence that the model learned the fact.
5. Write an `inflight` intent to a local SQLite WAL ledger and call the native SSE learning route.
6. Require a completed stream, exactly one native `learned.recalled=true`, an explicit `saved` event, and attribution of exactly one new graph fact.
7. Probe every positive, negative, anchor, and previously committed positive question. Also verify the previously committed facts were healthy before beginning the write. All must pass. Conservatively compare stable replies on negatives and anchors exactly after case/whitespace normalization. This can reject harmless stylistic drift.
8. If post-gates fail, ask native batch deletion to remove the attributed fact. Report `rolled_back` only after every `forgot.deleted=true`, graph state `deleted`, and the pre-edit probe outputs are restored. If attribution, graph reads or deletion fail, mark `needs_recovery` and refuse more writes for that model.
`committed` certifies **only the observed test questions**, not generalized semantic learning. It is not a formal proof that no unrelated output changed. The native delete is not byte-exact inverse training. It may leave interference from later refits or 4-bit group rounding; check remaining facts and performance on real GPU hardware after recovery.
The process lock serializes writers using the same local ledger on POSIX hosts. It cannot prevent learning from other clients, other machines, or other ledger files. The native server's own one-at-a-time learning gate remains authoritative. Concurrent external writers can make the graph attribution ambiguous and force manual recovery.
An unhandled crash after recording `inflight` deliberately blocks further work. Inspect the native graph, journal and checkpoint rather than blindly repeating the fact. There is intentionally no `--force`, automatic ledger reset, or unfenced retry mechanism.
## Architecture portability contract
The controller is independent of model tensor shapes, expert layouts, kernel backends and quantization because it interacts through three narrow native capabilities: deterministic chat evaluation, fact-graph inspection, and transactional *best-effort* learning/deletion SSE APIs. Models without all three **must refuse write attempts**. It is not an API for generic gradient training.
To support dense and new MoE/hybrid families natively, follow a separate implementation program:
- Add per-family trainability descriptors (`supports_gradients`, legal writable tensors, quantizer, architecture revision, maximum update budget, known rollback semantics), rather than detecting support from model names.
- Introduce staged checkpoint updates with a native transaction ID, base-checkpoint digest and compare-and-swap commit; publish on-disk manifests that survive power loss.
- Add a general objective over token log-likelihood, paraphrase invariance, locality loss and retained-task rehearsal; keep a non-training verifier to avoid a model grading only itself.
- Implement real backend VJPs/gradients for dense MLP, shared experts, MoE routing and state-space components separately, qualified on Metal/CUDA/HIP with numerical checks. Never silently train a subset and claim complete family support.
- Test F16/BF16/FP32 plus actual deployment quantizers, including post-roundtrip regression tests. Persist native safetensors only after a staging verifier passes.
- Measure dense factual recall, cross-subject disambiguation, multi-hop reasoning, procedural skill transfer, deletions and out-of-domain regression from clean copies at 1, 10, 100 and 1,000 facts. Include seed variance, thinking modes, restart, backend transfer, latency, RAM/VRAM and write amplification.
These remaining items are not implemented in this PR. Until then, the new controller is an explicit, bounded quality/safety improvement over existing native `--slide` only.
## Operational constraints
- Python 3.10+ and a local POSIX lock. No third-party Python packages.
- Loopback IP is required by default; `--allow-remote` explicitly enables authenticated remote HTTP(S). Use TLS if remote.
- HTTP redirects are refused, including redirects on the same origin, so the key stays with the configured server.
- The native `/v1/slide/graph` JSON must expose a `facts` array with positive integer IDs and states. Unknown schema fails closed.
- Graph comparisons ignore native recheck counters/verdicts and computed links; other changes to existing facts require recovery.
- One controller instance per ledger/checkpoint; avoid direct concurrent `/v1/slide/learn` requests.
- Prompts are tested at temperature 0 with a fixed token cap; reasoning-on and adversarial role/system-message tests are future native integrations.
- Model capability remains native-authoritative. A `501` is an unsupported model, not something the controller attempts to bypass.
- SQLite receipts can contain personal fact text and model answers. Keep the ledger private, rotate it under a managed retention policy, and do not commit it to source control.
- No cross-device numerical or performance qualification was performed in this environment.
## Recommended follow-on PR sequencing
1. Native staged-edit transaction and recovery protocol, with deterministic commit/abort and crash fault injection.
2. Native architecture descriptors and trainability refusal matrix for dense, MoE, state-space and hybrid models.
3. General differentiable objective and retain/replay stream; numerical gradient verification for every backend.
4. Progressive long-document/curriculum learning and capacity planning, with measured 100/1,000-fact performance.
5. GUI learning observability, per-fact lineage/provenance and inspectable model-level evaluation receipts.
+54
View File
@@ -0,0 +1,54 @@
from __future__ import annotations
import json
import tempfile
import unittest
from contextlib import redirect_stdout, redirect_stderr
from io import StringIO
from pathlib import Path
from living_weights_v2.__main__ import main
class CliTests(unittest.TestCase):
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
self.manifest = Path(self.dir.name) / "lesson.json"
self.manifest.write_text(json.dumps({
"schema_version": 1, "model": "local-model", "asserted_by_user": True,
"source": "test", "anchors": ["What is 2+3?"],
"facts": [{"subject": "Quillmoor", "relation": "office", "answer": "Sheffield",
"text": "Quillmoor is in Sheffield.", "evidence": "test",
"questions": ["Where is Quillmoor?", "Which city has Quillmoor?"],
"near_misses": ["Where is Brackenforth?"]}]
}))
def tearDown(self):
self.dir.cleanup()
def test_plan(self):
output = StringIO()
with redirect_stdout(output):
result = main(["plan", str(self.manifest)])
self.assertEqual(result, 0)
parsed = json.loads(output.getvalue())
self.assertFalse(parsed["mutates_weights"])
self.assertEqual(parsed["facts"][0]["positive_count"], 2)
def test_status_empty_ledger(self):
output = StringIO()
with redirect_stdout(output):
result = main(["status", "--ledger", str(Path(self.dir.name) / "new.sqlite3")])
self.assertEqual(result, 0)
self.assertEqual(json.loads(output.getvalue()), [])
def test_bad_manifest_exits_nonzero(self):
stderr = StringIO()
with redirect_stderr(stderr):
result = main(["plan", str(Path(self.dir.name) / "missing.json")])
self.assertEqual(result, 4)
self.assertIn("living_weights_v2:", stderr.getvalue())
if __name__ == "__main__":
unittest.main()
+278
View File
@@ -0,0 +1,278 @@
from __future__ import annotations
import tempfile
import unittest
from copy import deepcopy
from pathlib import Path
from living_weights_v2.controller import Controller, LearningError, _changes
from living_weights_v2.ledger import Ledger, LedgerError, exclusive_file
from living_weights_v2.schema import Fact, Manifest
from living_weights_v2.transport import Event, TransportError
def fact(answer="Sheffield"):
return Fact("Quillmoor Labs", "headquarters", answer,
f"Quillmoor Labs is headquartered in {answer}.", "approved",
("Where is Quillmoor Labs?", "Which city is Quillmoor Labs in?"),
("Where is Brackenforth Labs?",))
def manifest(f):
return Manifest("local-model", True, (f,), ("What is two plus three?",), "approved handbook", "abcd" * 16)
class FakeClient:
def __init__(self):
self.records = {}
self.reply = "Unknown"
self.saved = True
self.recalled = True
self.emit_id = True
self.fail_delete = False
self.fail_on_chat_after = False
self.teach_count = 0
self.delete_count = 0
self.answer_anchors_after = "5"
self.extraneous_fact = False
def models(self):
return {"local-model"}
def graph(self):
return {k: dict(v) for k, v in self.records.items()}
def chat(self, model, question):
if self.teach_count and self.fail_on_chat_after:
raise TransportError("simulated connection drop after edit")
if "two plus three" in question:
return self.answer_anchors_after if self.teach_count else "5"
if "Brackenforth" in question:
return "Unknown"
if self.teach_count and not self.records.get(1, {}).get("state") == "deleted":
return self.reply if "Quillmoor" in question else "Unknown"
return "Unknown"
def teach(self, text):
self.teach_count += 1
if self.recalled:
self.records[1] = {"id": 1, "state": "learned", "text": text}
if self.extraneous_fact:
self.records[2] = {"id": 2, "state": "learned", "text": "other concurrent fact"}
return tuple(
[Event("learned", {"recalled": self.recalled, **({"id": 1} if self.emit_id else {})})]
+ ([Event("saved", {"files": 1})] if self.saved else [Event("failed", {"phase": "saving"})])
)
def delete(self, ids, reason):
self.delete_count += 1
if self.fail_delete:
return (Event("forgot", {"deleted": False}),)
for item_id in ids:
self.records[item_id]["state"] = "deleted"
return tuple(Event("forgot", {"deleted": True}) for _ in ids)
class ControllerTests(unittest.TestCase):
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
self.ledger = Ledger(Path(self.dir.name) / "ledger.sqlite3")
self.client = FakeClient()
self.controller = Controller(self.client, self.ledger)
def tearDown(self):
self.ledger.close()
self.dir.cleanup()
def test_success_and_idempotency(self):
self.client.reply = "Sheffield"
result = self.controller.teach(manifest(fact()))
self.assertEqual(result[0]["state"], "committed")
self.assertEqual(self.client.teach_count, 1)
self.assertEqual(len(self.ledger.retained("local-model")), 1)
with self.assertRaises(LedgerError):
self.controller.teach(manifest(fact()))
def test_native_rechecks_and_links_allow_two_committed_lessons(self):
first = fact()
second = Fact("Quillmoor Labs", "mascot", "Kestrel",
"Quillmoor Labs has a mascot called Kestrel.", "approved",
("What is Quillmoor Labs' mascot?", "Name Quillmoor Labs' mascot."),
("What is Brackenforth Labs' mascot?",))
class NativeGraphClient(FakeClient):
def graph(self):
return deepcopy(self.records)
def chat(self, model, question):
if "two plus three" in question:
return "5"
for item_id, lesson in enumerate((first, second), 1):
if question in lesson.questions and item_id in self.records:
return lesson.answer
return "Unknown"
def teach(self, text):
self.teach_count += 1
item_id = self.teach_count
for old in self.records.values():
old["checks"] += 1
old["recalled"] = True
old["links"].append(item_id)
self.records[item_id] = {"id": item_id, "state": "learned", "text": text,
"checks": 1, "recalled": True,
"links": list(range(1, item_id))}
return (Event("learned", {"id": item_id, "recalled": True}),
Event("saved", {"saved": True}))
client = NativeGraphClient()
plan = Manifest("local-model", True, (first, second), manifest(first).anchors, "approved", "sequence")
result = Controller(client, self.ledger).teach(plan)
self.assertEqual([r["state"] for r in result], ["committed", "committed"])
self.assertEqual(client.delete_count, 0)
self.assertEqual(len(self.ledger.retained("local-model")), 2)
self.assertEqual(result[1]["new_graph_ids"], [2])
self.assertEqual(result[1]["assessment"]["retained_failures"], ())
def test_graph_metadata_changes_preserve_new_id_detection(self):
before = {17: {"id": 17, "text": "old fact", "state": "learned",
"checks": 1, "recalled": True, "links": []}}
after = deepcopy(before)
after[17].update(checks=2, recalled=False, links=[18])
after[18] = {"id": 18, "text": "new fact", "state": "learned"}
self.assertEqual(_changes(before, after), [18])
def test_graph_identity_state_placement_and_unknown_changes_fail_closed(self):
original = {"id": 17, "text": "old fact", "source": "chat", "at": 123,
"state": "learned", "neurons": [{"layer": 1, "neuron": 2, "key": "gate"}]}
changes = {"id": 18, "text": "different fact", "source": "document", "at": 456,
"state": "deleted", "neurons": [], "unknown_field": "unexpected"}
for field, value in changes.items():
with self.subTest(field=field), self.assertRaises(LearningError):
_changes({17: original}, {17: {**original, field: value}})
with self.assertRaises(LearningError):
_changes({17: original}, {})
def test_graph_mutation_still_requires_recovery_without_deleting(self):
self.client.records[17] = {"id": 17, "state": "learned", "text": "old fact"}
teach = self.client.teach
def mutate(text):
events = teach(text)
self.client.records[17]["state"] = "deleted"
return events
self.client.teach = mutate
self.client.reply = "Sheffield"
result = self.controller.teach(manifest(fact()))
self.assertEqual(result[0]["state"], "needs_recovery")
self.assertEqual(self.client.delete_count, 0)
with self.assertRaises(LedgerError):
self.controller.teach(manifest(fact("Cambridge")))
def test_recheck_metadata_does_not_hide_retained_answer_regression(self):
old = Fact("Pinebridge Labs", "headquarters", "Cambridge",
"Pinebridge Labs is headquartered in Cambridge.", "approved",
("Where is Pinebridge Labs?", "Which city is Pinebridge Labs in?"),
("Where is an unrelated lab?",))
entry = self.ledger.begin("local-model", "earlier-manifest", old)
self.ledger.finish(entry, "committed", {})
self.client.records[17] = {"id": 17, "state": "learned", "text": old.text,
"checks": 1, "recalled": True, "links": []}
self.client.reply = "Sheffield"
chat, teach = self.client.chat, self.client.teach
def changed_chat(model, question):
if question in old.questions:
active = self.client.records.get(1, {}).get("state") == "learned"
return "Unknown" if active else old.answer
return chat(model, question)
def changed_teach(text):
events = teach(text)
self.client.records[17].update(checks=2, recalled=False, links=[1])
return events
self.client.chat, self.client.teach = changed_chat, changed_teach
result = self.controller.teach(manifest(fact()))[0]
self.assertEqual(result["state"], "rolled_back")
self.assertEqual(result["assessment"]["retained_failures"], old.questions)
self.assertEqual(self.client.delete_count, 1)
def test_paraphrase_failure_calls_native_delete(self):
self.client.reply = "Unknown"
result = self.controller.teach(manifest(fact()))
self.assertEqual(result[0]["state"], "rolled_back")
self.assertEqual(self.client.delete_count, 1)
self.assertEqual(self.client.records[1]["state"], "deleted")
def test_failed_delete_blocks_future_writes(self):
self.client.reply = "Unknown"
self.client.fail_delete = True
result = self.controller.teach(manifest(fact()))
self.assertEqual(result[0]["state"], "needs_recovery")
with self.assertRaises(LedgerError):
self.controller.teach(manifest(fact("Cambridge")))
def test_crash_after_write_is_durable_unknown(self):
self.client.reply = "Sheffield"
self.client.fail_on_chat_after = True
result = self.controller.teach(manifest(fact()))
self.assertEqual(result[0]["state"], "needs_recovery")
self.assertEqual(len(self.ledger.history("local-model")), 1)
def test_unknown_native_owner_fails_closed(self):
self.client.reply = "Sheffield"
self.client.emit_id = False
self.client.extraneous_fact = True
result = self.controller.teach(manifest(fact()))
self.assertEqual(result[0]["state"], "needs_recovery")
self.assertEqual(self.client.delete_count, 0)
def test_cannot_alter_preexisting_graph(self):
self.client.records = {17: {"id": 17, "state": "deleting", "text": "old"}}
with self.assertRaises(LearningError):
self.controller.teach(manifest(fact()))
def test_unsupported_model_refused(self):
f = fact()
plan = Manifest("different", True, (f,), ("What is two plus three?",), "source", "e" * 64)
with self.assertRaises(LearningError):
self.controller.teach(plan)
def test_answer_baseline_does_not_write(self):
self.client.reply = "Sheffield"
original_chat = self.client.chat
self.client.chat = lambda model, question: "Sheffield" if "Quillmoor" in question else original_chat(model, question)
result = self.controller.teach(manifest(fact()))
self.assertEqual(result[0]["state"], "already_answers")
self.assertEqual(self.client.teach_count, 0)
def test_native_rejected_no_graph_delta(self):
self.client.recalled = False
result = self.controller.teach(manifest(fact()))
self.assertEqual(result[0]["state"], "rejected")
self.assertEqual(self.client.delete_count, 0)
def test_conflicting_answer_same_subject_rejected(self):
self.client.reply = "Sheffield"
self.assertEqual(self.controller.teach(manifest(fact()))[0]["state"], "committed")
with self.assertRaises(LedgerError):
self.ledger.require_safe("local-model", fact("Cambridge"))
def test_regression_to_anchor_triggers_delete(self):
self.client.reply = "Sheffield"
self.client.answer_anchors_after = "four"
result = self.controller.teach(manifest(fact()))
self.assertEqual(result[0]["state"], "needs_recovery")
def test_file_lock_refuses_concurrent_writer(self):
lock = Path(self.dir.name) / "writing.lock"
with exclusive_file(lock):
with self.assertRaises(LedgerError):
with exclusive_file(lock):
pass
if __name__ == "__main__":
unittest.main()
+40
View File
@@ -0,0 +1,40 @@
from __future__ import annotations
import unittest
from living_weights_v2.evaluator import evaluate
from living_weights_v2.schema import Fact, Manifest
class ReadOnlyEvaluatorTests(unittest.TestCase):
def setUp(self):
fact = Fact("Quillmoor Labs", "headquarters", "Sheffield",
"Quillmoor Labs is headquartered in Sheffield.", "approved",
("Where is Quillmoor?", "Which city is Quillmoor in?"),
("Where is Brackenforth?",))
self.manifest = Manifest("model", True, (fact,), ("What is 2 plus 3?",), "source", "digest")
def test_scores_and_keeps_anchor(self):
class Client:
def chat(self, model, question):
if "Brackenforth" in question:
return "Unknown"
if "plus" in question:
return "5"
return "Sheffield"
report = evaluate(self.manifest, Client())
self.assertEqual(report["positive_matches"], 2)
self.assertEqual(report["possible_near_miss_leaks"], 0)
self.assertEqual(report["anchors"][0]["answer"], "5")
self.assertFalse(report["weights_changed"])
def test_detects_leaks(self):
class Client:
def chat(self, model, question):
return "Sheffield"
report = evaluate(self.manifest, Client())
self.assertEqual(report["possible_near_miss_leaks"], 1)
if __name__ == "__main__":
unittest.main()
+133
View File
@@ -0,0 +1,133 @@
from __future__ import annotations
import json
import tempfile
import unittest
from pathlib import Path
from living_weights_v2.assessment import Observation, assess, contains_answer, affirmative_answer
from living_weights_v2.schema import ManifestError, load_manifest
FACT = {
"subject": "Quillmoor Labs", "relation": "headquarters", "answer": "Sheffield",
"text": "Quillmoor Labs is headquartered in Sheffield.", "evidence": "User approval",
"questions": ["Where is Quillmoor Labs located?", "Which city is Quillmoor Labs in?"],
"near_misses": ["Where is Quillmoor's marketing team?"]
}
def manifest(**overrides):
data = {"schema_version": 1, "model": "local-model", "asserted_by_user": True,
"facts": [FACT], "anchors": ["What is 2+3?"], "source": "A fictional handbook"}
data.update(overrides)
return data
class ManifestTests(unittest.TestCase):
def load(self, data):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "plan.json"
path.write_text(json.dumps(data), encoding="utf-8")
return load_manifest(path)
def test_load_and_hash(self):
result = self.load(manifest())
self.assertEqual(result.model, "local-model")
self.assertEqual(result.facts[0].answer, "Sheffield")
self.assertEqual(len(result.digest), 64)
self.assertEqual(result.facts[0].key, "quillmoor labs\x1fheadquarters")
def test_requires_user_attestation(self):
for value in (False, 1, "true", None):
with self.subTest(value=value), self.assertRaises(ManifestError):
self.load(manifest(asserted_by_user=value))
def test_unknown_and_missing_keys(self):
with self.assertRaises(ManifestError):
self.load(manifest(unreviewed="payload"))
item = manifest()
del item["source"]
with self.assertRaises(ManifestError):
self.load(item)
def test_duplicate_claims_conflict(self):
with self.assertRaises(ManifestError):
self.load(manifest(facts=[FACT, FACT]))
def test_duplicate_questions(self):
fact = {**FACT, "questions": ["Where?", " where? "]}
with self.assertRaises(ManifestError):
self.load(manifest(facts=[fact]))
def test_requires_answer_in_statement(self):
fact = {**FACT, "text": "Quillmoor Labs has a headquarters."}
with self.assertRaises(ManifestError):
self.load(manifest(facts=[fact]))
def test_length_and_type_bounds(self):
for invalid in ([], "none", [{}] * 129):
with self.subTest(value=str(invalid)[:16]), self.assertRaises(ManifestError):
self.load(manifest(facts=invalid))
def test_rejects_duplicate_json_keys(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "plan.json"
path.write_text('{"schema_version":1,"schema_version":1}')
with self.assertRaises(ManifestError):
load_manifest(path)
def test_rejects_oversized_input(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "plan.json"
path.write_text(" " * (1024 * 1024 + 1))
with self.assertRaises(ManifestError):
load_manifest(path)
class AssessmentTests(unittest.TestCase):
def setUp(self):
self.fact = ManifestTests().load(manifest()).facts[0]
def obs(self, question, answer):
return Observation(question, answer, "test")
def test_boundary_matching(self):
self.assertTrue(contains_answer("It's Sheffield.", "Sheffield"))
self.assertFalse(contains_answer("Sheffieldish is elsewhere", "Sheffield"))
self.assertFalse(contains_answer("The answer is blank", ""))
self.assertTrue(contains_answer("New York, USA", "New York"))
def test_negated_expected_answer_is_not_recall(self):
self.assertFalse(affirmative_answer("It is not Sheffield", "Sheffield"))
self.assertFalse(affirmative_answer("I am not sure, perhaps Sheffield", "Sheffield"))
self.assertTrue(affirmative_answer("It is Sheffield.", "Sheffield"))
def test_passed(self):
result = assess(self.fact, (self.obs("negative", "Unknown"),),
(self.obs("positive", "In Sheffield"),),
(self.obs("negative", "Unknown"),),
(self.obs("anchor", "5"),), (self.obs("anchor", "5"),), ())
self.assertTrue(result.passed)
def test_leak_and_drift(self):
result = assess(self.fact, (self.obs("negative", "Unknown"),),
(self.obs("positive", "Not sure"),),
(self.obs("negative", "Sheffield"),),
(self.obs("anchor", "5"),), (self.obs("anchor", "6"),), ())
self.assertFalse(result.passed)
self.assertEqual(result.leaks, ("negative",))
self.assertEqual(len(result.drift), 2)
def test_retained_failure(self):
result = assess(self.fact, (), (self.obs("p", "Sheffield"),), (), (), (),
((self.fact, (self.obs("old", "unknown"),)),))
self.assertEqual(result.retained_failures, ("old",))
def test_mismatched_probes_refused(self):
with self.assertRaises(ValueError):
assess(self.fact, (), (), (self.obs("extra", "x"),), (), (), ())
if __name__ == "__main__":
unittest.main()
+166
View File
@@ -0,0 +1,166 @@
from __future__ import annotations
import json
import tempfile
import threading
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from living_weights_v2.transport import Client, TransportError
class Handler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
pass
def do_GET(self):
self._reply({"data": [{"id": "local-model"}]} if self.path == "/v1/models" else {"facts": []})
def do_POST(self):
size = int(self.headers.get("Content-Length", "0"))
request = json.loads(self.rfile.read(size))
if self.path == "/v1/chat/completions":
self._reply({"choices": [{"message": {"content": "Sheffield"}}]})
return
if self.path == "/v1/slide/learn":
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
self.wfile.write(b'event: learned\ndata: {"recalled":true,"id":1}\n\nevent: saved\ndata: {"files":1}\n\ndata: [DONE]\n\n')
return
self._reply({"error": "unknown"})
def _reply(self, value):
body = json.dumps(value).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
class TransportTests(unittest.TestCase):
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
key_file = Path(self.dir.name) / "key"
key_file.write_text("secret\n")
self.key = key_file
self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
self.base = f"http://127.0.0.1:{self.server.server_port}"
def tearDown(self):
self.server.shutdown()
self.server.server_close()
self.thread.join(timeout=5)
self.dir.cleanup()
def test_real_http_sse_and_chat(self):
client = Client(self.base, self.key)
self.assertEqual(client.models(), {"local-model"})
self.assertEqual(client.graph(), {})
self.assertEqual(client.chat("local-model", "Where?"), "Sheffield")
events = client.teach("Something")
self.assertEqual([e.kind for e in events], ["learned", "saved"])
self.assertTrue(events[0].data["recalled"])
def test_loopback_only(self):
for url in ("https://example.org", "http://localhost:8080", "http://127.0.0.1/x", "file:///etc/passwd", "http://user:pass@127.0.0.1"):
with self.subTest(url=url), self.assertRaises(TransportError):
Client(url, self.key)
def test_allow_remote_explicit(self):
client = Client("https://example.org", self.key, allow_remote=True)
self.assertEqual(client.base_url, "https://example.org")
def test_redirects_never_forward_authenticated_requests(self):
received = []
class Destination(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def do_GET(self):
received.append((self.command, self.headers.get("Authorization")))
self.send_response(200)
self.send_header("Content-Length", "0")
self.end_headers()
do_POST = do_GET
do_DELETE = do_GET
destination = ThreadingHTTPServer(("127.0.0.1", 0), Destination)
destination_thread = threading.Thread(target=destination.serve_forever, daemon=True)
destination_thread.start()
class Redirect(BaseHTTPRequestHandler):
code = 302
location = f"http://127.0.0.1:{destination.server_port}/capture"
def log_message(self, *args):
pass
def do_GET(self):
if self.path == "/capture":
Destination.do_GET(self)
return
self.rfile.read(int(self.headers.get("Content-Length", "0")))
self.send_response(self.code)
self.send_header("Location", self.location)
self.send_header("Content-Length", "0")
self.end_headers()
do_POST = do_GET
do_DELETE = do_GET
origin = ThreadingHTTPServer(("127.0.0.1", 0), Redirect)
origin_thread = threading.Thread(target=origin.serve_forever, daemon=True)
origin_thread.start()
try:
for allow_remote in (False, True):
client = Client(f"http://127.0.0.1:{origin.server_port}", self.key, allow_remote=allow_remote)
for location in (f"http://127.0.0.1:{destination.server_port}/capture", "/capture"):
Redirect.location = location
for code in (301, 302, 303, 307, 308):
Redirect.code = code
for method in ("GET", "POST", "DELETE"):
with self.subTest(remote=allow_remote, location=location, code=code, method=method):
with self.assertRaisesRegex(TransportError, f"HTTP {code}"):
with client._open("/redirect", method, {"text": "test"} if method != "GET" else None):
pass
self.assertEqual(received, [], "redirect destination received credentials")
finally:
for server in (origin, destination):
server.shutdown()
server.server_close()
origin_thread.join(timeout=5)
destination_thread.join(timeout=5)
def test_missing_or_empty_key(self):
with self.assertRaises(TransportError):
Client(self.base, Path(self.dir.name) / "missing")
self.key.write_text("\n")
with self.assertRaises(TransportError):
Client(self.base, self.key)
def test_sse_without_terminal_done_rejected(self):
class FakeClient(Client):
def _open(self, path, method="GET", payload=None):
from io import BytesIO
return BytesIO(b'event: learned\ndata: {"recalled":true}\n\n')
with self.assertRaises(TransportError):
tuple(FakeClient(self.base, self.key).events("/learn", "POST", {"text": "x"}))
def test_invalid_sse_json_rejected(self):
class FakeClient(Client):
def _open(self, path, method="GET", payload=None):
from io import BytesIO
return BytesIO(b'event: saved\ndata: invalid\n\ndata: [DONE]\n\n')
with self.assertRaises(TransportError):
tuple(FakeClient(self.base, self.key).events("/learn", "POST", {"text": "x"}))
if __name__ == "__main__":
unittest.main()
+3
View File
@@ -0,0 +1,3 @@
"""Explicit, externally guarded native TensorFold learning workflows."""
__version__ = "0.1.0"
+77
View File
@@ -0,0 +1,77 @@
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from .controller import Controller, LearningError
from .evaluator import evaluate
from .ledger import Ledger, LedgerError, exclusive_file
from .schema import ManifestError, load_manifest
from .transport import Client, TransportError
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="python -m living_weights_v2", description="External guarded learning controller for native TensorFold Living Weights")
sub = parser.add_subparsers(dest="command", required=True)
plan = sub.add_parser("plan", help="validate and summarize a manifest without writing weights")
plan.add_argument("manifest", type=Path)
evaluation = sub.add_parser("evaluate", help="read-only lexical recall probes over any OpenAI-compatible chat server")
evaluation.add_argument("manifest", type=Path)
evaluation.add_argument("--base-url", default="http://127.0.0.1:8080")
evaluation.add_argument("--api-key-file", type=Path, required=True)
evaluation.add_argument("--allow-remote", action="store_true")
teach = sub.add_parser("teach", help="explicitly teach user-approved facts through the native API")
teach.add_argument("manifest", type=Path)
teach.add_argument("--base-url", default="http://127.0.0.1:8080")
teach.add_argument("--api-key-file", type=Path, required=True)
teach.add_argument("--ledger", type=Path, default=Path.home() / ".local/state/tensorfold/living-weights-v2.sqlite3")
teach.add_argument("--allow-remote", action="store_true", help="explicitly allow an authenticated remote server")
teach.add_argument("--timeout", type=int, default=3600)
status = sub.add_parser("status", help="show durable audit history and pending recovery")
status.add_argument("--ledger", type=Path, default=Path.home() / ".local/state/tensorfold/living-weights-v2.sqlite3")
status.add_argument("--model")
args = parser.parse_args(argv)
try:
if args.command == "plan":
manifest = load_manifest(args.manifest)
output = {"schema": 1, "model": manifest.model, "manifest_digest": manifest.digest, "source": manifest.source, "facts": [
{"subject": f.subject, "relation": f.relation, "fact_digest": f.digest, "positive_count": len(f.questions), "near_miss_count": len(f.near_misses)}
for f in manifest.facts
], "anchor_count": len(manifest.anchors), "mutates_weights": False}
print(json.dumps(output, indent=2))
return 0
if args.command == "status":
ledger = Ledger(args.ledger)
try:
print(json.dumps(ledger.history(args.model), indent=2, ensure_ascii=False))
finally:
ledger.close()
return 0
if args.command == "evaluate":
manifest = load_manifest(args.manifest)
client = Client(args.base_url, args.api_key_file, args.allow_remote)
if manifest.model not in client.models():
raise LearningError("model not listed by chat server")
print(json.dumps(evaluate(manifest, client), indent=2, ensure_ascii=False))
return 0
if args.timeout <= 0:
raise ValueError("timeout must be positive")
manifest = load_manifest(args.manifest)
client = Client(args.base_url, args.api_key_file, args.allow_remote, args.timeout)
with exclusive_file(args.ledger.with_suffix(args.ledger.suffix + ".lock")):
ledger = Ledger(args.ledger)
try:
result = Controller(client, ledger).teach(manifest)
print(json.dumps(result, indent=2, ensure_ascii=False))
return 3 if any(r["state"] == "needs_recovery" for r in result) else (2 if any(r["state"] in {"rejected", "rolled_back"} for r in result) else 0)
finally:
ledger.close()
except (ManifestError, TransportError, LearningError, LedgerError, ValueError) as exc:
print(f"living_weights_v2: {exc}", file=sys.stderr)
return 4
if __name__ == "__main__":
raise SystemExit(main())
+91
View File
@@ -0,0 +1,91 @@
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Callable, Iterable
from .schema import Fact
@dataclass(frozen=True)
class Observation:
question: str
answer: str
mode: str
@dataclass(frozen=True)
class Assessment:
positives: int
positive_total: int
leaks: tuple[str, ...]
drift: tuple[str, ...]
retained_failures: tuple[str, ...]
@property
def passed(self) -> bool:
return self.positives == self.positive_total and not (self.leaks or self.drift or self.retained_failures)
def contains_answer(response: str, expected: str) -> bool:
if not expected.strip():
return False
words = [re.escape(x) for x in expected.casefold().split()]
expression = r"(?<!\w)" + r"\s+".join(words) + r"(?!\w)"
return re.search(expression, response.casefold()) is not None
def affirmative_answer(response: str, expected: str) -> bool:
if not contains_answer(response, expected):
return False
unsafe = ("i don't know", "i do not know", "not sure", "cannot confirm", "can't verify",
"not enough information", "might be", "possibly", "perhaps", "no evidence")
lowered = response.casefold()
if any(phrase in lowered for phrase in unsafe):
return False
pattern = r"\b(?:not|never|isn't|wasn't|ain't)\b.{0,24}" + re.escape(expected.casefold())
if re.search(pattern, lowered):
return False
return True
def observe(questions: Iterable[str], request: Callable[[str], str], mode: str) -> tuple[Observation, ...]:
return tuple(Observation(question, request(question), mode) for question in questions)
def _key(text: str) -> str:
return " ".join(text.casefold().split())
def assess(
fact: Fact,
baseline_negatives: tuple[Observation, ...],
after_positives: tuple[Observation, ...],
after_negatives: tuple[Observation, ...],
baseline_anchors: tuple[Observation, ...],
after_anchors: tuple[Observation, ...],
retained: tuple[tuple[Fact, tuple[Observation, ...]], ...],
) -> Assessment:
if len(baseline_negatives) != len(after_negatives) or len(baseline_anchors) != len(after_anchors):
raise ValueError("pre/post checks have different lengths")
leaks = []
drift = []
failures = []
positive_count = sum(affirmative_answer(o.answer, fact.answer) for o in after_positives)
for before, after in zip(baseline_negatives, after_negatives):
if before.question != after.question:
raise ValueError("near-miss probes changed")
if contains_answer(after.answer, fact.answer) and not contains_answer(before.answer, fact.answer):
leaks.append(after.question)
if _key(before.answer) != _key(after.answer):
drift.append(after.question)
for before, after in zip(baseline_anchors, after_anchors):
if before.question != after.question:
raise ValueError("anchor probes changed")
if _key(before.answer) != _key(after.answer):
drift.append(after.question)
for old, observations in retained:
for observation in observations:
if not affirmative_answer(observation.answer, old.answer):
failures.append(observation.question)
return Assessment(positive_count, len(after_positives), tuple(leaks), tuple(drift), tuple(failures))
+187
View File
@@ -0,0 +1,187 @@
from __future__ import annotations
from dataclasses import asdict
from typing import Any
from .assessment import affirmative_answer, assess, contains_answer, observe
from .ledger import Ledger
from .schema import Fact, Manifest
from .transport import Client, Event, TransportError
class LearningError(RuntimeError):
pass
def _stable_graph_fact(item: dict) -> dict:
# Native rechecks update counters and verdicts; links are recomputed from all current fact texts.
return {key: value for key, value in item.items() if key not in {"checks", "recalled", "links"}}
def _changes(before: dict[int, dict], after: dict[int, dict]) -> list[int]:
removed = set(before) - set(after)
if removed:
raise LearningError(f"graph lost facts {sorted(removed)}")
for key in before.keys() & after.keys():
if _stable_graph_fact(before[key]) != _stable_graph_fact(after[key]):
raise LearningError(f"existing graph fact {key} changed during lesson")
return sorted(set(after) - set(before))
def _event_summary(events: tuple[Event, ...]) -> dict:
meaningful = [e for e in events if e.kind in {"learned", "saved", "failed", "forgot"}]
return {"events": [{"kind": e.kind, "data": e.data} for e in meaningful]}
def _claimed_id(event: Event) -> int | None:
value = event.data.get("id")
if type(value) is int and value > 0:
return value
nested = event.data.get("fact")
if isinstance(nested, dict) and type(nested.get("id")) is int:
return nested["id"]
return None
def _owns_new_fact(new_ids: list[int], events: tuple[Event, ...], graph: dict[int, dict], fact: Fact) -> bool:
if len(new_ids) != 1:
return False
if any(_claimed_id(event) == new_ids[0] for event in events if event.kind in {"fact", "learned"}):
return True
item = graph[new_ids[0]]
for field in ("text", "statement", "fact", "content"):
value = item.get(field)
if isinstance(value, str) and value.strip().casefold() == fact.text.casefold():
return True
return False
class Controller:
def __init__(self, client: Client, ledger: Ledger):
self.client = client
self.ledger = ledger
def _probe(self, model: str, questions: tuple[str, ...], mode: str):
return observe(questions, lambda question: self.client.chat(model, question), mode)
def _restore(self, ids: list[int]) -> bool:
if not ids or len(ids) > 256:
return False
try:
events = self.client.delete(ids, "Living Weights v2 external regression gate")
forgot = [event for event in events if event.kind == "forgot"]
if len(forgot) != len(ids) or any(event.data.get("deleted") is not True for event in forgot):
return False
post = self.client.graph()
return all(post.get(i, {}).get("state") == "deleted" for i in ids)
except (TransportError, ValueError):
return False
def _verify_existing(self, model: str, retained: tuple[Fact, ...]):
return tuple((fact, self._probe(model, fact.questions, "retained")) for fact in retained)
def _recovered(self, model: str, baseline_pos, baseline_neg, baseline_anchor, baseline_retained) -> bool:
sequences = [baseline_pos, baseline_neg, baseline_anchor]
sequences.extend(observations for _, observations in baseline_retained)
for before in sequences:
after = self._probe(model, tuple(item.question for item in before), "recovery-check")
for original, current in zip(before, after):
if " ".join(original.answer.casefold().split()) != " ".join(current.answer.casefold().split()):
return False
return True
def preflight(self, manifest: Manifest) -> dict:
if manifest.model not in self.client.models():
raise LearningError("requested model is not listed by the server")
graph = self.client.graph()
if any(item.get("state") == "deleting" for item in graph.values()):
raise LearningError("graph has an unfinished native deletion")
for fact in manifest.facts:
self.ledger.require_safe(manifest.model, fact)
return {"model": manifest.model, "facts": len(manifest.facts), "graph_entries": len(graph)}
def teach(self, manifest: Manifest) -> list[dict[str, Any]]:
self.preflight(manifest)
receipts = []
for fact in manifest.facts:
receipts.append(self._teach_one(manifest, fact))
if receipts[-1]["state"] in {"needs_recovery", "rolled_back", "rejected"}:
break
return receipts
def _teach_one(self, manifest: Manifest, fact: Fact) -> dict:
model = manifest.model
self.ledger.require_safe(model, fact)
retained = self.ledger.retained(model)
before_graph = self.client.graph()
baseline_pos = self._probe(model, fact.questions, "before-positive")
baseline_neg = self._probe(model, fact.near_misses, "before-near-miss")
baseline_anchor = self._probe(model, manifest.anchors, "before-anchor")
baseline_retained = self._verify_existing(model, retained)
for old_fact, observations in baseline_retained:
if not all(affirmative_answer(o.answer, old_fact.answer) for o in observations):
return {"state": "rejected", "fact": fact.digest, "reason": "an earlier committed fact already fails its probes"}
if all(affirmative_answer(result.answer, fact.answer) for result in baseline_pos):
return {"state": "already_answers", "fact": fact.digest, "note": "not proof of retention; no weights changed"}
if any(contains_answer(result.answer, fact.answer) for result in baseline_neg):
return {"state": "rejected", "fact": fact.digest, "reason": "baseline leaks the expected answer to a near-miss"}
entry_id = self.ledger.begin(model, manifest.digest, fact)
receipt: dict[str, Any] = {
"entry_id": entry_id, "fact_digest": fact.digest, "manifest_digest": manifest.digest,
"model": model, "baseline": {
"positives": [asdict(o) for o in baseline_pos],
"near_misses": [asdict(o) for o in baseline_neg],
"anchors": [asdict(o) for o in baseline_anchor],
"retained": [{"fact_digest": old.digest, "observations": [asdict(o) for o in values]} for old, values in baseline_retained],
},
}
state = "needs_recovery"
try:
events = self.client.teach(fact.text)
receipt["native"] = _event_summary(events)
learned = [event for event in events if event.kind == "learned"]
saved = [event for event in events if event.kind == "saved"]
errors = [event for event in events if event.kind == "failed"]
after_graph = self.client.graph()
new_ids = _changes(before_graph, after_graph)
receipt["new_graph_ids"] = new_ids
owned = _owns_new_fact(new_ids, events, after_graph, fact)
receipt["new_fact_attributed"] = owned
if errors or not saved or len(learned) != 1 or learned[0].data.get("recalled") is not True:
if not new_ids:
state = "rejected"
elif owned and self._restore(new_ids):
if self._recovered(model, baseline_pos, baseline_neg, baseline_anchor, baseline_retained):
state = "rolled_back"
else:
receipt["reason"] = "deletion completed but baseline output was not recovered"
receipt["reason"] = "native learner did not confirm exactly one recalled and saved fact"
elif not owned:
receipt["reason"] = "cannot prove graph entry belongs to this request"
else:
after_pos = self._probe(model, fact.questions, "after-positive")
after_neg = self._probe(model, fact.near_misses, "after-near-miss")
after_anchor = self._probe(model, manifest.anchors, "after-anchor")
retained_observations = self._verify_existing(model, retained)
evaluation = assess(fact, baseline_neg, after_pos, after_neg, baseline_anchor, after_anchor, retained_observations)
receipt["assessment"] = asdict(evaluation)
receipt["answers"] = {
"positives": [asdict(o) for o in after_pos],
"near_misses": [asdict(o) for o in after_neg],
"anchors": [asdict(o) for o in after_anchor],
"retained": [{"fact_digest": old.digest, "observations": [asdict(o) for o in values]} for old, values in retained_observations],
}
if evaluation.passed:
state = "committed"
elif self._restore(new_ids):
if self._recovered(model, baseline_pos, baseline_neg, baseline_anchor, baseline_retained):
state = "rolled_back"
else:
receipt["reason"] = "deletion completed but baseline output was not recovered"
else:
receipt["reason"] = "post-training regression and native deletion was not confirmed"
except Exception as exc:
receipt["error"] = type(exc).__name__ + ": " + str(exc)
receipt["state"] = state
self.ledger.finish(entry_id, state, receipt)
return receipt
+40
View File
@@ -0,0 +1,40 @@
from __future__ import annotations
from dataclasses import asdict
from typing import Protocol
from .assessment import affirmative_answer, contains_answer
from .schema import Manifest
class ChatModel(Protocol):
def chat(self, model: str, question: str) -> str: ...
def evaluate(manifest: Manifest, client: ChatModel) -> dict:
"""Read-only lexical checks; not a semantic correctness certificate."""
checks = []
total = 0
correct = 0
leaked = 0
for fact in manifest.facts:
positive = []
negative = []
for question in fact.questions:
answer = client.chat(manifest.model, question)
matched = affirmative_answer(answer, fact.answer)
total += 1
correct += int(matched)
positive.append({"question": question, "answer": answer, "expected_present": matched})
for question in fact.near_misses:
answer = client.chat(manifest.model, question)
violation = contains_answer(answer, fact.answer)
leaked += int(violation)
negative.append({"question": question, "answer": answer, "possible_leak": violation})
checks.append({"fact_digest": fact.digest, "subject": fact.subject,
"positives": positive, "near_misses": negative})
anchors = [{"question": question, "answer": client.chat(manifest.model, question)} for question in manifest.anchors]
return {"model": manifest.model, "manifest_digest": manifest.digest, "positive_matches": correct,
"positive_total": total, "possible_near_miss_leaks": leaked, "anchors": anchors,
"checks": checks, "weights_changed": False,
"disclaimer": "lexical answer-presence checks; not a semantic or model-family training guarantee"}
+110
View File
@@ -0,0 +1,110 @@
from __future__ import annotations
import contextlib
import json
import os
import sqlite3
from dataclasses import asdict
from pathlib import Path
from typing import Iterator
from .schema import Fact, normalized
class LedgerError(RuntimeError):
pass
@contextlib.contextmanager
def exclusive_file(path: Path) -> Iterator[None]:
try:
import fcntl
except ImportError as exc:
raise LedgerError("exclusive locking requires a POSIX host") from exc
path.parent.mkdir(parents=True, exist_ok=True)
descriptor = os.open(str(path), os.O_CREAT | os.O_RDWR, 0o600)
try:
import fcntl
fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
yield
except BlockingIOError as exc:
raise LedgerError("another Living Weights v2 writer is active") from exc
finally:
os.close(descriptor)
class Ledger:
def __init__(self, path: Path):
self.path = path
path.parent.mkdir(parents=True, exist_ok=True)
self.db = sqlite3.connect(path, timeout=2)
self.db.row_factory = sqlite3.Row
self.db.executescript("""
PRAGMA journal_mode=WAL;
PRAGMA synchronous=FULL;
CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
model TEXT NOT NULL,
fact_digest TEXT NOT NULL,
subject_key TEXT NOT NULL,
answer TEXT NOT NULL,
fact_json TEXT NOT NULL,
manifest_digest TEXT NOT NULL,
state TEXT NOT NULL,
receipt_json TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
);
CREATE INDEX IF NOT EXISTS entries_model_state ON entries(model, state);
""")
self.db.commit()
def close(self):
self.db.close()
def require_safe(self, model: str, fact: Fact) -> None:
pending = self.db.execute("SELECT id, state FROM entries WHERE model=? AND state IN ('inflight','needs_recovery')", (model,)).fetchall()
if pending:
raise LedgerError(f"model has unresolved write records {[int(row['id']) for row in pending]}; recovery required")
entries = self.db.execute("SELECT answer, fact_digest FROM entries WHERE model=? AND subject_key=? AND state='committed'", (model, fact.key)).fetchall()
for row in entries:
if normalized(row["answer"]) != normalized(fact.answer):
raise LedgerError("contradictory fact about the same subject/relation; explicit delete and independent validation required")
if row["fact_digest"] == fact.digest:
raise LedgerError("identical fact already committed; teaching again is not idempotent")
raise LedgerError("subject/relation already learned with different evidence; review required")
def retained(self, model: str) -> tuple[Fact, ...]:
entries = self.db.execute("SELECT fact_json FROM entries WHERE model=? AND state='committed' ORDER BY id", (model,)).fetchall()
result = []
for row in entries:
value = json.loads(row["fact_json"])
value["questions"] = tuple(value["questions"])
value["near_misses"] = tuple(value["near_misses"])
result.append(Fact(**value))
return tuple(result)
def begin(self, model: str, manifest_digest: str, fact: Fact) -> int:
self.require_safe(model, fact)
with self.db:
cursor = self.db.execute("INSERT INTO entries(model, fact_digest, subject_key, answer, fact_json, manifest_digest, state) VALUES(?,?,?,?,?,?,?)", (
model, fact.digest, fact.key, fact.answer, json.dumps(asdict(fact), ensure_ascii=False), manifest_digest, "inflight",
))
return int(cursor.lastrowid)
def finish(self, entry_id: int, state: str, receipt: dict) -> None:
if state not in {"committed", "skipped", "rejected", "rolled_back", "needs_recovery"}:
raise LedgerError("invalid final state")
with self.db:
cursor = self.db.execute("UPDATE entries SET state=?, receipt_json=?, updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id=? AND state='inflight'", (
state, json.dumps(receipt, sort_keys=True, ensure_ascii=False), entry_id,
))
if cursor.rowcount != 1:
raise LedgerError("no matching inflight entry")
def history(self, model: str | None = None) -> list[dict]:
if model:
rows = self.db.execute("SELECT id, model, subject_key, state, receipt_json, created_at FROM entries WHERE model=? ORDER BY id", (model,))
else:
rows = self.db.execute("SELECT id, model, subject_key, state, receipt_json, created_at FROM entries ORDER BY id")
return [{**dict(row), "receipt": json.loads(row["receipt_json"])} for row in rows]
+123
View File
@@ -0,0 +1,123 @@
from __future__ import annotations
import hashlib
import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any
class ManifestError(ValueError):
pass
def normalized(value: str) -> str:
return " ".join(value.casefold().split())
def _string(value: Any, name: str, limit: int = 4096) -> str:
if not isinstance(value, str) or not value.strip() or len(value) > limit:
raise ManifestError(f"{name} must be a nonempty string of at most {limit} characters")
return value.strip()
def _fields(obj: Any, required: set[str], optional: set[str], name: str) -> dict:
if not isinstance(obj, dict):
raise ManifestError(f"{name} must be an object")
missing = required - obj.keys()
unknown = obj.keys() - required - optional
if missing or unknown:
raise ManifestError(f"{name}: missing {sorted(missing)}; unknown {sorted(unknown)}")
return obj
def _questions(value: Any, name: str, min_count: int = 1) -> tuple[str, ...]:
if not isinstance(value, list) or not min_count <= len(value) <= 64:
raise ManifestError(f"{name} must contain {min_count} to 64 questions")
result = tuple(_string(item, name, 1000) for item in value)
if len(set(map(normalized, result))) != len(result):
raise ManifestError(f"{name} contains duplicate questions")
return result
@dataclass(frozen=True)
class Fact:
subject: str
relation: str
answer: str
text: str
evidence: str
questions: tuple[str, ...]
near_misses: tuple[str, ...]
@property
def key(self) -> str:
return normalized(self.subject) + "\x1f" + normalized(self.relation)
@property
def digest(self) -> str:
fields = [self.subject, self.relation, self.answer, self.text, self.evidence]
return hashlib.sha256(json.dumps(fields, ensure_ascii=False).encode()).hexdigest()
@dataclass(frozen=True)
class Manifest:
model: str
asserted_by_user: bool
facts: tuple[Fact, ...]
anchors: tuple[str, ...]
source: str
digest: str
def _reject_duplicates(pairs: list[tuple[str, Any]]) -> dict:
result = {}
for key, value in pairs:
if key in result:
raise ManifestError(f"duplicate JSON key: {key}")
result[key] = value
return result
def load_manifest(path: Path) -> Manifest:
try:
raw = path.read_bytes()
if len(raw) > 1024 * 1024:
raise ManifestError("manifest exceeds 1 MiB")
data = json.loads(raw, object_pairs_hook=_reject_duplicates)
except (OSError, json.JSONDecodeError) as exc:
raise ManifestError(str(exc)) from exc
obj = _fields(data, {"schema_version", "model", "asserted_by_user", "facts", "anchors", "source"}, set(), "manifest")
if type(obj["schema_version"]) is not int or obj["schema_version"] != 1:
raise ManifestError("schema_version must be 1")
if obj["asserted_by_user"] is not True:
raise ManifestError("asserted_by_user must be true; evidence is user-supplied, not automatically verified")
if not isinstance(obj["facts"], list) or not 1 <= len(obj["facts"]) <= 128:
raise ManifestError("facts must contain 1 to 128 entries")
facts = []
keys = set()
for i, raw_fact in enumerate(obj["facts"]):
entry = _fields(raw_fact, {"subject", "relation", "answer", "text", "evidence", "questions", "near_misses"}, set(), f"fact[{i}]")
fact = Fact(
subject=_string(entry["subject"], "subject", 256),
relation=_string(entry["relation"], "relation", 128),
answer=_string(entry["answer"], "answer", 256),
text=_string(entry["text"], "text", 1024),
evidence=_string(entry["evidence"], "evidence", 8192),
questions=_questions(entry["questions"], "questions", 2),
near_misses=_questions(entry["near_misses"], "near_misses", 1),
)
if normalized(fact.answer) not in normalized(fact.text):
raise ManifestError(f"fact[{i}] answer must occur in text")
if fact.key in keys:
raise ManifestError(f"fact[{i}] duplicates a subject/relation in this manifest")
keys.add(fact.key)
facts.append(fact)
return Manifest(
model=_string(obj["model"], "model", 256),
asserted_by_user=True,
facts=tuple(facts),
anchors=_questions(obj["anchors"], "anchors", 1),
source=_string(obj["source"], "source", 2048),
digest=hashlib.sha256(raw).hexdigest(),
)
+161
View File
@@ -0,0 +1,161 @@
from __future__ import annotations
import ipaddress
import json
import socket
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterator
class TransportError(RuntimeError):
pass
@dataclass(frozen=True)
class Event:
kind: str
data: dict[str, Any]
class _RejectRedirects(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
# Every request carries a key for the configured origin, so redirects must fail before another request.
return None
class Client:
def __init__(self, base_url: str, api_key_file: Path, allow_remote: bool = False, timeout: float = 600):
parsed = urllib.parse.urlsplit(base_url)
if parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.path not in {"", "/"} or parsed.query or parsed.fragment or parsed.username:
raise TransportError("base URL must be an HTTP(S) origin with no path, query, or credentials")
if not allow_remote:
try:
if not ipaddress.ip_address(parsed.hostname).is_loopback:
raise TransportError("only literal loopback addresses allowed without --allow-remote")
except ValueError as exc:
raise TransportError("use a literal loopback IP or explicitly allow remote access") from exc
try:
key = api_key_file.read_text(encoding="utf-8").strip()
except OSError as exc:
raise TransportError(f"cannot read key file: {exc.strerror}") from exc
if not key or "\n" in key or "\r" in key:
raise TransportError("API key file must contain one nonempty line")
self.base_url = base_url.rstrip("/")
self.timeout = timeout
self.headers = {"Authorization": "Bearer " + key, "Accept": "application/json"}
self._opener = urllib.request.build_opener(_RejectRedirects())
def _open(self, path: str, method: str = "GET", payload: dict | None = None):
data = json.dumps(payload).encode() if payload is not None else None
headers = dict(self.headers)
if data is not None:
headers["Content-Type"] = "application/json"
request = urllib.request.Request(self.base_url + path, data=data, headers=headers, method=method)
try:
return self._opener.open(request, timeout=self.timeout)
except (urllib.error.URLError, TimeoutError, socket.timeout) as exc:
if isinstance(exc, urllib.error.HTTPError):
raise TransportError(f"HTTP {exc.code} from {path}") from exc
raise TransportError(f"request to {path} failed: {type(exc).__name__}") from exc
def json(self, path: str, method: str = "GET", payload: dict | None = None) -> dict:
with self._open(path, method, payload) as response:
raw = response.read(4 * 1024 * 1024 + 1)
if len(raw) > 4 * 1024 * 1024:
raise TransportError("JSON response exceeds 4 MiB")
try:
result = json.loads(raw)
if not isinstance(result, dict):
raise ValueError("expected JSON object")
return result
except (ValueError, UnicodeError) as exc:
raise TransportError("malformed JSON response") from exc
def events(self, path: str, method: str, payload: dict) -> Iterator[Event]:
received_done = False
with self._open(path, method, payload) as response:
kind = "message"
lines = []
for binary_line in response:
if len(binary_line) > 1024 * 1024:
raise TransportError("oversized SSE line")
try:
line = binary_line.decode("utf-8").rstrip("\r\n")
except UnicodeDecodeError as exc:
raise TransportError("invalid UTF-8 in SSE") from exc
if not line:
if not lines:
kind = "message"
continue
content = "\n".join(lines)
lines = []
if content == "[DONE]":
received_done = True
break
try:
parsed = json.loads(content)
except json.JSONDecodeError as exc:
raise TransportError("malformed SSE JSON") from exc
if not isinstance(parsed, dict):
raise TransportError("SSE payload must be a JSON object")
actual_kind = str(parsed.get("event", kind)) if kind == "message" else kind
yield Event(actual_kind, parsed)
kind = "message"
elif line.startswith("event:"):
kind = line[6:].strip()
elif line.startswith("data:"):
lines.append(line[5:].lstrip(" "))
if sum(map(len, lines)) > 1024 * 1024:
raise TransportError("oversized SSE event")
if lines and "\n".join(lines) == "[DONE]":
received_done = True
if not received_done:
raise TransportError("SSE stream ended without [DONE]")
def chat(self, model: str, question: str) -> str:
result = self.json("/v1/chat/completions", "POST", {
"model": model,
"messages": [{"role": "user", "content": question}],
"temperature": 0,
"max_tokens": 128,
})
try:
value = result["choices"][0]["message"]["content"]
if not isinstance(value, str):
raise TypeError("content is not a string")
return value
except (KeyError, IndexError, TypeError) as exc:
raise TransportError("chat response does not contain string content") from exc
def models(self) -> set[str]:
response = self.json("/v1/models")
try:
return {str(entry["id"]) for entry in response["data"]}
except (TypeError, ValueError, KeyError) as exc:
raise TransportError("invalid model listing") from exc
def graph(self) -> dict[int, dict]:
response = self.json("/v1/slide/graph")
facts = response.get("facts")
if not isinstance(facts, list):
raise TransportError("unrecognized graph schema: missing facts array")
result = {}
for fact in facts:
if not isinstance(fact, dict) or type(fact.get("id")) is not int or fact["id"] <= 0:
raise TransportError("unrecognized graph fact")
if fact["id"] in result:
raise TransportError("duplicate graph fact ID")
result[fact["id"]] = fact
return result
def teach(self, text: str) -> tuple[Event, ...]:
return tuple(self.events("/v1/slide/learn", "POST", {"text": text}))
def delete(self, ids: list[int], reason: str) -> tuple[Event, ...]:
if not ids or len(ids) > 256 or len(ids) != len(set(ids)) or any(type(i) is not int or i <= 0 for i in ids):
raise ValueError("invalid deletion IDs")
return tuple(self.events("/v1/slide/facts", "DELETE", {"ids": ids, "reason": reason}))