parsefabric 0.1.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.
Files changed (51) hide show
  1. parsefabric/__init__.py +79 -0
  2. parsefabric/_json.py +247 -0
  3. parsefabric/_summary_review.py +315 -0
  4. parsefabric/aggregation/__init__.py +30 -0
  5. parsefabric/aggregation/base.py +265 -0
  6. parsefabric/aggregation/codec.py +77 -0
  7. parsefabric/aggregation/evidence.py +667 -0
  8. parsefabric/aggregation/routing.py +161 -0
  9. parsefabric/aggregation/statistical.py +153 -0
  10. parsefabric/builtins/__init__.py +22 -0
  11. parsefabric/builtins/application_log.py +121 -0
  12. parsefabric/builtins/cli_output.py +159 -0
  13. parsefabric/builtins/code_detection.py +228 -0
  14. parsefabric/builtins/json_parser.py +140 -0
  15. parsefabric/builtins/mixed_content.py +655 -0
  16. parsefabric/builtins/python_traceback.py +120 -0
  17. parsefabric/builtins/timestamped_log.py +135 -0
  18. parsefabric/capabilities.py +109 -0
  19. parsefabric/compression.py +118 -0
  20. parsefabric/engine.py +462 -0
  21. parsefabric/errors.py +150 -0
  22. parsefabric/execution/__init__.py +15 -0
  23. parsefabric/execution/_executor.py +102 -0
  24. parsefabric/execution/async_backend.py +69 -0
  25. parsefabric/execution/base.py +143 -0
  26. parsefabric/execution/process_backend.py +41 -0
  27. parsefabric/execution/thread_backend.py +36 -0
  28. parsefabric/models.py +506 -0
  29. parsefabric/observability.py +252 -0
  30. parsefabric/parser/__init__.py +10 -0
  31. parsefabric/parser/_text.py +34 -0
  32. parsefabric/parser/async_parser.py +53 -0
  33. parsefabric/parser/base.py +205 -0
  34. parsefabric/parser/deterministic.py +219 -0
  35. parsefabric/parser/semantic.py +15 -0
  36. parsefabric/partitioning.py +172 -0
  37. parsefabric/patterns/__init__.py +19 -0
  38. parsefabric/patterns/base.py +98 -0
  39. parsefabric/patterns/exact.py +61 -0
  40. parsefabric/patterns/match.py +22 -0
  41. parsefabric/patterns/predicate.py +62 -0
  42. parsefabric/patterns/regex.py +78 -0
  43. parsefabric/patterns/structured.py +59 -0
  44. parsefabric/py.typed +0 -0
  45. parsefabric/registry.py +174 -0
  46. parsefabric/serialization.py +67 -0
  47. parsefabric/summarization.py +563 -0
  48. parsefabric-0.1.0.dist-info/METADATA +208 -0
  49. parsefabric-0.1.0.dist-info/RECORD +51 -0
  50. parsefabric-0.1.0.dist-info/WHEEL +4 -0
  51. parsefabric-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,667 @@
1
+ """Lossless, grouped evidence aggregation.
2
+
3
+ Events of one source are grouped into one `EvidenceAggregate` per
4
+ ``(event_type, parser_name)``, then into `EvidenceGroup` objects per
5
+ ``(pattern, severity)``. Each `EvidenceEntry` stores a distinct message
6
+ once with its occurrence count and the 1-based source line ``positions`` of
7
+ its events. Reproducible parsers rebuild every event by re-parsing the source;
8
+ other parsers retain the events in the entries. Every aggregate carries a
9
+ SHA-256 over its complete canonical events, and
10
+ `EvidenceAggregator.materialize` rebuilds and verifies them exactly.
11
+
12
+ Every aggregate has one canonical JSON form (`Aggregate.to_dict`),
13
+ identical for every parser because the only parser-specific value, the entry
14
+ ``message``, is itself JSON; `Parser.serialize` owns the envelope.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import re
21
+ from collections.abc import AsyncIterable, Callable, Iterable, Sequence
22
+ from dataclasses import dataclass, field
23
+ from datetime import datetime
24
+ from typing import Any, ClassVar, override
25
+
26
+ from parsefabric._json import (
27
+ canonical_dumps,
28
+ check_text,
29
+ copy_json,
30
+ dumps,
31
+ require_object,
32
+ )
33
+ from parsefabric.aggregation.base import Aggregate, Aggregator
34
+ from parsefabric.errors import CapabilityError, IntegrityError
35
+ from parsefabric.models import Evidence, JSONValue, ParsedEvent
36
+
37
+ type Position = int | None
38
+ type MessageFunction = Callable[[ParsedEvent], JSONValue]
39
+
40
+ _SHA256 = re.compile(r"[0-9a-f]{64}")
41
+
42
+
43
+ _GROUP_FIELDS = frozenset(("pattern", "severity", "evidence"))
44
+ _ENTRY_FIELDS = frozenset(("message", "occurrences", "positions"))
45
+ _RETAINED_FIELDS = frozenset(("events", "sequence"))
46
+
47
+
48
+ def canonical_event(event: ParsedEvent) -> str:
49
+ """Return the canonical JSON text that event checksums are computed over.
50
+
51
+ The text is compact UTF-8 JSON with sorted keys, so equal events always
52
+ produce identical text.
53
+
54
+ Args:
55
+ event: Event to encode.
56
+
57
+ Returns:
58
+ The canonical text.
59
+ """
60
+ return canonical_dumps(event._to_wire())
61
+
62
+
63
+ def default_event_message(event: ParsedEvent) -> JSONValue:
64
+ """Return the information an evidence entry carries for its events.
65
+
66
+ The message is the event's string ``message`` attribute (a parser's
67
+ compact statement of what happened, such as a log message); otherwise all
68
+ of the event's attributes (for example a JSON value, a metric name and
69
+ value, or unmatched text), so the aggregate itself says what occurred and
70
+ positions only record where and in which order. ``None`` only for events
71
+ without attributes.
72
+
73
+ Args:
74
+ event: Event to describe.
75
+
76
+ Returns:
77
+ The entry message.
78
+ """
79
+ message = event.attributes.get("message")
80
+ if isinstance(message, str):
81
+ return message
82
+ return dict(event.attributes) or None
83
+
84
+
85
+ def _message_key(value: JSONValue) -> object:
86
+ # Text messages compare as themselves; other values by their sorted JSON,
87
+ # wrapped in a tuple so that they never equal a text message.
88
+ if type(value) is str:
89
+ return value
90
+ try:
91
+ return ("json", dumps(value, sort_keys=True))
92
+ except (TypeError, ValueError) as error:
93
+ raise TypeError("event messages must be JSON-compatible values") from error
94
+
95
+
96
+ def _is_position(value: object) -> bool:
97
+ return value is None or (type(value) is int and value >= 1)
98
+
99
+
100
+ @dataclass(frozen=True, slots=True)
101
+ class EvidenceEntry:
102
+ """One distinct message, or one consecutive run of it, and where it occurs.
103
+
104
+ ``positions`` holds the 1-based source line of each occurrence in source
105
+ order (the first line of a multi-line event), or ``None`` when the parser
106
+ cannot locate it. Exact offsets are not stored: they are part of the
107
+ checksummed events that ``materialize`` rebuilds and verifies. ``events``
108
+ and their stream ``sequence`` positions are retained only for parsers
109
+ whose events cannot be rebuilt by re-parsing the source.
110
+
111
+ Attributes:
112
+ message: JSON-compatible description shared by the occurrences.
113
+ occurrences: Number of events represented.
114
+ positions: Source line of each occurrence.
115
+ events: Retained events, for non-reproducible parsers.
116
+ sequence: Zero-based stream position of each retained event.
117
+ """
118
+
119
+ message: JSONValue
120
+ occurrences: int
121
+ positions: tuple[Position, ...]
122
+ events: tuple[ParsedEvent, ...] = ()
123
+ sequence: tuple[int, ...] = ()
124
+
125
+ def __post_init__(self) -> None:
126
+ object.__setattr__(self, "message", copy_json(self.message, "evidence message"))
127
+ if type(self.occurrences) is not int or self.occurrences < 1:
128
+ raise ValueError("occurrences must be a positive integer")
129
+ if not isinstance(self.positions, tuple) or any(
130
+ not _is_position(value) for value in self.positions
131
+ ):
132
+ raise ValueError("positions must be positive line numbers or None")
133
+ if len(self.positions) != self.occurrences:
134
+ raise ValueError("each occurrence needs exactly one position")
135
+ known = [value for value in self.positions if value is not None]
136
+ if known != sorted(known):
137
+ raise ValueError("positions must be in source order")
138
+ if not isinstance(self.events, tuple) or any(
139
+ not isinstance(event, ParsedEvent) for event in self.events
140
+ ):
141
+ raise ValueError("retained events must be ParsedEvent instances")
142
+ if self.events and len(self.events) != self.occurrences:
143
+ raise ValueError("retained events must match occurrences")
144
+ if (
145
+ not isinstance(self.sequence, tuple)
146
+ or len(self.sequence) != len(self.events)
147
+ or any(type(value) is not int or value < 0 for value in self.sequence)
148
+ ):
149
+ raise ValueError("each retained event needs a stream position")
150
+
151
+
152
+ @dataclass(frozen=True, slots=True)
153
+ class EvidenceGroup:
154
+ """Entries sharing one pattern and severity, such as one log level.
155
+
156
+ Attributes:
157
+ pattern: Pattern or route that produced the events, if any.
158
+ severity: Severity of the events, if any.
159
+ evidence: Entries in source order of their first occurrence.
160
+ """
161
+
162
+ pattern: str | None
163
+ severity: str | None
164
+ evidence: tuple[EvidenceEntry, ...]
165
+
166
+ def __post_init__(self) -> None:
167
+ for value in (self.pattern, self.severity):
168
+ if value is not None:
169
+ if not isinstance(value, str):
170
+ raise ValueError("pattern and severity must be strings or None")
171
+ check_text(value, "pattern and severity")
172
+ if (
173
+ not isinstance(self.evidence, tuple)
174
+ or not self.evidence
175
+ or any(not isinstance(entry, EvidenceEntry) for entry in self.evidence)
176
+ ):
177
+ raise ValueError("an evidence group needs EvidenceEntry items")
178
+
179
+ @property
180
+ def occurrences(self) -> int:
181
+ """Total events represented by this group."""
182
+ return sum(entry.occurrences for entry in self.evidence)
183
+
184
+
185
+ @dataclass(frozen=True, slots=True)
186
+ class EvidenceAggregate(Aggregate):
187
+ """Lossless summary of one event type from one parser in one source.
188
+
189
+ Attributes:
190
+ source_id: Source document of the events.
191
+ parser_name: Parser that produced the events.
192
+ parser_version: Version of that parser.
193
+ groups: Entries grouped by pattern and severity.
194
+ events_sha256: SHA-256 over the canonical text of every event, in
195
+ stream order, each followed by a newline.
196
+ """
197
+
198
+ FIELDS: ClassVar[tuple[str, ...]] = (
199
+ "parser_name",
200
+ "parser_version",
201
+ "source_id",
202
+ "groups",
203
+ "events_sha256",
204
+ )
205
+
206
+ source_id: str | None
207
+ parser_name: str | None
208
+ parser_version: str | None
209
+ groups: tuple[EvidenceGroup, ...]
210
+ events_sha256: str
211
+
212
+ @override
213
+ def __post_init__(self) -> None:
214
+ Aggregate.__post_init__(self)
215
+ for value in (self.source_id, self.parser_name, self.parser_version):
216
+ if value is not None:
217
+ if not isinstance(value, str):
218
+ raise ValueError(
219
+ "source, parser name, and version must be str or None"
220
+ )
221
+ check_text(value, "source, parser name, and version")
222
+ if (
223
+ not isinstance(self.groups, tuple)
224
+ or not self.groups
225
+ or any(not isinstance(group, EvidenceGroup) for group in self.groups)
226
+ ):
227
+ raise ValueError("an evidence aggregate needs EvidenceGroup items")
228
+ entries = [entry for group in self.groups for entry in group.evidence]
229
+ if sum(entry.occurrences for entry in entries) != self.count:
230
+ raise ValueError("occurrences do not add up to the aggregate count")
231
+ if len({bool(entry.events) for entry in entries}) > 1:
232
+ raise ValueError("either every entry or none retains its events")
233
+ if not isinstance(self.events_sha256, str) or not _SHA256.fullmatch(
234
+ self.events_sha256
235
+ ):
236
+ raise ValueError("events_sha256 must be a lowercase SHA-256 hex digest")
237
+
238
+ @property
239
+ def retains_events(self) -> bool:
240
+ """Whether the entries carry the events themselves."""
241
+ return bool(self.groups[0].evidence[0].events)
242
+
243
+ @override
244
+ def _fields_to_wire(self) -> dict[str, JSONValue]:
245
+ return {
246
+ "parser_name": self.parser_name,
247
+ "parser_version": self.parser_version,
248
+ "source_id": self.source_id,
249
+ "groups": [
250
+ {
251
+ "pattern": group.pattern,
252
+ "severity": group.severity,
253
+ "evidence": [_entry_to_wire(entry) for entry in group.evidence],
254
+ }
255
+ for group in self.groups
256
+ ],
257
+ "events_sha256": self.events_sha256,
258
+ }
259
+
260
+ @classmethod
261
+ @override
262
+ def _fields_from_dict(cls, fields: dict[str, Any]) -> dict[str, Any]:
263
+ groups = fields["groups"]
264
+ if not isinstance(groups, list):
265
+ raise ValueError("groups must be a list")
266
+ return {
267
+ "source_id": fields["source_id"],
268
+ "parser_name": fields["parser_name"],
269
+ "parser_version": fields["parser_version"],
270
+ "groups": tuple(_group_from_dict(group) for group in groups),
271
+ "events_sha256": fields["events_sha256"],
272
+ }
273
+
274
+
275
+ def _entry_to_wire(entry: EvidenceEntry) -> dict[str, JSONValue]:
276
+ data: dict[str, JSONValue] = {
277
+ "message": entry.message,
278
+ "occurrences": entry.occurrences,
279
+ "positions": list(entry.positions),
280
+ }
281
+ if entry.events:
282
+ data["events"] = [event._to_wire() for event in entry.events]
283
+ data["sequence"] = list(entry.sequence)
284
+ return data
285
+
286
+
287
+ def _list(fields: dict[str, Any], key: str) -> list[Any]:
288
+ value = fields[key]
289
+ if not isinstance(value, list):
290
+ raise ValueError(f"{key} must be a list")
291
+ return value
292
+
293
+
294
+ def _group_from_dict(data: object) -> EvidenceGroup:
295
+ fields = require_object(data, "evidence group", _GROUP_FIELDS)
296
+ return EvidenceGroup(
297
+ pattern=fields["pattern"],
298
+ severity=fields["severity"],
299
+ evidence=tuple(_entry_from_dict(entry) for entry in _list(fields, "evidence")),
300
+ )
301
+
302
+
303
+ def _entry_from_dict(data: object) -> EvidenceEntry:
304
+ fields = require_object(data, "evidence entry", _ENTRY_FIELDS, _RETAINED_FIELDS)
305
+ if ("events" in fields) != ("sequence" in fields):
306
+ raise ValueError("retained events and their sequence must appear together")
307
+ events: tuple[ParsedEvent, ...] = ()
308
+ sequence: tuple[int, ...] = ()
309
+ if "events" in fields:
310
+ retained = _list(fields, "events")
311
+ if not retained:
312
+ raise ValueError("retained events must not be empty")
313
+ events = tuple(ParsedEvent.from_dict(event) for event in retained)
314
+ sequence = tuple(_list(fields, "sequence"))
315
+ return EvidenceEntry(
316
+ message=fields["message"],
317
+ occurrences=fields["occurrences"],
318
+ positions=tuple(_list(fields, "positions")),
319
+ events=events,
320
+ sequence=sequence,
321
+ )
322
+
323
+
324
+ @dataclass
325
+ class _Entry:
326
+ message: JSONValue
327
+ positions: list[Position] = field(default_factory=list)
328
+ occurrences: int = 0
329
+ events: list[ParsedEvent] = field(default_factory=list)
330
+ sequence: list[int] = field(default_factory=list)
331
+
332
+
333
+ @dataclass
334
+ class _Document:
335
+ event_type: str
336
+ parser_name: str | None
337
+ parser_version: str | None
338
+ groups: dict[tuple[str | None, str | None], list[_Entry]] = field(
339
+ default_factory=dict
340
+ )
341
+ digest: Any = field(default_factory=hashlib.sha256)
342
+ count: int = 0
343
+ first_seen: datetime | None = None
344
+ last_seen: datetime | None = None
345
+
346
+
347
+ def _adjacent(previous: Evidence, current: Evidence) -> bool:
348
+ """Whether ``current`` directly follows ``previous`` in the source.
349
+
350
+ Events whose byte spans abut are adjacent. Otherwise events on the same
351
+ or the next line are adjacent, so any skipped line, blank or not, starts
352
+ a new run regardless of the line ending. Events without comparable
353
+ locations follow each other in stream order.
354
+ """
355
+ has_offsets = previous.end_offset is not None and current.start_offset is not None
356
+ if has_offsets and current.start_offset == previous.end_offset:
357
+ return True
358
+ if previous.line_number is not None and current.line_number is not None:
359
+ return 0 <= current.line_number - previous.line_number <= 1
360
+ return not has_offsets
361
+
362
+
363
+ def _identity(aggregate: EvidenceAggregate) -> tuple[str, str | None]:
364
+ return aggregate.event_type, aggregate.parser_name
365
+
366
+
367
+ class EvidenceAggregator(Aggregator):
368
+ """Group events by type, parser, pattern, severity and message losslessly.
369
+
370
+ Each source yields one aggregate per ``(event_type, parser_name)``. Only
371
+ identical events that directly follow each other in the source form one
372
+ entry listing the line position of each event in the run, so a
373
+ recurrence after any other event or skipped source line starts a new
374
+ entry and the source order is kept.
375
+
376
+ Args:
377
+ reproducible: Whether the owning parser rebuilds identical events from
378
+ the same source and context. Reproducible aggregates store only
379
+ positions; otherwise every event is retained.
380
+ message: Function deriving an entry's message from an event. Defaults
381
+ to `default_event_message`.
382
+ """
383
+
384
+ def __init__(
385
+ self,
386
+ *,
387
+ reproducible: bool = False,
388
+ message: MessageFunction | None = None,
389
+ ) -> None:
390
+ if not isinstance(reproducible, bool):
391
+ raise TypeError("reproducible must be bool")
392
+ if message is not None and not callable(message):
393
+ raise TypeError("message must be callable")
394
+ self._reproducible = reproducible
395
+ self._message = message or default_event_message
396
+
397
+ @property
398
+ def reproducible(self) -> bool:
399
+ """Whether the owning parser rebuilds identical events on re-parse."""
400
+ return self._reproducible
401
+
402
+ @property
403
+ @override
404
+ def lossless(self) -> bool:
405
+ return True
406
+
407
+ @property
408
+ @override
409
+ def requires_source(self) -> bool:
410
+ return self.reproducible
411
+
412
+ @override
413
+ async def aggregate(
414
+ self, events: Iterable[ParsedEvent] | AsyncIterable[ParsedEvent]
415
+ ) -> tuple[EvidenceAggregate, ...]:
416
+ """Aggregate the events of one source document.
417
+
418
+ Args:
419
+ events: Events of a single source, in source order.
420
+
421
+ Returns:
422
+ One aggregate per event type and parser, in order of first
423
+ appearance.
424
+
425
+ Raises:
426
+ TypeError: If an item is not a `ParsedEvent` or a message
427
+ is not JSON-compatible.
428
+ ValueError: If the events mix sources, go backwards in the source,
429
+ or mix versions of one parser.
430
+ """
431
+ documents: dict[tuple[str, str | None], _Document] = {}
432
+ versions: dict[str, str | None] = {}
433
+ source_id: str | None = None
434
+ last_line: int | None = None
435
+ # Run key and evidence of the previous event.
436
+ previous: (
437
+ tuple[
438
+ tuple[tuple[str, str | None], tuple[str | None, str | None], object],
439
+ Evidence,
440
+ ]
441
+ | None
442
+ ) = None
443
+ count = 0
444
+
445
+ def add(event: ParsedEvent) -> None:
446
+ nonlocal source_id, last_line, previous, count
447
+ if not isinstance(event, ParsedEvent):
448
+ raise TypeError("events must be ParsedEvent instances")
449
+ evidence = event.evidence
450
+ if count and evidence.source_id != source_id:
451
+ raise ValueError("aggregate each source document separately")
452
+ line = evidence.line_number
453
+ if last_line is not None and line is not None and line < last_line:
454
+ raise ValueError("events must be in source order")
455
+ if evidence.parser_name is not None:
456
+ known = versions.setdefault(
457
+ evidence.parser_name, evidence.parser_version
458
+ )
459
+ if known != evidence.parser_version:
460
+ raise ValueError(
461
+ f"parser {evidence.parser_name!r} appears with "
462
+ "different versions in one document"
463
+ )
464
+ source_id = evidence.source_id
465
+ last_line = line if line is not None else last_line
466
+ doc_key = (event.event_type, evidence.parser_name)
467
+ document = documents.get(doc_key)
468
+ if document is None:
469
+ document = documents[doc_key] = _Document(
470
+ event.event_type, evidence.parser_name, evidence.parser_version
471
+ )
472
+ if document.parser_version != evidence.parser_version:
473
+ raise ValueError("events of one parser must share a version")
474
+ group_key = (evidence.pattern_name, event.severity)
475
+ message = self._message(event)
476
+ message_key = _message_key(message)
477
+ entries = document.groups.setdefault(group_key, [])
478
+ current = (doc_key, group_key, message_key)
479
+ if (
480
+ previous is not None
481
+ and previous[0] == current
482
+ and _adjacent(previous[1], evidence)
483
+ ):
484
+ entry = entries[-1]
485
+ else:
486
+ entry = _Entry(message)
487
+ entries.append(entry)
488
+ entry.positions.append(line)
489
+ entry.occurrences += 1
490
+ if not self.reproducible:
491
+ entry.events.append(event)
492
+ entry.sequence.append(count)
493
+ document.digest.update(canonical_event(event).encode("utf-8") + b"\n")
494
+ document.count += 1
495
+ if event.timestamp is not None:
496
+ document.first_seen = (
497
+ event.timestamp
498
+ if document.first_seen is None
499
+ else min(document.first_seen, event.timestamp)
500
+ )
501
+ document.last_seen = (
502
+ event.timestamp
503
+ if document.last_seen is None
504
+ else max(document.last_seen, event.timestamp)
505
+ )
506
+ previous = (current, evidence)
507
+ count += 1
508
+
509
+ if isinstance(events, AsyncIterable):
510
+ async for event in events:
511
+ add(event)
512
+ else:
513
+ for event in events:
514
+ add(event)
515
+ return tuple(
516
+ self._document_aggregate(document, source_id)
517
+ for document in documents.values()
518
+ )
519
+
520
+ def _document_aggregate(
521
+ self, document: _Document, source_id: str | None
522
+ ) -> EvidenceAggregate:
523
+ return EvidenceAggregate(
524
+ event_type=document.event_type,
525
+ count=document.count,
526
+ first_seen=document.first_seen,
527
+ last_seen=document.last_seen,
528
+ source_id=source_id,
529
+ parser_name=document.parser_name,
530
+ parser_version=document.parser_version,
531
+ groups=tuple(
532
+ EvidenceGroup(
533
+ pattern,
534
+ severity,
535
+ tuple(
536
+ EvidenceEntry(
537
+ entry.message,
538
+ entry.occurrences,
539
+ tuple(entry.positions),
540
+ tuple(entry.events),
541
+ tuple(entry.sequence),
542
+ )
543
+ for entry in entries
544
+ ),
545
+ )
546
+ for (pattern, severity), entries in document.groups.items()
547
+ ),
548
+ events_sha256=document.digest.hexdigest(),
549
+ )
550
+
551
+ @staticmethod
552
+ def _validate(aggregates: Sequence[Aggregate]) -> tuple[EvidenceAggregate, ...]:
553
+ selected: list[EvidenceAggregate] = []
554
+ keys: set[tuple[str, str | None]] = set()
555
+ sources: set[str | None] = set()
556
+ for aggregate in aggregates:
557
+ if not isinstance(aggregate, EvidenceAggregate):
558
+ raise TypeError("aggregates must be EvidenceAggregate instances")
559
+ key = _identity(aggregate)
560
+ if key in keys:
561
+ raise IntegrityError(
562
+ "duplicate aggregate for one event type and parser"
563
+ )
564
+ keys.add(key)
565
+ sources.add(aggregate.source_id)
566
+ selected.append(aggregate)
567
+ if len(sources) > 1:
568
+ raise IntegrityError("aggregates must come from exactly one source")
569
+ return tuple(selected)
570
+
571
+ @staticmethod
572
+ def _retained_events(
573
+ aggregates: Sequence[EvidenceAggregate],
574
+ ) -> list[ParsedEvent]:
575
+ retained: list[tuple[int, ParsedEvent]] = []
576
+ for aggregate in aggregates:
577
+ if not aggregate.retains_events:
578
+ raise IntegrityError(
579
+ "aggregate does not retain its events; materialize it by "
580
+ "re-parsing the source with a reproducible parser"
581
+ )
582
+ for group in aggregate.groups:
583
+ for entry in group.evidence:
584
+ retained.extend(zip(entry.sequence, entry.events, strict=True))
585
+ retained.sort(key=lambda pair: pair[0])
586
+ if [position for position, _ in retained] != list(range(len(retained))):
587
+ raise IntegrityError("retained event positions are inconsistent")
588
+ return [event for _, event in retained]
589
+
590
+ @override
591
+ async def materialize(
592
+ self,
593
+ aggregates: Sequence[Aggregate],
594
+ events: Sequence[ParsedEvent] | None = None,
595
+ ) -> tuple[ParsedEvent, ...]:
596
+ """Rebuild every original event and verify it against ``aggregates``.
597
+
598
+ Reproducible parsers pass the events of a fresh parse of the same
599
+ source and context as ``events``; otherwise the retained events are
600
+ used. Either way the aggregates are rebuilt from the candidate events
601
+ and must match exactly, including the checksums. The order of
602
+ ``aggregates`` does not matter, and an empty sequence represents a
603
+ source without events.
604
+
605
+ Args:
606
+ aggregates: Every aggregate of one source document.
607
+ events: Events of a fresh parse, for reproducible parsers.
608
+
609
+ Returns:
610
+ The verified original events in stream order.
611
+
612
+ Raises:
613
+ TypeError: If an aggregate is not an `EvidenceAggregate`.
614
+ IntegrityError: If the aggregates are inconsistent or do not match
615
+ the candidate events.
616
+ """
617
+ selected = self._validate(aggregates)
618
+ candidates = (
619
+ list(events) if events is not None else self._retained_events(selected)
620
+ )
621
+ try:
622
+ rebuilt = await self.aggregate(candidates)
623
+ except (TypeError, ValueError) as error:
624
+ raise IntegrityError(f"events cannot be aggregated: {error}") from error
625
+ if {_identity(item): item for item in rebuilt} != {
626
+ _identity(item): item for item in selected
627
+ }:
628
+ raise IntegrityError(
629
+ "events do not match the aggregate evidence or checksum; "
630
+ "use the exact source, parser version, and parse context"
631
+ )
632
+ return tuple(candidates)
633
+
634
+ @override
635
+ async def merge(
636
+ self, partials: Iterable[Aggregate] | AsyncIterable[Aggregate]
637
+ ) -> tuple[Aggregate, ...]:
638
+ """Combine aggregates of distinct source documents.
639
+
640
+ Args:
641
+ partials: Aggregates to combine.
642
+
643
+ Returns:
644
+ The aggregates, unchanged and in input order.
645
+
646
+ Raises:
647
+ TypeError: If an item is not an `EvidenceAggregate`.
648
+ CapabilityError: If two aggregates describe the same source,
649
+ event type and parser, because a checksummed document cannot
650
+ be split into partitions and merged.
651
+ """
652
+ if isinstance(partials, AsyncIterable):
653
+ items: list[Aggregate] = [item async for item in partials]
654
+ else:
655
+ items = list(partials)
656
+ seen: set[tuple[str | None, str, str | None]] = set()
657
+ for item in items:
658
+ if not isinstance(item, EvidenceAggregate):
659
+ raise TypeError("partials must be EvidenceAggregate instances")
660
+ key = (item.source_id, item.event_type, item.parser_name)
661
+ if key in seen:
662
+ raise CapabilityError(
663
+ "source documents are checksummed as a whole; aggregate each "
664
+ "complete source once instead of merging partitions"
665
+ )
666
+ seen.add(key)
667
+ return tuple(items)