File size: 29,262 Bytes
651b674
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
"""A causal, transactional session around interchangeable extraction components.

Every new/revised turn re-extracts the available prefix. The default full-prefix
mode verifies every candidate; incremental mode reuses grounded decisions only
when its model-independent dependency policy permits it. Identical semantic facts
and dates are deduplicated across mentions; repeated actions are not inferred.
"""

from __future__ import annotations

from collections import defaultdict
from collections.abc import Callable
from copy import deepcopy
from datetime import datetime, timezone
import hashlib
import json
from threading import RLock
from typing import Any

ATTRIBUTES = frozenset({"service_state", "tariff", "ticket_status", "action", "agreement"})
SINGLE_VALUED = frozenset({"service_state", "tariff", "ticket_status"})
ENTITY_TYPES = frozenset({"service", "device", "ticket", "client"})
VERDICTS = frozenset({"supported", "refuted", "insufficient_evidence"})


def _require(condition: bool, message: str) -> None:
    if not condition:
        raise ValueError(message)


def _json(value: Any) -> str:
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))


def _timestamp(value: Any, field: str) -> datetime:
    _require(isinstance(value, str) and bool(value), f"{field} must be an ISO date or datetime")
    try:
        return datetime.fromisoformat(value)
    except ValueError as exc:
        raise ValueError(f"{field} must be an ISO date or datetime") from exc


class OnlineSession:
    """Process a single call, publishing only complete successful transactions.

    ``pack_builder(candidate, turns)`` returns the verifier's evidence pack.
    ``extractor.extract(call_id, started_at, turns)`` returns *all* candidates in
    that prefix. Call ``drain_trace`` after each event to persist diagnostics.
    The trace buffer has a hard bound and never silently discards records.
    """

    def __init__(
        self, call_id: str, started_at: str, extractor: Any, retriever: Any,
        verifier: Any, *, pack_builder: Callable[[dict, list[dict]], dict],
        max_turns: int = 1000, max_candidates: int = 500,
        max_turn_chars: int = 20000, max_trace_records: int = 5000,
        verification_mode: str = "full_prefix",
        final_refresh: bool = False,
    ) -> None:
        _require(isinstance(call_id, str) and bool(call_id.strip()), "call_id must be a nonempty string")
        self._anchor = _timestamp(started_at, "started_at")
        for name, value in (("max_turns", max_turns), ("max_candidates", max_candidates),
                            ("max_turn_chars", max_turn_chars), ("max_trace_records", max_trace_records)):
            _require(type(value) is int and value > 0, f"{name} must be a positive integer")
        _require(callable(getattr(extractor, "extract", None)), "extractor must provide extract()")
        _require(callable(getattr(verifier, "verify", None)), "verifier must provide verify()")
        _require(callable(pack_builder), "pack_builder must be callable")
        _require(isinstance(verification_mode, str) and verification_mode in {"full_prefix", "incremental_v1"}, "Unknown verification_mode")
        _require(type(final_refresh) is bool, "final_refresh must be a boolean")
        _require(not final_refresh or verification_mode == "incremental_v1", "final_refresh requires incremental_v1")
        model_id = getattr(verifier, "model_id", None)
        _require(isinstance(model_id, str) and bool(model_id), "verifier must expose a nonempty model_id")
        self.call_id, self.started_at = call_id, started_at
        self.extractor, self.retriever, self.verifier = extractor, retriever, verifier
        self.model_id = model_id
        self.pack_builder = pack_builder
        self.verification_mode = verification_mode
        self.final_refresh = final_refresh
        self.max_turns, self.max_candidates = max_turns, max_candidates
        self.max_turn_chars, self.max_trace_records = max_turn_chars, max_trace_records
        graph = getattr(retriever, "graph", {})
        self._graph_id = graph.get("graph_id") if isinstance(graph, dict) else None
        self._turns: dict[int, dict] = {}
        self._facts: dict[str, dict] = {}
        self._versions: dict[str, int] = {}
        self._pending: dict[str, dict] = {}
        self._decision_cache: dict[str, dict] = {}
        self._trace: list[dict] = []
        self._finished = False
        self._lock = RLock()
        self._verification_identity = self._component_identity()

    def _component_identity(self) -> dict:
        config = getattr(self.verifier, "config", None)
        to_dict = getattr(config, "to_dict", None)
        graph = getattr(self.retriever, "graph", {})
        return deepcopy({"model_id": getattr(self.verifier, "model_id", None),
                         "verification_mode": self.verification_mode, "final_refresh": self.final_refresh,
                         "prompt_sha256": getattr(self.verifier, "prompt_sha256", None),
                         "prompt_version": getattr(self.verifier, "prompt_version", None),
                         "config": to_dict() if callable(to_dict) else config,
                         "graph_id": graph.get("graph_id") if isinstance(graph, dict) else None,
                         "index": getattr(self.retriever, "manifest", None),
                         "pack_builder_identity": id(self.pack_builder)})

    @property
    def turns(self) -> list[dict]:
        with self._lock:
            return deepcopy([self._turns[idx] for idx in sorted(self._turns)])

    @property
    def facts(self) -> list[dict]:
        with self._lock:
            return [deepcopy(fact) for _, fact in sorted(self._facts.items(), key=lambda pair: self._fact_order(pair[1], pair[0]))]

    @property
    def pending_candidates(self) -> list[dict]:
        with self._lock:
            return deepcopy([self._pending[key] for key in sorted(self._pending)])

    @property
    def trace(self) -> list[dict]:
        """A copy of undrained diagnostics; prefer drain_trace for long calls."""
        with self._lock:
            return deepcopy(self._trace)

    @property
    def finished(self) -> bool:
        with self._lock:
            return self._finished

    def drain_trace(self) -> list[dict]:
        with self._lock:
            result = self._trace
            self._trace = []
            return result

    def ingest(self, turn: dict) -> list[dict]:
        """Accept a new turn or a strictly newer revision; publish atomically.

        On extractor, evidence, verifier or validation failure the input event is
        not consumed. Retrying it after fixing the component is safe. External
        model calls already made cannot be rolled back and may be repeated.
        Failed transactions do not publish trace records; their provider usage
        must be observed separately if failed-attempt cost is being measured.
        """
        with self._lock:
            incoming = self._normalize_turn(turn)
            previous = self._turns.get(incoming["idx"])
            if previous is not None:
                if incoming == previous:
                    return []
                _require(incoming["revision"] > previous["revision"], "A conflicting or older turn revision is not accepted")
            else:
                _require(not self._turns or incoming["idx"] > max(self._turns), "New turn indices must increase monotonically")
                _require(len(self._turns) < self.max_turns, "max_turns exceeded")
            _require(not self._finished, "The call is already finished")
            _require(getattr(self.verifier, "model_id", None) == self.model_id, "Verifier model_id cannot change inside a call")
            if "incremental_v1" in (self.verification_mode, self._verification_identity["verification_mode"]):
                _require(self._component_identity() == self._verification_identity,
                         "Verifier prompt/config or graph/context identity changed inside an incremental call")
            staged = deepcopy(self._turns)
            staged[incoming["idx"]] = incoming
            turns = [staged[idx] for idx in sorted(staged)]
            as_of_turn = max(staged)
            trigger = {"type": "turn_revised" if previous is not None else "turn_added",
                       "turn_idx": incoming["idx"], "revision": incoming["revision"], "as_of_turn": as_of_turn}
            facts, pending, records, evidence, decision_cache = self._evaluate(turns, trigger)
            events, versions = self._diff(facts, evidence, as_of_turn)
            # All component calls and checks succeeded. These are the only
            # mutations to the session's committed state.
            self._turns = staged
            self._facts = facts
            self._pending = pending
            self._versions = versions
            self._decision_cache = decision_cache
            self._trace.extend(records)
            return events

    def finish(self) -> list[dict]:
        """Complete the call, optionally refreshing stale decisions once.

        A failed final refresh publishes no facts, cache entries, trace or finish
        flag. A successful repeated finish never performs additional inference.
        """
        with self._lock:
            if self._finished:
                return []
            _require(len(self._trace) < self.max_trace_records, "Trace buffer is full; drain_trace() before finish()")
            if self.final_refresh or "incremental_v1" in (self.verification_mode, self._verification_identity["verification_mode"]):
                _require(self._component_identity() == self._verification_identity,
                         "Verifier prompt/config or graph/context identity changed inside an incremental call")
            events, records = [], []
            facts, pending, versions, decision_cache = self._facts, self._pending, self._versions, self._decision_cache
            if self.final_refresh and self._turns:
                _require(getattr(self.verifier, "model_id", None) == self.model_id, "Verifier model_id cannot change inside a call")
                turns = deepcopy([self._turns[idx] for idx in sorted(self._turns)])
                as_of_turn = turns[-1]["idx"]
                trigger = {"type": "call_finished", "turn_idx": as_of_turn,
                           "revision": turns[-1]["revision"], "as_of_turn": as_of_turn}
                facts, pending, records, evidence, decision_cache = self._evaluate(turns, trigger, finalize=True)
                events, versions = self._diff(facts, evidence, as_of_turn)
            record = {"type": "finished", "call_id": self.call_id,
                      "as_of_turn": max(self._turns) if self._turns else None,
                      "model_id": self.model_id, "fact_count": len(facts),
                      "pending_claim_ids": sorted(pending)}
            _require(len(self._trace) + len(records) + 1 <= self.max_trace_records,
                     "Trace buffer would overflow; drain_trace() before finish()")
            self._facts, self._pending = facts, pending
            self._versions, self._decision_cache = versions, decision_cache
            self._trace.extend(records)
            self._trace.append(record)
            self._finished = True
            return events

    def _normalize_turn(self, turn: Any) -> dict:
        _require(isinstance(turn, dict), "turn must be an object")
        idx, revision = turn.get("idx"), turn.get("revision", 0)
        _require(type(idx) is int and idx >= 0, "turn.idx must be a nonnegative integer")
        _require(type(revision) is int and revision >= 0, "turn.revision must be a nonnegative integer")
        _require(isinstance(turn.get("speaker"), str) and turn["speaker"] in {"client", "operator"}, "turn.speaker must be client or operator")
        text = turn.get("text")
        _require(isinstance(text, str) and len(text) <= self.max_turn_chars, "turn.text is invalid or exceeds max_turn_chars")
        return {"idx": idx, "speaker": turn["speaker"], "text": text, "revision": revision}

    def _reference(self, reference: Any, turns: dict[int, dict], label: str) -> None:
        _require(isinstance(reference, dict), f"{label} must be an object")
        idx = reference.get("turn_idx")
        _require(type(idx) is int and idx in turns, f"{label} refers to a turn outside the current prefix")
        span = reference.get("span")
        _require(isinstance(span, (list, tuple)) and len(span) == 2 and all(type(value) is int for value in span),
                 f"{label}.span must contain two integer offsets")
        first, last = span
        text = turns[idx]["text"]
        _require(0 <= first < last <= len(text), f"{label}.span is outside the original turn")
        _require(reference.get("quote") == text[first:last], f"{label}.quote does not match the original turn")

    def _candidate(self, candidate: Any, turns: dict[int, dict]) -> dict:
        _require(isinstance(candidate, dict), "extractor candidates must be objects")
        candidate = deepcopy(candidate)
        _require(isinstance(candidate.get("claim_id"), str) and bool(candidate["claim_id"]), "candidate.claim_id is required")
        _require(candidate.get("call_id") == self.call_id, "Candidate belongs to another call")
        obj = candidate.get("object")
        _require(isinstance(obj, dict) and isinstance(obj.get("type"), str) and obj["type"] in ENTITY_TYPES and isinstance(obj.get("name"), str),
                 "Candidate object must have a supported type and a name")
        if "id" in obj:
            _require(isinstance(obj["id"], str) and bool(obj["id"]), "Candidate object.id must be nonempty when supplied")
        _require(isinstance(candidate.get("attribute"), str) and candidate["attribute"] in ATTRIBUTES, "Unsupported candidate attribute")
        _require(isinstance(candidate.get("raw_value"), str) and bool(candidate["raw_value"].strip()), "Candidate raw_value must be nonempty")
        canonical = candidate.get("canonical_value")
        _require(canonical is None or isinstance(canonical, str) and bool(canonical.strip()), "Invalid canonical_value")
        _require(type(candidate.get("polarity")) is int and candidate["polarity"] in {-1, 1}, "Candidate polarity must be -1 or 1")
        _require(isinstance(candidate.get("extractor_version"), str) and bool(candidate["extractor_version"]), "extractor_version is required")
        self._reference(candidate.get("source"), turns, "candidate.source")
        source_turn = turns[candidate["source"]["turn_idx"]]
        _require(candidate.get("speaker") == source_turn["speaker"], "Candidate speaker differs from its source turn")
        _require(type(candidate.get("turn_revision")) is int and candidate["turn_revision"] == source_turn["revision"],
                 "Candidate refers to a stale turn revision")
        self._moment(candidate.get("valid_from"), "candidate.valid_from")
        if candidate.get("valid_to") is not None:
            _require(self._moment(candidate["valid_to"], "candidate.valid_to") >= self._moment(candidate["valid_from"]),
                     "Candidate valid_to is before valid_from")
        return candidate

    def _pack(self, candidate: dict, turns: list[dict]) -> dict:
        pack = self.pack_builder(deepcopy(candidate), deepcopy(turns))
        _require(isinstance(pack, dict), "pack_builder must return an object")
        pack = deepcopy(pack)
        _require(pack.get("candidate") == candidate, "Evidence pack changed the candidate")
        _require(pack.get("started_at") == self.started_at, "Evidence pack changed started_at")
        by_idx = {turn["idx"]: turn for turn in turns}
        _require(pack.get("as_of_turn") == max(by_idx), "Evidence pack has an incorrect prefix boundary")
        if self._graph_id is not None:
            _require(pack.get("graph_id") == self._graph_id, "Evidence pack graph version changed")
        evidence = pack.get("dialogue_evidence")
        _require(isinstance(evidence, list), "Evidence pack must contain dialogue_evidence")
        seen = set()
        for turn in evidence:
            _require(isinstance(turn, dict), "Dialogue evidence entries must be turns")
            idx = turn.get("idx", turn.get("turn_idx"))
            _require(type(idx) is int and idx in by_idx, "Evidence pack contains a turn outside the current prefix")
            _require(idx not in seen, "Evidence pack repeats a turn")
            seen.add(idx)
            original = by_idx[idx]
            _require(turn.get("text") == original["text"] and turn.get("speaker") == original["speaker"]
                     and turn.get("revision", 0) == original["revision"], "Evidence pack changed a turn or its revision")
        _require(candidate["source"]["turn_idx"] in seen, "Evidence pack omitted the candidate's source turn")
        return pack

    def _evaluate(self, turns: list[dict], trigger: dict, *, finalize: bool = False) -> tuple[dict, dict, list[dict], dict, dict]:
        from compact_fact_extraction.verification.client import validate_decision

        extracted = self.extractor.extract(self.call_id, self.started_at, deepcopy(turns))
        _require(isinstance(extracted, list), "extractor.extract() must return a list of all prefix candidates")
        _require(len(extracted) <= self.max_candidates, "max_candidates exceeded")
        _require(len(self._trace) + len(extracted) + 1 + int(finalize) <= self.max_trace_records,
                 "Trace buffer would overflow; drain_trace() before ingest()")
        by_idx = {turn["idx"]: turn for turn in turns}
        candidates: dict[str, dict] = {}
        for raw in extracted:
            candidate = self._candidate(raw, by_idx)
            claim_id = candidate["claim_id"]
            _require(claim_id not in candidates, f"Duplicate claim_id in extractor output: {claim_id}")
            candidates[claim_id] = candidate
        records, supported, pending, next_cache = [], [], {}, {}
        for claim_id in sorted(candidates):
            candidate = candidates[claim_id]
            cached = self._decision_cache.get(claim_id)
            reason = "full_prefix"
            if finalize:
                reason = "final_context" if (cached is None or cached["candidate"] != candidate
                                               or cached["pack"]["as_of_turn"] != trigger["as_of_turn"]) else None
            elif self.verification_mode == "incremental_v1":
                from .scheduling import reverification_reason

                # This internal policy is a pure, read-only function. Passing
                # the existing snapshots avoids copying the entire candidate
                # set for each claim; verifier inputs remain isolated below.
                reason = reverification_reason(candidate, cached, turns, trigger, candidates)
                _require(reason is None or isinstance(reason, str) and bool(reason), "Invalid reverification reason")
            reused = reason is None
            if reused:
                _require(cached is not None and cached["candidate"] == candidate, "Cached candidate content changed")
                # Committed entries are private immutable snapshots. Consumers
                # receive copies below; reuse need not clone or rehash a pack.
                pack = cached["pack"]
                _require(pack.get("candidate") == candidate and pack.get("started_at") == self.started_at,
                         "Cached evidence pack identity changed")
                # Validate against the original verified pack; never invent a
                # new inference prefix or input hash for a cached decision.
                decision = validate_decision(cached["decision"], pack)
                for evidence_turn in pack["dialogue_evidence"]:
                    idx = evidence_turn["idx"]
                    _require(idx in by_idx and all(evidence_turn.get(key, 0 if key == "revision" else None) == by_idx[idx][key]
                                                   for key in ("speaker", "text", "revision")),
                             "Cached evidence contains a changed or stale dialogue turn")
                verifier_metadata = cached["verifier_metadata"]
            else:
                pack = self._pack(candidate, turns)
                raw_decision = self.verifier.verify(deepcopy(pack))
                decision = validate_decision(raw_decision, pack)
                verifier_metadata = deepcopy(getattr(self.verifier, "last_metadata", {}))
            _require(isinstance(decision, dict) and isinstance(decision.get("verdict"), str) and decision["verdict"] in VERDICTS, "Invalid validated verifier decision")
            _require(isinstance(decision.get("evidence"), list), "Verifier evidence must be a list")
            for reference in decision["evidence"]:
                self._reference(reference, by_idx, "verifier.evidence")
            if decision["verdict"] == "supported":
                _require(bool(decision["evidence"]), "A supported decision requires evidence")
                supported.append((candidate, decision))
            elif decision["verdict"] == "insufficient_evidence":
                pending[claim_id] = deepcopy(candidate)
            if self.verification_mode == "incremental_v1":
                next_cache[claim_id] = cached if reused else {
                    "candidate": deepcopy(candidate), "pack": deepcopy(pack),
                    "decision": deepcopy(decision), "verifier_metadata": deepcopy(verifier_metadata),
                    "cache_key": hashlib.sha256(_json([candidate, pack]).encode("utf-8")).hexdigest()}
            if reused:
                records.append({"type": "decision_reused", "call_id": self.call_id, "event": deepcopy(trigger),
                                "model_id": self.model_id, "candidate": deepcopy(candidate), "decision": deepcopy(decision),
                                "original_input_hash": pack.get("input_hash"), "verified_as_of_turn": pack["as_of_turn"],
                                "cache_key": cached["cache_key"]})
            else:
                record = {"type": "decision", "call_id": self.call_id, "event": deepcopy(trigger),
                          "model_id": self.model_id, "candidate": deepcopy(candidate),
                          "pack": pack, "decision": deepcopy(decision), "verifier_metadata": verifier_metadata}
                if self.verification_mode == "incremental_v1":
                    record["reverification_reason"] = reason
                records.append(record)
        facts, evidence = self._reduce(supported)
        records.append({"type": "prefix_committed", "call_id": self.call_id, "event": deepcopy(trigger),
                        "model_id": self.model_id, "candidate_count": len(candidates),
                        "fact_count": len(facts), "pending_claim_ids": sorted(pending)})
        return facts, pending, records, evidence, next_cache

    def _moment(self, value: Any, field: str = "timestamp") -> datetime:
        parsed = _timestamp(value, field)
        if parsed.tzinfo is None:
            parsed = parsed.replace(tzinfo=self._anchor.tzinfo or timezone.utc)
        return parsed.astimezone(timezone.utc)

    @staticmethod
    def _object_key(obj: dict) -> tuple:
        return (obj["type"], "id", obj["id"]) if obj.get("id") else (obj["type"], "name", obj["name"])

    def _fact_order(self, fact: dict, fact_id: str = "") -> tuple:
        source = fact["source"]
        return (self._moment(fact["valid_from"]), source["turn_idx"], source["span"][0],
                fact["attribute"], _json(fact["object"]), fact["value"], fact_id)

    def _reduce(self, supported: list[tuple[dict, dict]]) -> tuple[dict, dict]:
        grouped: dict[str, list[tuple[dict, dict]]] = defaultdict(list)
        observations = []
        for candidate, decision in supported:
            start = decision.get("valid_from") or candidate["valid_from"]
            end = decision.get("valid_to") or candidate.get("valid_to")
            start_moment = self._moment(start, "valid_from")
            end_moment = self._moment(end, "valid_to") if end is not None else None
            _require(end_moment is None or end_moment >= start_moment, "Verified valid_to is before valid_from")
            value = candidate.get("canonical_value") or candidate["raw_value"]
            fact = {"object": deepcopy(candidate["object"]), "attribute": candidate["attribute"], "value": value,
                    "polarity": candidate["polarity"], "speaker": candidate["speaker"],
                    "valid_from": start, "valid_to": end, "source": deepcopy(candidate["source"])}
            # Explicitly different intervals stay separate. A closing boundary
            # inferred below is excluded from identity, so it produces an upsert.
            identity = [self.call_id, self._object_key(fact["object"]), fact["attribute"], value, fact["polarity"],
                        start_moment.isoformat(), end_moment.isoformat() if end_moment is not None else None]
            observations.append({"fact": fact, "decision": decision, "identity": identity,
                                 "claim_id": candidate["claim_id"]})
        # Resolve state episodes *before* deduplicating mentions. Otherwise
        # A -> B -> A at day-level precision would merge both A occurrences and
        # incorrectly leave B current. Anchors come from the first source claim
        # of each consecutive-value episode, not from mutable closing dates.
        episodes: dict[tuple, list[dict]] = defaultdict(list)
        for observation in observations:
            fact = observation["fact"]
            if fact["attribute"] in SINGLE_VALUED and fact["polarity"] == 1:
                episodes[(self._object_key(fact["object"]), fact["attribute"])].append(observation)
        for episode_observations in episodes.values():
            episode_observations.sort(key=lambda item: self._fact_order(item["fact"], item["claim_id"]))
            previous_value, anchor = None, None
            for observation in episode_observations:
                fact = observation["fact"]
                if anchor is None or fact["value"] != previous_value:
                    anchor = [observation["claim_id"], fact["source"]["turn_idx"], fact["source"]["span"]]
                observation["identity"].extend(["state_episode", anchor])
                previous_value = fact["value"]
        for observation in observations:
            identity = observation["identity"]
            fact_id = f"{self.call_id}:fact:{hashlib.sha256(_json(identity).encode()).hexdigest()[:24]}"
            grouped[fact_id].append((observation["fact"], observation["decision"]))
        facts, evidence = {}, {}
        for fact_id, entries in grouped.items():
            entries.sort(key=lambda entry: self._fact_order(entry[0], fact_id))
            facts[fact_id] = entries[0][0]
            evidence[fact_id] = []
            for _, decision in entries:
                for reference in decision["evidence"]:
                    if reference not in evidence[fact_id]:
                        evidence[fact_id].append(deepcopy(reference))
        states: dict[tuple, list[str]] = defaultdict(list)
        for fact_id, fact in facts.items():
            if fact["attribute"] in SINGLE_VALUED and fact["polarity"] == 1:
                states[(self._object_key(fact["object"]), fact["attribute"])].append(fact_id)
        for fact_ids in states.values():
            fact_ids.sort(key=lambda fact_id: self._fact_order(facts[fact_id], fact_id))
            for index, fact_id in enumerate(fact_ids):
                fact = facts[fact_id]
                for following_id in fact_ids[index + 1 :]:
                    following = facts[following_id]
                    if following["value"] == fact["value"]:
                        continue
                    boundary = following["valid_from"]
                    if fact["valid_to"] is None or self._moment(boundary) < self._moment(fact["valid_to"]):
                        fact["valid_to"] = boundary
                    break
        return facts, evidence

    def _diff(self, facts: dict, evidence: dict, as_of_turn: int) -> tuple[list[dict], dict]:
        versions = self._versions.copy()
        events = []
        for fact_id in sorted(set(self._facts) - set(facts)):
            versions[fact_id] = versions.get(fact_id, 0) + 1
            events.append({"type": "retract", "call_id": self.call_id, "fact_id": fact_id,
                           "version": versions[fact_id], "as_of_turn": as_of_turn})
        for fact_id, fact in sorted(facts.items(), key=lambda pair: self._fact_order(pair[1], pair[0])):
            if self._facts.get(fact_id) == fact:
                continue
            versions[fact_id] = versions.get(fact_id, 0) + 1
            events.append({"type": "upsert", "call_id": self.call_id, "fact_id": fact_id,
                           "version": versions[fact_id], "as_of_turn": as_of_turn,
                           "fact": deepcopy(fact), "evidence": deepcopy(evidence[fact_id])})
        return events, versions