Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

docs(reasoning): explain checkpoint restore and storage boundaries

江俊杰f486336dcecf
diff --git a/docs/reference/truth_maintenance.md b/docs/reference/truth_maintenance.md
index 255a9cd5..6e27714f 100644
--- a/docs/reference/truth_maintenance.md
+++ b/docs/reference/truth_maintenance.md
@@ -124,6 +124,98 @@ session state unchanged. Returned snapshots (`MaintenanceDelta`,
dataclasses with immutable collections; mutating caller-owned rules or
previously returned results cannot mutate the session.
+### Checkpoint export and restore
+
+Use `to_checkpoint()` and `from_checkpoint()` when an application must resume
+the same logical session in a later process. These methods are a serialization
+boundary, not a storage engine.
+
+- `to_checkpoint()` returns a new JSON-compatible `dict` containing the fixed
+ rules captured at construction, the complete support catalog (including
+ withdrawn supports), the active support IDs, and the committed session
+ version. It does not save derived facts or internal indexes.
+- `from_checkpoint(payload)` accepts the result of `json.loads()` — not a JSON
+ string or file path — validates the complete payload, rebuilds derived facts,
+ direct derivations, and dependency indexes, and returns a new session only
+ after reconstruction succeeds.
+
+`snapshot()` remains a read-only query view of the current state. A checkpoint
+is different: it is a restart format that preserves the support-ID bindings and
+arity constraints needed to continue updates after serialization. The
+`session_version` in a checkpoint is only a local commit counter. It does not
+authorize reusing old snapshot-provider identities, temporal adapter history,
+or external caches.
+
+The fixed v1 schema is:
+
+```json
+{
+ "format_version": 1,
+ "session_version": 4,
+ "rules": [
+ {
+ "rule_id": "employment-eligibility",
+ "conditions": ["Employed(?x)"],
+ "conclusion": "Eligible(?x)"
+ }
+ ],
+ "support_catalog": [
+ {"support_id": "document-v1", "fact": "Employed(Alice)"},
+ {"support_id": "document-v2", "fact": "Employed(Alice)"}
+ ],
+ "active_support_ids": ["document-v2"]
+}
+```
+
+The top level and each rule/catalog record have exact field sets; missing and
+unknown fields are rejected. `format_version` must be integer `1`;
+`session_version` must be a non-negative integer. Rules and catalog facts are
+semantic values, so invalid atoms, variables in facts, recursive rules, and
+arity conflicts are rejected with the same `ValidationError` used by
+construction and `apply()`. Unsupported future formats are also rejected, and
+restore never returns a partially reconstructed session.
+
+Applications choose where to store the JSON. The minimal example below is
+intended only to show the API; `Path.write_text()` does **not** provide a
+crash-safe atomic commit. Use an atomic file replacement or transactional
+database commit if losing or partially writing a checkpoint is unacceptable.
+
+```python
+import json
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from semantica.reasoning import FactSupport, Rule, TruthMaintenanceSession
+
+session = TruthMaintenanceSession(rules=[
+ Rule("eligibility", "Eligibility", ["Employed(?x)"], "Eligible(?x)")
+])
+session.apply(assertions=[
+ FactSupport("doc-1", "Employed(Alice)"),
+ FactSupport("doc-2", "Employed(Alice)"),
+])
+saved_version = session.version
+with TemporaryDirectory() as directory:
+ path = Path(directory) / "checkpoint.json"
+ path.write_text(json.dumps(session.to_checkpoint()), encoding="utf-8")
+ del session
+ restored = TruthMaintenanceSession.from_checkpoint(
+ json.loads(path.read_text(encoding="utf-8"))
+ )
+ assert restored.version == saved_version
+ restored.apply(retractions=["doc-1"])
+ assert "Eligible(Alice)" in restored.facts
+ restored.apply(retractions=["doc-2"])
+ assert "Eligible(Alice)" not in restored.facts
+```
+
+Restore covers only the last successfully exported and saved checkpoint.
+Updates committed after that checkpoint, including updates that succeeded but
+were not durably stored, cannot be recovered. A malformed JSON document raises
+`JSONDecodeError` from the application's own `json.loads()` call;
+`from_checkpoint()` validates the resulting structured object and raises
+`ValidationError` for malformed checkpoint data.
+
## Cost Model
@@ -134,6 +226,15 @@ previously returned results cannot mutate the session.
pay one whole-state copy per filtered retrieval. Do not call it in a tight
loop when a single shared read is enough.
- The copy-on-update and catalog costs are per-batch whole-state costs; do not assume end-to-end latency is strictly proportional to the affected subgraph. Measure before relying on performance.
+- **Checkpoint payloads grow with the fixed rules and the complete historical
+ support catalog**, not just the active supports. Export also pays a
+ deterministic sorting cost for the catalog and active IDs.
+- **Restore is a full reconstruction**: it validates every catalog entry,
+ combines rule and catalog arity constraints, and rebuilds the complete
+ closure and direct explanations by replaying only the active supports. Join
+ matching can produce many intermediate matches, memory grows with those
+ matches and the copied candidate state, and no constant-time or
+ active-support-only cost bound is promised.
## Limitations
@@ -142,7 +243,9 @@ previously returned results cannot mutate the session.
- **Narrow atom syntax**: ASCII predicate/variable identifiers and unquoted scalar symbol constants, including zero-arity atoms. No quoted strings, whitespace-bearing constants, nested terms, comparisons, aggregation, negation, or disjunction. Exactly one arity per predicate within the session.
- **Boolean support semantics**; no confidence propagation, no probabilistic reasoning.
- **No side effects**: the session never executes actions or handlers and creates no LLM or store clients.
-- **No thread-safety, persistence, temporal validity, or cross-store synchronization** guarantees. Access must be caller-serialized in a single process.
+- **No automatic storage or recovery**: checkpoints are an explicit serialization format, but the session never writes to a file or database and does not recover automatically after a crash. The application owns storage, atomic commit, and choosing the last good checkpoint.
+- **No thread-safety or concurrent writers**: access remains caller-serialized in a single process, and checkpointing does not add a distributed locking or multi-writer protocol.
+- **No temporal validity or cross-store synchronization** guarantees. Restoring a checkpoint does not restore temporal adapter history, snapshot-provider identities, or external caches.
- **Fixed rules**: rule changes require constructing a new session.
- No historical proof archive: `explain()` describes the current state only.