File size: 11,316 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
"""Crash-resumable, idempotent completion-token accounting."""

from __future__ import annotations

import json
from collections.abc import Iterable
from dataclasses import dataclass
from pathlib import Path
from typing import Any

from ..atomic_io import atomic_write_json
from ..hashing import canonical_json_hash, is_sha256


class LedgerError(RuntimeError):
    """Raised on cap overflow, identity drift, or corrupted resume state."""


@dataclass(frozen=True)
class CompletionEntry:
    completion_id: str
    token_count: int
    slot_id: str | None = None
    generation_index: int | None = None
    completion_sha256: str | None = None

    def to_dict(self) -> dict[str, Any]:
        row: dict[str, Any] = {
            "completion_id": self.completion_id,
            "token_count": self.token_count,
        }
        if self.slot_id is not None:
            row["slot_id"] = self.slot_id
        if self.generation_index is not None:
            row["generation_index"] = self.generation_index
        if self.completion_sha256 is not None:
            row["completion_sha256"] = self.completion_sha256
        return row


def completion_id(run_id: str, slot_id: str, generation_index: int) -> str:
    if not run_id or not slot_id:
        raise LedgerError("run_id and slot_id must be non-empty")
    if (
        isinstance(generation_index, bool)
        or not isinstance(generation_index, int)
        or generation_index < 0
    ):
        raise LedgerError("generation_index must be a non-negative integer")
    return canonical_json_hash(
        {
            "schema_version": 1,
            "run_id": run_id,
            "slot_id": slot_id,
            "generation_index": generation_index,
        }
    )


class CompletionTokenLedger:
    """Idempotent ledger whose state can be atomically checkpointed and resumed."""

    SCHEMA_VERSION = 1

    def __init__(
        self,
        *,
        run_id: str,
        max_tokens: int,
        config_sha256: str | None = None,
        data_manifest_sha256: str | None = None,
        comparison_slot_manifest_sha256: str | None = None,
    ) -> None:
        if not run_id:
            raise LedgerError("run_id must be non-empty")
        if isinstance(max_tokens, bool) or not isinstance(max_tokens, int) or max_tokens <= 0:
            raise LedgerError("max_tokens must be a positive integer")
        for name, value in (
            ("config_sha256", config_sha256),
            ("data_manifest_sha256", data_manifest_sha256),
            ("comparison_slot_manifest_sha256", comparison_slot_manifest_sha256),
        ):
            if value is not None and not is_sha256(value):
                raise LedgerError(f"{name} is not a SHA-256")
        self.run_id = run_id
        self.max_tokens = max_tokens
        self.config_sha256 = config_sha256
        self.data_manifest_sha256 = data_manifest_sha256
        self.comparison_slot_manifest_sha256 = comparison_slot_manifest_sha256
        self._entries: dict[str, CompletionEntry] = {}
        self._consumed = 0

    @property
    def consumed_tokens(self) -> int:
        return self._consumed

    @property
    def remaining_tokens(self) -> int:
        return self.max_tokens - self._consumed

    @property
    def exhausted(self) -> bool:
        return self._consumed >= self.max_tokens

    @property
    def completion_count(self) -> int:
        return len(self._entries)

    def record(
        self,
        completion_key: str,
        token_count: int,
        *,
        slot_id: str | None = None,
        generation_index: int | None = None,
        completion_sha256: str | None = None,
    ) -> bool:
        """Record once; exact duplicates are resume-safe no-ops.

        Returns ``True`` for a new record and ``False`` for an identical replay.
        Reusing an ID with different metadata is corruption and fails.
        """

        return self.record_many(
            [
                CompletionEntry(
                    completion_id=completion_key,
                    token_count=token_count,
                    slot_id=slot_id,
                    generation_index=generation_index,
                    completion_sha256=completion_sha256,
                )
            ]
        )[0]

    def record_many(self, entries: Iterable[CompletionEntry]) -> tuple[bool, ...]:
        pending = list(entries)
        seen_pending: dict[str, CompletionEntry] = {}
        results: list[bool] = []
        new_tokens = 0
        for entry in pending:
            if not isinstance(entry.completion_id, str) or not entry.completion_id:
                raise LedgerError("completion_id must be non-empty")
            if (
                isinstance(entry.token_count, bool)
                or not isinstance(entry.token_count, int)
                or entry.token_count < 0
            ):
                raise LedgerError("token_count must be a non-negative integer")
            if entry.generation_index is not None and (
                isinstance(entry.generation_index, bool)
                or not isinstance(entry.generation_index, int)
                or entry.generation_index < 0
            ):
                raise LedgerError("generation_index must be a non-negative integer")
            if entry.slot_id is not None and (
                not isinstance(entry.slot_id, str) or not entry.slot_id
            ):
                raise LedgerError("slot_id must be a non-empty string when supplied")
            if entry.completion_sha256 is not None and not is_sha256(entry.completion_sha256):
                raise LedgerError("completion_sha256 must be a SHA-256 when supplied")
            existing = self._entries.get(entry.completion_id) or seen_pending.get(
                entry.completion_id
            )
            if existing is not None:
                if existing != entry:
                    raise LedgerError(
                        f"completion_id {entry.completion_id} was reused with different metadata"
                    )
                results.append(False)
                continue
            seen_pending[entry.completion_id] = entry
            new_tokens += entry.token_count
            results.append(True)
        if self._consumed + new_tokens > self.max_tokens:
            raise LedgerError(
                f"completion-token cap exceeded: {self._consumed}+{new_tokens}>{self.max_tokens}"
            )
        for entry in seen_pending.values():
            self._entries[entry.completion_id] = entry
        self._consumed += new_tokens
        return tuple(results)

    def to_dict(self) -> dict[str, Any]:
        entries = [self._entries[key].to_dict() for key in sorted(self._entries)]
        return {
            "schema_version": self.SCHEMA_VERSION,
            "run_id": self.run_id,
            "max_tokens": self.max_tokens,
            "consumed_tokens": self._consumed,
            "config_sha256": self.config_sha256,
            "data_manifest_sha256": self.data_manifest_sha256,
            "comparison_slot_manifest_sha256": self.comparison_slot_manifest_sha256,
            "entries": entries,
        }

    def save(self, path: str | Path) -> None:
        atomic_write_json(path, self.to_dict())

    @classmethod
    def load(
        cls,
        path: str | Path,
        *,
        expected_run_id: str | None = None,
        expected_max_tokens: int | None = None,
        expected_config_sha256: str | None = None,
        expected_data_manifest_sha256: str | None = None,
        expected_comparison_slot_manifest_sha256: str | None = None,
    ) -> CompletionTokenLedger:
        source = Path(path)
        try:
            value = json.loads(source.read_text(encoding="utf-8"))
        except (OSError, json.JSONDecodeError) as exc:
            raise LedgerError(f"cannot load ledger {source}: {exc}") from exc
        if not isinstance(value, dict) or value.get("schema_version") != cls.SCHEMA_VERSION:
            raise LedgerError("unsupported ledger schema")
        try:
            raw_max_tokens = value.get("max_tokens", 0)
            if isinstance(raw_max_tokens, bool) or not isinstance(raw_max_tokens, int):
                raise TypeError("max_tokens is not an integer")
            ledger = cls(
                run_id=str(value.get("run_id", "")),
                max_tokens=raw_max_tokens,
                config_sha256=value.get("config_sha256"),
                data_manifest_sha256=value.get("data_manifest_sha256"),
                comparison_slot_manifest_sha256=value.get("comparison_slot_manifest_sha256"),
            )
        except (TypeError, ValueError, LedgerError) as exc:
            raise LedgerError(f"invalid ledger header: {exc}") from exc
        checks = (
            ("run_id", expected_run_id, ledger.run_id),
            ("max_tokens", expected_max_tokens, ledger.max_tokens),
            ("config_sha256", expected_config_sha256, ledger.config_sha256),
            (
                "data_manifest_sha256",
                expected_data_manifest_sha256,
                ledger.data_manifest_sha256,
            ),
            (
                "comparison_slot_manifest_sha256",
                expected_comparison_slot_manifest_sha256,
                ledger.comparison_slot_manifest_sha256,
            ),
        )
        for name, expected, actual in checks:
            if expected is not None and expected != actual:
                raise LedgerError(f"resume {name} mismatch: {actual!r} != {expected!r}")

        raw_entries = value.get("entries")
        if not isinstance(raw_entries, list):
            raise LedgerError("ledger entries must be a list")
        entries: list[CompletionEntry] = []
        for raw in raw_entries:
            if not isinstance(raw, dict):
                raise LedgerError("ledger entry must be an object")
            try:
                token_count = raw.get("token_count", -1)
                generation_index = raw.get("generation_index")
                if isinstance(token_count, bool) or not isinstance(token_count, int):
                    raise TypeError("token_count is not an integer")
                if generation_index is not None and (
                    isinstance(generation_index, bool) or not isinstance(generation_index, int)
                ):
                    raise TypeError("generation_index is not an integer")
                entries.append(
                    CompletionEntry(
                        completion_id=str(raw.get("completion_id", "")),
                        token_count=token_count,
                        slot_id=raw.get("slot_id"),
                        generation_index=generation_index,
                        completion_sha256=raw.get("completion_sha256"),
                    )
                )
            except (TypeError, ValueError) as exc:
                raise LedgerError(f"invalid ledger entry: {exc}") from exc
        ledger.record_many(entries)
        raw_consumed = value.get("consumed_tokens")
        if isinstance(raw_consumed, bool) or not isinstance(raw_consumed, int):
            raise LedgerError("ledger consumed_tokens must be an integer")
        if ledger.consumed_tokens != raw_consumed:
            raise LedgerError("ledger consumed_tokens does not equal entry sum")
        return ledger