ucde 0.2.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.
ucde/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ """Local experimental evidence memory for Python applications."""
2
+
3
+ from .archive import verify_archive
4
+ from .crate import create_crate
5
+ from .model import (
6
+ ConflictError, Evidence, EvidenceRetraction, EvidenceWrite, LedgerCheckpoint, LedgerHead, Revision,
7
+ SearchHit, SearchResult,
8
+ ValidationError, VerificationReport,
9
+ )
10
+ from .packet import compare_packets, export_packet, replay_packet, verify_packet
11
+ from .store import MemoryStore
12
+
13
+ __version__ = "0.2.0"
14
+
15
+ __all__ = [
16
+ "ConflictError", "Evidence", "EvidenceRetraction", "EvidenceWrite", "LedgerCheckpoint", "LedgerHead", "MemoryStore",
17
+ "Revision",
18
+ "SearchHit", "SearchResult", "ValidationError", "VerificationReport", "__version__",
19
+ "compare_packets", "create_crate", "export_packet", "replay_packet", "verify_archive", "verify_packet",
20
+ ]
ucde/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Allow running the UCDE CLI as a Python module."""
2
+
3
+ from .cli import main
4
+
5
+
6
+ if __name__ == "__main__":
7
+ raise SystemExit(main())
ucde/archive.py ADDED
@@ -0,0 +1,109 @@
1
+ """The checkpoint wire format and its standalone, streaming verifier."""
2
+
3
+ from hashlib import sha256
4
+ from hmac import compare_digest
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any, BinaryIO, NoReturn
8
+
9
+ from .model import LedgerCheckpoint, ValidationError, bounded_integer, checked_sha256, checked_text, timestamp
10
+
11
+
12
+ CHECKPOINT_FORMAT = "ucde.ledger-checkpoint.v1"
13
+ MAX_ARCHIVE_LINE_BYTES = 2 * 1024 * 1024
14
+ _MAX_SQLITE_INTEGER = 2**63 - 1
15
+
16
+
17
+ def checkpoint_line(values: tuple[object, ...]) -> bytes:
18
+ try:
19
+ frame = json.dumps(values, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
20
+ return (frame + "\n").encode("utf-8")
21
+ except (TypeError, ValueError, RecursionError) as error:
22
+ raise ValidationError("ledger has a value that cannot be included in a checkpoint") from error
23
+
24
+
25
+ def _reject_constant(value: str) -> NoReturn:
26
+ raise ValueError(f"invalid JSON constant {value}")
27
+
28
+
29
+ def _read_frame(source: BinaryIO) -> tuple[bytes, list[Any]] | None:
30
+ raw = source.readline(MAX_ARCHIVE_LINE_BYTES + 1)
31
+ if not raw:
32
+ return None
33
+ if len(raw) > MAX_ARCHIVE_LINE_BYTES:
34
+ raise ValidationError("archive frame exceeds the size limit")
35
+ if not raw.endswith(b"\n"):
36
+ raise ValidationError("archive ends in an incomplete frame")
37
+ try:
38
+ values = json.loads(raw.decode("utf-8"), parse_constant=_reject_constant)
39
+ except (ValueError, RecursionError) as error:
40
+ raise ValidationError("archive frame must contain valid UTF-8 JSON") from error
41
+ if not isinstance(values, list) or checkpoint_line(tuple(values)) != raw:
42
+ raise ValidationError("archive frame must be a canonical JSON array")
43
+ return raw, values
44
+
45
+
46
+ def _normalized_timestamp(value: object, name: str) -> str:
47
+ if not isinstance(value, str) or timestamp(value, name) != value:
48
+ raise ValidationError(f"{name} must be a normalized UTC timestamp")
49
+ return value
50
+
51
+
52
+ def _revision_key(values: list[Any], cutoff: str) -> tuple[str, int]:
53
+ if len(values) != 9:
54
+ raise ValidationError("archive revision must contain nine fields")
55
+ identifier, revision, recorded, observed, retracted, restored, payload, tokens, space = values
56
+ identifier = checked_text(identifier, "archive observation ID")
57
+ revision = bounded_integer(revision, "archive revision number", 1, _MAX_SQLITE_INTEGER)
58
+ recorded = _normalized_timestamp(recorded, "archive recording time")
59
+ _normalized_timestamp(observed, "archive observation time")
60
+ if recorded > cutoff:
61
+ raise ValidationError("archive contains a revision recorded after the cutoff")
62
+ bounded_integer(retracted, "archive retraction flag", 0, 1)
63
+ if restored is not None:
64
+ bounded_integer(restored, "archive restoration reference", 1, revision - 1)
65
+ bounded_integer(tokens, "archive token count", 0, _MAX_SQLITE_INTEGER)
66
+ if space is not None:
67
+ checked_text(space, "archive embedding space")
68
+ if not isinstance(payload, str):
69
+ raise ValidationError("archive revision payload must be a JSON object string")
70
+ try:
71
+ decoded = json.loads(payload, parse_constant=_reject_constant)
72
+ except (ValueError, RecursionError) as error:
73
+ raise ValidationError("archive revision payload must be a JSON object string") from error
74
+ if not isinstance(decoded, dict):
75
+ raise ValidationError("archive revision payload must be a JSON object string")
76
+ return identifier, revision
77
+
78
+
79
+ def verify_archive(path: str | Path, *, expected_sha256: str) -> LedgerCheckpoint:
80
+ """Compare a portable archive with an independently saved ledger checkpoint digest."""
81
+ expected = checked_sha256(expected_sha256, "expected_sha256")
82
+ revisions = observations = 0
83
+ previous: tuple[str, int] | None = None
84
+ # SQLite BINARY compares text in the database encoding, which v1 does not store.
85
+ encodings: tuple[str, ...] = ("utf-8", "utf-16-le", "utf-16-be")
86
+ with Path(path).open("rb") as source:
87
+ header = _read_frame(source)
88
+ if header is None or len(header[1]) != 2 or header[1][0] != CHECKPOINT_FORMAT:
89
+ raise ValidationError("archive must start with a supported checkpoint header")
90
+ raw, values = header
91
+ cutoff = _normalized_timestamp(values[1], "archive cutoff")
92
+ digest = sha256(raw)
93
+ while frame := _read_frame(source):
94
+ raw, values = frame
95
+ key = _revision_key(values, cutoff)
96
+ if previous is None or key[0] != previous[0]:
97
+ if previous is not None:
98
+ encodings = tuple(encoding for encoding in encodings
99
+ if previous[0].encode(encoding) < key[0].encode(encoding))
100
+ if not encodings:
101
+ raise ValidationError("archive observation IDs are out of SQLite BINARY order")
102
+ observations += 1
103
+ elif key[1] <= previous[1]:
104
+ raise ValidationError("archive revisions are out of order or duplicated")
105
+ revisions += 1
106
+ previous = key
107
+ digest.update(raw)
108
+ actual = digest.hexdigest()
109
+ return LedgerCheckpoint(CHECKPOINT_FORMAT, cutoff, observations, revisions, actual, compare_digest(expected, actual))
ucde/chain.py ADDED
@@ -0,0 +1,222 @@
1
+ """Schema 3 commitment writes inside the ledger's SQLite transaction."""
2
+
3
+ from collections.abc import Iterable, Iterator, Sequence
4
+ from hashlib import sha256
5
+ from hmac import compare_digest
6
+ import json
7
+ import re
8
+ from secrets import token_hex
9
+ import sqlite3
10
+
11
+ from .model import LedgerHead, ValidationError, bounded_integer, checked_sha256, timestamp
12
+
13
+
14
+ CHAIN_FORMAT = "ucde.ledger-chain.v3"
15
+ GENESIS_HEAD = "0" * 64
16
+ CHAIN_TABLES = ("chain_commit", "chain_member", "chain_link")
17
+ REVISION_COLUMNS = (
18
+ "id", "revision", "recorded_at", "observed_at", "retracted", "restored_from",
19
+ "payload", "token_count", "embedding_space",
20
+ )
21
+ _MAX_SEQUENCE = 2**63 - 1
22
+ _LEAF_DOMAIN = b"UCDE-LEDGER-LEAF-v3\x00"
23
+ _COMMIT_DOMAIN = b"UCDE-LEDGER-COMMIT-v3\x00"
24
+ _FIELDS = ", ".join(REVISION_COLUMNS)
25
+ _SCHEMA = (
26
+ "ALTER TABLE ledger_state ADD COLUMN chain_id TEXT",
27
+ "ALTER TABLE ledger_state ADD COLUMN chain_sequence INTEGER",
28
+ "ALTER TABLE ledger_state ADD COLUMN chain_head TEXT",
29
+ """CREATE TABLE chain_commit (
30
+ sequence INTEGER PRIMARY KEY,
31
+ recorded_at TEXT NOT NULL,
32
+ operation TEXT NOT NULL,
33
+ previous_head TEXT NOT NULL,
34
+ sha256 TEXT NOT NULL
35
+ )""",
36
+ """CREATE TABLE chain_member (
37
+ sequence INTEGER NOT NULL,
38
+ ordinal INTEGER NOT NULL,
39
+ leaf_sha256 TEXT,
40
+ target_sequence INTEGER,
41
+ target_ordinal INTEGER,
42
+ PRIMARY KEY (sequence, ordinal)
43
+ )""",
44
+ """CREATE TABLE chain_link (
45
+ row_id INTEGER PRIMARY KEY,
46
+ sequence INTEGER NOT NULL,
47
+ ordinal INTEGER NOT NULL,
48
+ nonce TEXT NOT NULL,
49
+ UNIQUE (sequence, ordinal)
50
+ )""",
51
+ )
52
+
53
+
54
+ def _canonical(value: object) -> bytes:
55
+ try:
56
+ return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")).encode("utf-8")
57
+ except (TypeError, ValueError, RecursionError) as error:
58
+ raise ValidationError("chain frame contains a value that cannot be encoded") from error
59
+
60
+
61
+ def _recording_time(value: str) -> str:
62
+ if timestamp(value, "chain recording time") != value:
63
+ raise ValidationError("chain recording time must be a normalized UTC timestamp")
64
+ return value
65
+
66
+
67
+ def checked_head(head: LedgerHead) -> LedgerHead:
68
+ """Validate and normalize a separately saved chain head."""
69
+ if not isinstance(head, LedgerHead) or head.format != CHAIN_FORMAT:
70
+ raise ValidationError("unsupported ledger chain head format")
71
+ if not isinstance(head.ledger_id, str) or re.fullmatch(r"[0-9a-fA-F]{32}", head.ledger_id) is None:
72
+ raise ValidationError("ledger_id must be a 32-character hexadecimal identifier")
73
+ sequence = bounded_integer(head.sequence, "chain sequence", 1, _MAX_SEQUENCE)
74
+ return LedgerHead(CHAIN_FORMAT, head.ledger_id.lower(), sequence, checked_sha256(head.sha256, "chain head"))
75
+
76
+
77
+ def load_head(connection: sqlite3.Connection) -> LedgerHead:
78
+ """Read the durable state row without changing the transaction."""
79
+ state = connection.execute("SELECT chain_id, chain_sequence, chain_head FROM ledger_state WHERE singleton = 1")
80
+ row = state.fetchone()
81
+ if row is None:
82
+ raise ValidationError("the ledger chain state is missing")
83
+ raw = LedgerHead(CHAIN_FORMAT, *tuple(row))
84
+ normalized = checked_head(raw)
85
+ if raw != normalized:
86
+ raise ValidationError("the ledger chain state is not in canonical form")
87
+ return normalized
88
+
89
+
90
+ def leaf_hash(nonce: str, fields: tuple[object, ...]) -> str:
91
+ normalized_nonce = checked_sha256(nonce, "chain nonce")
92
+ if nonce != normalized_nonce:
93
+ raise ValidationError("chain nonce is not in canonical form")
94
+ return sha256(_LEAF_DOMAIN + bytes.fromhex(nonce) + _canonical(fields)).hexdigest()
95
+
96
+
97
+ def commit_hash(
98
+ ledger_id: str, sequence: int, recorded_at: str, operation: str, previous_head: str,
99
+ members: Iterable[str | tuple[int, int]],
100
+ ) -> str:
101
+ """Hash the canonical commit frame while streaming one member at a time."""
102
+ digest = sha256(_COMMIT_DOMAIN)
103
+ digest.update(_canonical((ledger_id, sequence, recorded_at, operation, previous_head))[:-1] + b",[")
104
+ for position, member in enumerate(members):
105
+ if position:
106
+ digest.update(b",")
107
+ digest.update(_canonical(member))
108
+ digest.update(b"]]")
109
+ return digest.hexdigest()
110
+
111
+
112
+ def _write_commit(
113
+ connection: sqlite3.Connection, previous: LedgerHead, recorded_at: str, operation: str,
114
+ members: Iterable[str | tuple[int, int]],
115
+ ) -> LedgerHead:
116
+ sequence = previous.sequence + 1
117
+ digest = commit_hash(previous.ledger_id, sequence, recorded_at, operation, previous.sha256, members)
118
+ connection.execute("INSERT INTO chain_commit VALUES (?, ?, ?, ?, ?)",
119
+ (sequence, recorded_at, operation, previous.sha256, digest))
120
+ connection.execute(
121
+ "UPDATE ledger_state SET chain_id = ?, chain_sequence = ?, chain_head = ? WHERE singleton = 1",
122
+ (previous.ledger_id, sequence, digest),
123
+ )
124
+ return LedgerHead(CHAIN_FORMAT, previous.ledger_id, sequence, digest)
125
+
126
+
127
+ def _attach_revisions(
128
+ connection: sqlite3.Connection, sequence: int, rows: Iterable[sqlite3.Row | tuple],
129
+ ) -> Iterator[str]:
130
+ for ordinal, row in enumerate(rows, start=1):
131
+ nonce = token_hex(32)
132
+ leaf = leaf_hash(nonce, tuple(row[1:]))
133
+ connection.execute(
134
+ "INSERT INTO chain_member (sequence, ordinal, leaf_sha256) VALUES (?, ?, ?)", (sequence, ordinal, leaf),
135
+ )
136
+ connection.execute("INSERT INTO chain_link VALUES (?, ?, ?, ?)", (row[0], sequence, ordinal, nonce))
137
+ yield leaf
138
+
139
+
140
+ def initialize_chain(connection: sqlite3.Connection, recorded_at: str) -> LedgerHead:
141
+ """Commit all retained revisions as a migration baseline without rewriting them."""
142
+ _recording_time(recorded_at)
143
+ for statement in _SCHEMA:
144
+ connection.execute(statement)
145
+ previous = LedgerHead(CHAIN_FORMAT, token_hex(16), 0, GENESIS_HEAD)
146
+ rows = connection.execute(f"SELECT row_id, {_FIELDS} FROM evidence_revision ORDER BY id COLLATE BINARY, revision")
147
+ return _write_commit(connection, previous, recorded_at, "baseline", _attach_revisions(connection, 1, rows))
148
+
149
+
150
+ def _prior_commit(connection: sqlite3.Connection, recorded_at: str) -> LedgerHead:
151
+ _recording_time(recorded_at)
152
+ previous = load_head(connection)
153
+ bounded_integer(previous.sequence + 1, "new chain sequence", 2, _MAX_SEQUENCE)
154
+ row = connection.execute("SELECT recorded_at, sha256 FROM chain_commit WHERE sequence = ?",
155
+ (previous.sequence,)).fetchone()
156
+ if row is None or row[1] != previous.sha256:
157
+ raise ValidationError("ledger chain head does not match its stored commit")
158
+ if recorded_at <= _recording_time(row[0]):
159
+ raise ValidationError("a chain commit must follow the previous recording time")
160
+ return previous
161
+
162
+
163
+ def _write_rows(connection: sqlite3.Connection, row_ids: Sequence[int]) -> Iterator[tuple | sqlite3.Row]:
164
+ for row_id in row_ids:
165
+ row = connection.execute(f"SELECT row_id, {_FIELDS} FROM evidence_revision WHERE row_id = ?",
166
+ (row_id,)).fetchone()
167
+ if row is None:
168
+ raise ValidationError("a revision to be committed is missing")
169
+ yield row
170
+
171
+
172
+ def record_revisions(connection: sqlite3.Connection, recorded_at: str, row_ids: Sequence[int]) -> LedgerHead:
173
+ """Append one commitment frame for the supplied transaction's write order."""
174
+ if not row_ids:
175
+ raise ValidationError("a write commitment requires at least one revision")
176
+ previous = _prior_commit(connection, recorded_at)
177
+ members = _attach_revisions(connection, previous.sequence + 1, _write_rows(connection, row_ids))
178
+ return _write_commit(connection, previous, recorded_at, "write", members)
179
+
180
+
181
+ def _purge_members(
182
+ connection: sqlite3.Connection, sequence: int, identifier: str,
183
+ ) -> Iterator[tuple[int, int]]:
184
+ fields = ", ".join(f"r.{name}" for name in REVISION_COLUMNS)
185
+ rows = connection.execute(f"""
186
+ SELECT l.sequence, l.ordinal, l.nonce, m.leaf_sha256, c.operation, {fields}
187
+ FROM evidence_revision AS r
188
+ LEFT JOIN chain_link AS l ON l.row_id = r.row_id
189
+ LEFT JOIN chain_member AS m ON m.sequence = l.sequence AND m.ordinal = l.ordinal
190
+ AND m.target_sequence IS NULL AND m.target_ordinal IS NULL
191
+ LEFT JOIN chain_commit AS c ON c.sequence = l.sequence
192
+ WHERE r.id = ? ORDER BY l.sequence, l.ordinal
193
+ """, (identifier,))
194
+ ordinal = 0
195
+ for ordinal, row in enumerate(rows, start=1):
196
+ target_sequence, target_ordinal, nonce, saved_leaf, operation = row[:5]
197
+ if (type(target_sequence) is not int or not 1 <= target_sequence < sequence
198
+ or type(target_ordinal) is not int or target_ordinal < 1
199
+ or operation not in ("baseline", "write")
200
+ or not isinstance(nonce, str) or not isinstance(saved_leaf, str)):
201
+ raise ValidationError("the purge target has a missing or malformed chain link")
202
+ validated_leaf = checked_sha256(saved_leaf, "purge target commitment")
203
+ if saved_leaf != validated_leaf or not compare_digest(saved_leaf, leaf_hash(nonce, tuple(row[5:]))):
204
+ raise ValidationError("the purge target does not match its committed revision")
205
+ connection.execute(
206
+ "INSERT INTO chain_member (sequence, ordinal, target_sequence, target_ordinal) VALUES (?, ?, ?, ?)",
207
+ (sequence, ordinal, target_sequence, target_ordinal),
208
+ )
209
+ yield target_sequence, target_ordinal
210
+ if not ordinal:
211
+ raise ValidationError("a purge commitment requires at least one retained revision")
212
+
213
+
214
+ def record_purge(connection: sqlite3.Connection, recorded_at: str, identifier: str) -> LedgerHead:
215
+ """Commit opaque purge references and erase the live links before row deletion."""
216
+ previous = _prior_commit(connection, recorded_at)
217
+ members = _purge_members(connection, previous.sequence + 1, identifier)
218
+ head = _write_commit(connection, previous, recorded_at, "purge", members)
219
+ connection.execute(
220
+ "DELETE FROM chain_link WHERE row_id IN (SELECT row_id FROM evidence_revision WHERE id = ?)", (identifier,),
221
+ )
222
+ return head
ucde/chain_audit.py ADDED
@@ -0,0 +1,210 @@
1
+ """Read-only verification of schema 3 commit and revision commitments."""
2
+
3
+ from collections.abc import Callable, Iterable, Iterator
4
+ from hmac import compare_digest
5
+ from itertools import chain, groupby
6
+ import sqlite3
7
+
8
+ from .chain import GENESIS_HEAD, REVISION_COLUMNS, checked_head, commit_hash, leaf_hash, load_head
9
+ from .model import LedgerHead, ValidationError, bounded_integer, checked_sha256, timestamp
10
+
11
+
12
+ _MAX_SQLITE_INTEGER = 2**63 - 1
13
+
14
+
15
+ def _normalized_time(value: object, name: str) -> str:
16
+ if not isinstance(value, str) or timestamp(value, name) != value:
17
+ raise ValidationError(f"{name} must be a normalized UTC timestamp")
18
+ return value
19
+
20
+
21
+ def _stored_digest(value: object, name: str) -> str:
22
+ normalized = checked_sha256(value, name)
23
+ if normalized != value:
24
+ raise ValidationError(f"{name} must be lowercase")
25
+ return normalized
26
+
27
+
28
+ def _audit_links(connection: sqlite3.Connection, report: Callable[[str], None]) -> None:
29
+ for message, query in (
30
+ ("duplicate commit sequences", """
31
+ SELECT count(*) FROM (
32
+ SELECT sequence FROM chain_commit GROUP BY sequence HAVING count(*) > 1
33
+ )
34
+ """),
35
+ ("members without a commit", """
36
+ SELECT count(*) FROM chain_member AS m
37
+ LEFT JOIN chain_commit AS c ON c.sequence = m.sequence
38
+ WHERE c.sequence IS NULL
39
+ """),
40
+ ("revision links without a retained leaf and evidence row", """
41
+ SELECT count(*) FROM chain_link AS l
42
+ LEFT JOIN chain_member AS m ON m.sequence = l.sequence AND m.ordinal = l.ordinal
43
+ LEFT JOIN chain_commit AS c ON c.sequence = l.sequence
44
+ LEFT JOIN evidence_revision AS r ON r.row_id = l.row_id
45
+ WHERE r.row_id IS NULL OR m.leaf_sha256 IS NULL
46
+ OR c.sequence IS NULL OR c.operation NOT IN ('baseline', 'write')
47
+ """),
48
+ ("retained revisions missing a chain link", """
49
+ SELECT count(*) FROM evidence_revision AS r
50
+ LEFT JOIN chain_link AS l ON l.row_id = r.row_id
51
+ WHERE l.row_id IS NULL
52
+ """),
53
+ ("evidence rows with duplicate chain links", """
54
+ SELECT count(*) FROM (
55
+ SELECT row_id FROM chain_link GROUP BY row_id HAVING count(*) > 1
56
+ )
57
+ """),
58
+ ):
59
+ count = connection.execute(query).fetchone()[0]
60
+ if count:
61
+ report(f"chain has {count} {message}")
62
+
63
+
64
+ def _check_leaf(
65
+ row: sqlite3.Row, operation: str, recorded_at: str, prefix: str, report: Callable[[str], None],
66
+ ) -> str:
67
+ leaf = _stored_digest(row["leaf_sha256"], "revision commitment")
68
+ if row["target_sequence"] is not None or row["target_ordinal"] is not None:
69
+ raise ValidationError("revision commitment contains a purge coordinate")
70
+ if row["evidence_row_id"] is not None:
71
+ evidence_time = _normalized_time(row["recorded_at"], "revision recording time")
72
+ if evidence_time > recorded_at or (operation == "write" and evidence_time != recorded_at):
73
+ report(f"{prefix}: revision recording time disagrees with its chain commit")
74
+ nonce = _stored_digest(row["nonce"], "revision nonce")
75
+ try:
76
+ digest = leaf_hash(nonce, tuple(row[column] for column in REVISION_COLUMNS))
77
+ except (TypeError, ValueError, RecursionError) as error:
78
+ raise ValidationError("retained evidence cannot be encoded as a revision commitment") from error
79
+ if not compare_digest(leaf, digest):
80
+ report(f"{prefix}: revision commitment does not match retained evidence")
81
+ return leaf
82
+
83
+
84
+ def _members(
85
+ rows: Iterable[sqlite3.Row], sequence: int, recorded_at: str, operation: str,
86
+ missing: set[tuple[int, int]], purged: set[tuple[int, int]], report: Callable[[str], None],
87
+ ) -> Iterator[str | tuple[int, int]]:
88
+ has_members = False
89
+ for position, row in enumerate(rows, 1):
90
+ if row["member_sequence"] is None:
91
+ continue
92
+ has_members = True
93
+ prefix = f"chain commit {sequence} member {position}"
94
+ try:
95
+ ordinal = bounded_integer(row["ordinal"], "member ordinal", 1, _MAX_SQLITE_INTEGER)
96
+ if ordinal != position:
97
+ report(f"{prefix} is out of ordinal order")
98
+ if operation == "purge":
99
+ if row["leaf_sha256"] is not None:
100
+ raise ValidationError("purge member contains a revision commitment")
101
+ coordinate = (
102
+ bounded_integer(row["target_sequence"], "purge target sequence", 1, sequence - 1),
103
+ bounded_integer(row["target_ordinal"], "purge target ordinal", 1, _MAX_SQLITE_INTEGER),
104
+ )
105
+ if coordinate in purged:
106
+ report(f"{prefix} repeats a purge target")
107
+ elif coordinate not in missing:
108
+ report(f"{prefix} is a purge of an unknown or still retained revision")
109
+ else:
110
+ missing.remove(coordinate)
111
+ purged.add(coordinate)
112
+ yield coordinate
113
+ else:
114
+ leaf = _check_leaf(row, operation, recorded_at, prefix, report)
115
+ if row["evidence_row_id"] is None:
116
+ missing.add((sequence, ordinal))
117
+ yield leaf
118
+ except ValidationError as error:
119
+ report(f"{prefix}: {error}")
120
+ if not has_members and operation != "baseline":
121
+ report(f"chain commit {sequence} {operation} has no members")
122
+
123
+
124
+ def audit_chain(
125
+ connection: sqlite3.Connection, report: Callable[[str], None], expected_head: LedgerHead | None = None,
126
+ ) -> None:
127
+ """Check the full internal chain and, optionally, an independently saved prefix."""
128
+ expected = checked_head(expected_head) if expected_head is not None else None
129
+ try:
130
+ _audit_chain(connection, report, expected)
131
+ except (sqlite3.DatabaseError, ValidationError) as error:
132
+ report(f"chain could not be verified: {error}")
133
+
134
+
135
+ def _audit_chain(
136
+ connection: sqlite3.Connection, report: Callable[[str], None], expected: LedgerHead | None,
137
+ ) -> None:
138
+ head = load_head(connection)
139
+ if expected is not None and expected.ledger_id != head.ledger_id:
140
+ report("saved chain head has a different ledger identity")
141
+ expected = None
142
+
143
+ _audit_links(connection, report)
144
+ missing: set[tuple[int, int]] = set()
145
+ purged: set[tuple[int, int]] = set()
146
+ final_sequence, final_digest = 0, GENESIS_HEAD
147
+ final_time: str | None = None
148
+ anchored_digest = None
149
+ empty_baseline = False
150
+ fields = ", ".join("r." + column for column in REVISION_COLUMNS)
151
+ cursor = connection.cursor()
152
+ cursor.row_factory = sqlite3.Row
153
+ rows = cursor.execute(f"""
154
+ SELECT c.sequence AS commit_sequence, c.recorded_at AS commit_time, c.operation,
155
+ c.previous_head, c.sha256 AS commit_digest,
156
+ m.sequence AS member_sequence, m.ordinal, m.leaf_sha256, m.target_sequence, m.target_ordinal,
157
+ l.nonce, r.row_id AS evidence_row_id, {fields}
158
+ FROM chain_commit AS c
159
+ LEFT JOIN chain_member AS m ON m.sequence = c.sequence
160
+ LEFT JOIN chain_link AS l ON l.sequence = m.sequence AND l.ordinal = m.ordinal
161
+ LEFT JOIN evidence_revision AS r ON r.row_id = l.row_id
162
+ ORDER BY c.sequence, m.ordinal
163
+ """)
164
+
165
+ for raw_sequence, group in groupby(rows, key=lambda row: row["commit_sequence"]):
166
+ try:
167
+ sequence = bounded_integer(raw_sequence, "commit sequence", 1, _MAX_SQLITE_INTEGER)
168
+ except ValidationError as error:
169
+ report(f"chain {error}")
170
+ continue
171
+ members = iter(group)
172
+ first = next(members)
173
+ if sequence != final_sequence + 1:
174
+ report(f"chain commit {sequence} is out of sequence")
175
+ final_sequence = sequence
176
+ try:
177
+ recorded_at = _normalized_time(first["commit_time"], "commit recording time")
178
+ if final_time is not None and recorded_at <= final_time:
179
+ report(f"chain commit {sequence} does not advance recording time")
180
+ final_time = recorded_at
181
+ operation = first["operation"]
182
+ if operation not in (("baseline",) if sequence == 1 else ("write", "purge")):
183
+ raise ValidationError("commit operation is not valid at this sequence")
184
+ empty_baseline = sequence == 1 and first["member_sequence"] is None
185
+ previous_head = _stored_digest(first["previous_head"], "previous commit digest")
186
+ if not compare_digest(previous_head, final_digest):
187
+ report(f"chain commit {sequence} does not reference the preceding digest")
188
+ final_digest = _stored_digest(first["commit_digest"], "commit digest")
189
+ entries = _members(chain((first,), members), sequence, recorded_at, operation, missing, purged, report)
190
+ digest = commit_hash(head.ledger_id, sequence, recorded_at, operation, previous_head, entries)
191
+ if not compare_digest(digest, final_digest):
192
+ report(f"chain commit {sequence} digest disagrees with its members")
193
+ if expected is not None and sequence == expected.sequence:
194
+ anchored_digest = digest
195
+ except ValidationError as error:
196
+ report(f"chain commit {sequence}: {error}")
197
+
198
+ if missing:
199
+ report(f"chain has {len(missing)} missing revisions without a valid purge")
200
+ if (head.sequence, head.sha256) != (final_sequence, final_digest):
201
+ report("chain state head does not match the final commit")
202
+ state = connection.execute("SELECT last_recorded FROM ledger_state WHERE singleton = 1").fetchone()
203
+ watermark = state[0] if state is not None else None
204
+ if watermark != final_time and not (head.sequence == 1 and empty_baseline and watermark == ""):
205
+ report("chain recording time does not match the ledger watermark")
206
+ if expected is not None:
207
+ if expected.sequence > final_sequence:
208
+ report("saved chain head is ahead of this ledger")
209
+ elif anchored_digest is None or not compare_digest(expected.sha256, anchored_digest):
210
+ report("saved chain head does not match the ledger at its sequence")