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
parsefabric/engine.py ADDED
@@ -0,0 +1,462 @@
1
+ """Run parsers on inputs and streams; aggregate, merge and materialize evidence."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from collections.abc import (
7
+ AsyncGenerator,
8
+ AsyncIterable,
9
+ AsyncIterator,
10
+ Awaitable,
11
+ Callable,
12
+ Iterable,
13
+ )
14
+ from dataclasses import replace
15
+
16
+ from parsefabric.aggregation import Aggregate, EvidenceAggregate
17
+ from parsefabric.errors import CapabilityError, ParseIssue
18
+ from parsefabric.models import ParseContext, ParsedEvent, ParseResult
19
+ from parsefabric.observability import (
20
+ LifecycleEvent,
21
+ NullObservabilitySink,
22
+ ObservabilitySink,
23
+ )
24
+ from parsefabric.parser import Parser
25
+
26
+ __all__ = [
27
+ "ParseEngine",
28
+ ]
29
+
30
+
31
+ async def _iterate[T](
32
+ items: Iterable[T] | AsyncIterable[T],
33
+ ) -> AsyncGenerator[T, None]:
34
+ """Yield the items of a synchronous or asynchronous iterable."""
35
+ if isinstance(items, AsyncIterable):
36
+ async for item in items:
37
+ yield item
38
+ else:
39
+ for item in items:
40
+ yield item
41
+
42
+
43
+ class ParseEngine:
44
+ """Run parsers over single inputs or streams and enrich their evidence.
45
+
46
+ The engine is independent of where work runs: it awaits parsers directly
47
+ and reports lifecycle events to an optional
48
+ `ObservabilitySink`.
49
+
50
+ Args:
51
+ sink: Destination for lifecycle events. Defaults to a sink that
52
+ discards them.
53
+ """
54
+
55
+ def __init__(self, sink: ObservabilitySink | None = None) -> None:
56
+ self._sink = sink or NullObservabilitySink()
57
+
58
+ async def parse(
59
+ self,
60
+ parser: Parser,
61
+ source: object,
62
+ context: ParseContext | None = None,
63
+ *,
64
+ continue_on_error: bool = False,
65
+ ) -> ParseResult:
66
+ """Parse one input and fill in missing evidence from the context.
67
+
68
+ Events whose evidence already names the source, parser, version,
69
+ partition and correlation are returned unchanged; missing fields are
70
+ filled from ``context`` and the parser identity.
71
+
72
+ Args:
73
+ parser: Parser to run.
74
+ source: Input value accepted by ``parser``.
75
+ context: Caller-supplied source, correlation, partition and offset.
76
+ continue_on_error: Return a result containing a
77
+ `ParseIssue` instead of raising
78
+ when the parser fails.
79
+
80
+ Returns:
81
+ The enriched parse result.
82
+
83
+ Raises:
84
+ Exception: Any parser exception when ``continue_on_error`` is
85
+ false. Cancellation always propagates.
86
+ """
87
+ partition_id = context.partition_id if context else None
88
+ self._sink.emit(LifecycleEvent("ParserSelected", parser_name=parser.name))
89
+ self._sink.emit(
90
+ LifecycleEvent(
91
+ "ParseStarted", parser_name=parser.name, partition_id=partition_id
92
+ )
93
+ )
94
+ try:
95
+ result = await parser.parse(source, context)
96
+ except asyncio.CancelledError:
97
+ self._sink.emit(
98
+ LifecycleEvent(
99
+ "ParseCancelled", parser_name=parser.name, partition_id=partition_id
100
+ )
101
+ )
102
+ raise
103
+ except Exception as error:
104
+ self._sink.emit(
105
+ LifecycleEvent(
106
+ "ParseFailed",
107
+ parser_name=parser.name,
108
+ partition_id=partition_id,
109
+ attributes={"error_type": type(error).__name__},
110
+ )
111
+ )
112
+ if not continue_on_error:
113
+ raise
114
+ return ParseResult(
115
+ errors=(
116
+ ParseIssue.from_exception(
117
+ error,
118
+ source_id=context.source_id if context else None,
119
+ ),
120
+ ),
121
+ parser_name=parser.name,
122
+ parser_version=parser.version,
123
+ correlation_id=context.correlation_id if context else None,
124
+ )
125
+
126
+ enriched = self._enrich(parser, result, context)
127
+ self._emit_pattern_matches(parser, enriched)
128
+ if partition_id is not None:
129
+ self._sink.emit(
130
+ LifecycleEvent(
131
+ "PartitionCompleted",
132
+ parser_name=parser.name,
133
+ partition_id=partition_id,
134
+ attributes={"event_count": len(enriched.events)},
135
+ )
136
+ )
137
+ self._sink.emit(
138
+ LifecycleEvent(
139
+ "ParseCompleted",
140
+ parser_name=parser.name,
141
+ partition_id=partition_id,
142
+ attributes={"event_count": len(enriched.events)},
143
+ )
144
+ )
145
+ return enriched
146
+
147
+ def _emit_pattern_matches(self, parser: Parser, result: ParseResult) -> None:
148
+ for statistic in result.pattern_statistics:
149
+ if statistic.matches:
150
+ self._sink.emit(
151
+ LifecycleEvent(
152
+ "PatternMatched",
153
+ parser_name=parser.name,
154
+ attributes={
155
+ "pattern_name": statistic.pattern_name,
156
+ "match_count": statistic.matches,
157
+ },
158
+ )
159
+ )
160
+
161
+ @staticmethod
162
+ def _enrich(
163
+ parser: Parser,
164
+ result: ParseResult,
165
+ context: ParseContext | None,
166
+ ) -> ParseResult:
167
+ def enrich_event(event: ParsedEvent) -> ParsedEvent:
168
+ evidence = event.evidence
169
+ source_id = evidence.source_id or (context.source_id if context else None)
170
+ parser_name = evidence.parser_name or parser.name
171
+ parser_version = evidence.parser_version or parser.version
172
+ partition_id = evidence.partition_id or (
173
+ context.partition_id if context else None
174
+ )
175
+ correlation_id = evidence.correlation_id or (
176
+ context.correlation_id if context else None
177
+ )
178
+ if (
179
+ source_id == evidence.source_id
180
+ and parser_name == evidence.parser_name
181
+ and parser_version == evidence.parser_version
182
+ and partition_id == evidence.partition_id
183
+ and correlation_id == evidence.correlation_id
184
+ ):
185
+ return event
186
+ return event.with_evidence(
187
+ replace(
188
+ evidence,
189
+ source_id=source_id,
190
+ parser_name=parser_name,
191
+ parser_version=parser_version,
192
+ partition_id=partition_id,
193
+ correlation_id=correlation_id,
194
+ )
195
+ )
196
+
197
+ return ParseResult(
198
+ events=tuple(enrich_event(event) for event in result.events),
199
+ warnings=result.warnings,
200
+ errors=result.errors,
201
+ pattern_statistics=result.pattern_statistics,
202
+ parser_name=result.parser_name or parser.name,
203
+ parser_version=result.parser_version or parser.version,
204
+ correlation_id=result.correlation_id
205
+ or (context.correlation_id if context else None),
206
+ llm_result=result.llm_result,
207
+ )
208
+
209
+ async def parse_iter(
210
+ self,
211
+ parser: Parser,
212
+ sources: Iterable[object] | AsyncIterable[object],
213
+ *,
214
+ context: ParseContext | None = None,
215
+ continue_on_error: bool = False,
216
+ ) -> AsyncIterator[ParseResult]:
217
+ """Parse inputs one at a time, yielding each result in input order.
218
+
219
+ Args:
220
+ parser: Parser to run for every input.
221
+ sources: Synchronous or asynchronous iterable of inputs.
222
+ context: Context applied to every input.
223
+ continue_on_error: See `parse`.
224
+
225
+ Yields:
226
+ One enriched result per input.
227
+ """
228
+ async for source in _iterate(sources):
229
+ yield await self.parse(
230
+ parser, source, context, continue_on_error=continue_on_error
231
+ )
232
+
233
+ async def parse_async_iter(
234
+ self,
235
+ parser: Parser,
236
+ sources: Iterable[object] | AsyncIterable[object],
237
+ *,
238
+ max_concurrency: int = 1,
239
+ context: ParseContext | None = None,
240
+ continue_on_error: bool = False,
241
+ ) -> AsyncIterator[ParseResult]:
242
+ """Parse inputs concurrently with a bound on outstanding work.
243
+
244
+ At most ``max_concurrency`` inputs are parsed at once. With more than
245
+ one, results are yielded in completion order. Closing or cancelling
246
+ the iterator cancels outstanding parses and consumes their outcomes.
247
+
248
+ Args:
249
+ parser: Parser to run; it must be parallel-safe when
250
+ ``max_concurrency`` is greater than one.
251
+ sources: Synchronous or asynchronous iterable of inputs.
252
+ max_concurrency: Maximum number of parses in flight.
253
+ context: Context applied to every input.
254
+ continue_on_error: See `parse`.
255
+
256
+ Yields:
257
+ One enriched result per input.
258
+
259
+ Raises:
260
+ ValueError: If ``max_concurrency`` is not a positive integer.
261
+ CapabilityError: If concurrency is requested for a parser that is
262
+ not parallel-safe.
263
+ """
264
+ if type(max_concurrency) is not int or max_concurrency < 1:
265
+ raise ValueError("max_concurrency must be a positive integer")
266
+ if max_concurrency > 1:
267
+ parser.capabilities.require_parallel_safe()
268
+ inputs = _iterate(sources)
269
+ pending: set[asyncio.Task[ParseResult]] = set()
270
+ exhausted = False
271
+ try:
272
+ while True:
273
+ while not exhausted and len(pending) < max_concurrency:
274
+ try:
275
+ source = await anext(inputs)
276
+ except StopAsyncIteration:
277
+ exhausted = True
278
+ else:
279
+ pending.add(
280
+ asyncio.create_task(
281
+ self.parse(
282
+ parser,
283
+ source,
284
+ context,
285
+ continue_on_error=continue_on_error,
286
+ )
287
+ )
288
+ )
289
+ if not pending:
290
+ return
291
+ completed, _ = await asyncio.wait(
292
+ pending, return_when=asyncio.FIRST_COMPLETED
293
+ )
294
+ for task in completed:
295
+ pending.remove(task)
296
+ yield task.result()
297
+ except asyncio.CancelledError:
298
+ self._sink.emit(LifecycleEvent("ParseCancelled", parser_name=parser.name))
299
+ raise
300
+ finally:
301
+ for task in pending:
302
+ task.cancel()
303
+ if pending:
304
+ await asyncio.gather(*pending, return_exceptions=True)
305
+ await inputs.aclose()
306
+
307
+ async def parse_many(
308
+ self,
309
+ parser: Parser,
310
+ sources: Iterable[object] | AsyncIterable[object],
311
+ *,
312
+ context: ParseContext | None = None,
313
+ continue_on_error: bool = False,
314
+ ) -> tuple[ParseResult, ...]:
315
+ """Parse a finite batch sequentially and return every result.
316
+
317
+ Args:
318
+ parser: Parser to run for every input.
319
+ sources: Synchronous or asynchronous iterable of inputs.
320
+ context: Context applied to every input.
321
+ continue_on_error: See `parse`.
322
+
323
+ Returns:
324
+ The enriched results in input order.
325
+ """
326
+ return tuple(
327
+ [
328
+ await self.parse(
329
+ parser, source, context, continue_on_error=continue_on_error
330
+ )
331
+ async for source in _iterate(sources)
332
+ ]
333
+ )
334
+
335
+ async def aggregate(
336
+ self,
337
+ parser: Parser,
338
+ events: Iterable[ParsedEvent] | AsyncIterable[ParsedEvent],
339
+ ) -> tuple[EvidenceAggregate, ...]:
340
+ """Aggregate events with the parser's package-managed aggregator.
341
+
342
+ Args:
343
+ parser: Parser whose events are aggregated.
344
+ events: Events of one source document, in source order.
345
+
346
+ Returns:
347
+ Lossless evidence aggregates.
348
+
349
+ Raises:
350
+ CapabilityError: If the parser is not aggregatable.
351
+ """
352
+ return await self._observe_aggregation(parser, lambda: parser.aggregate(events))
353
+
354
+ async def merge_aggregates(
355
+ self,
356
+ parser: Parser,
357
+ partials: Iterable[Aggregate] | AsyncIterable[Aggregate],
358
+ ) -> tuple[EvidenceAggregate, ...]:
359
+ """Combine aggregates of distinct source documents.
360
+
361
+ Args:
362
+ parser: Parser that produced the aggregates.
363
+ partials: Aggregates to combine.
364
+
365
+ Returns:
366
+ The combined aggregates.
367
+
368
+ Raises:
369
+ CapabilityError: If the parser is not aggregatable or the
370
+ aggregates split one source document.
371
+ """
372
+ return await self._observe_aggregation(
373
+ parser, lambda: parser.merge_aggregates(partials)
374
+ )
375
+
376
+ async def _observe_aggregation(
377
+ self,
378
+ parser: Parser,
379
+ operation: Callable[[], Awaitable[tuple[EvidenceAggregate, ...]]],
380
+ ) -> tuple[EvidenceAggregate, ...]:
381
+ if not parser.capabilities.aggregatable:
382
+ raise CapabilityError("parser capabilities do not allow aggregation")
383
+ self._sink.emit(LifecycleEvent("AggregationStarted", parser_name=parser.name))
384
+ try:
385
+ result = await operation()
386
+ except Exception as error:
387
+ self._sink.emit(
388
+ LifecycleEvent(
389
+ "AggregationFailed",
390
+ parser_name=parser.name,
391
+ attributes={"error_type": type(error).__name__},
392
+ )
393
+ )
394
+ raise
395
+ self._sink.emit(
396
+ LifecycleEvent(
397
+ "AggregationCompleted",
398
+ parser_name=parser.name,
399
+ attributes={"aggregate_count": len(result)},
400
+ )
401
+ )
402
+ return result
403
+
404
+ async def materialize(
405
+ self,
406
+ parser: Parser,
407
+ source: object,
408
+ aggregates: Iterable[Aggregate],
409
+ context: ParseContext | None = None,
410
+ ) -> tuple[ParsedEvent, ...]:
411
+ """Rebuild every original event from lossless aggregates and verify it.
412
+
413
+ When the parser's aggregator requires the source, ``source`` is parsed
414
+ again with ``context`` (by default only the aggregates' ``source_id``);
415
+ otherwise the events retained in the aggregates are used. The
416
+ aggregates are rebuilt from those candidate events and must match
417
+ exactly, including their SHA-256 checksums.
418
+
419
+ Args:
420
+ parser: Parser that produced the aggregates.
421
+ source: The original input.
422
+ aggregates: Every aggregate of the source document.
423
+ context: Context of the original parse.
424
+
425
+ Returns:
426
+ The verified original events in source order.
427
+
428
+ Raises:
429
+ IntegrityError: If the events do not reproduce the aggregates.
430
+ """
431
+ selected = tuple(aggregates)
432
+ aggregator = parser.aggregator
433
+ self._sink.emit(LifecycleEvent("MaterializeStarted", parser_name=parser.name))
434
+ try:
435
+ events = None
436
+ if aggregator.requires_source:
437
+ if context is None:
438
+ source_id = (
439
+ getattr(selected[0], "source_id", None) if selected else None
440
+ )
441
+ context = ParseContext(
442
+ source_id=source_id if isinstance(source_id, str) else None
443
+ )
444
+ events = (await self.parse(parser, source, context)).events
445
+ result = await aggregator.materialize(selected, events)
446
+ except Exception as error:
447
+ self._sink.emit(
448
+ LifecycleEvent(
449
+ "MaterializeFailed",
450
+ parser_name=parser.name,
451
+ attributes={"error_type": type(error).__name__},
452
+ )
453
+ )
454
+ raise
455
+ self._sink.emit(
456
+ LifecycleEvent(
457
+ "MaterializeCompleted",
458
+ parser_name=parser.name,
459
+ attributes={"event_count": len(result)},
460
+ )
461
+ )
462
+ return result
parsefabric/errors.py ADDED
@@ -0,0 +1,150 @@
1
+ """Typed exceptions and the serializable parse issue."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Self
7
+
8
+ from parsefabric._json import JSONValue, check_text, require_object
9
+
10
+ __all__ = [
11
+ "CapabilityError",
12
+ "ConfigurationError",
13
+ "DuplicateParserError",
14
+ "IntegrityError",
15
+ "ParseError",
16
+ "ParseFabricError",
17
+ "ParseIssue",
18
+ "RegistryError",
19
+ "SerializationError",
20
+ "SummaryValidationError",
21
+ ]
22
+
23
+
24
+ class ParseFabricError(Exception):
25
+ """Base class for every exception raised by ParseFabric."""
26
+
27
+
28
+ class ParseError(ParseFabricError):
29
+ """A parser cannot interpret its input."""
30
+
31
+
32
+ class ConfigurationError(ParseFabricError, ValueError):
33
+ """A parser or runtime configuration is invalid."""
34
+
35
+
36
+ class RegistryError(ParseFabricError):
37
+ """A parser registry operation is invalid."""
38
+
39
+
40
+ class DuplicateParserError(RegistryError):
41
+ """A parser with the same name is already registered."""
42
+
43
+
44
+ class CapabilityError(ParseFabricError):
45
+ """The requested operation conflicts with a parser's declared capabilities."""
46
+
47
+
48
+ class SerializationError(ParseFabricError, ValueError):
49
+ """A value cannot be encoded to, or decoded from, a supported JSON format."""
50
+
51
+
52
+ class IntegrityError(ParseFabricError, ValueError):
53
+ """Aggregates cannot be materialized into verified original events."""
54
+
55
+
56
+ class SummaryValidationError(ParseFabricError, ValueError):
57
+ """An LLM summary did not pass bounded evidence review."""
58
+
59
+
60
+ _ISSUE_FIELDS = frozenset(("error_type", "message", "source_id", "input_index"))
61
+
62
+
63
+ @dataclass(frozen=True, slots=True)
64
+ class ParseIssue:
65
+ """A serializable failure recorded in a tolerant parse result.
66
+
67
+ Attributes:
68
+ error_type: Name of the exception class.
69
+ message: Exception message.
70
+ source_id: Source document that failed, if known.
71
+ input_index: Zero-based position of the failed input in a batch, if
72
+ known.
73
+ """
74
+
75
+ error_type: str
76
+ message: str
77
+ source_id: str | None = None
78
+ input_index: int | None = None
79
+
80
+ def __post_init__(self) -> None:
81
+ if not isinstance(self.error_type, str) or not self.error_type:
82
+ raise ValueError("issue error_type must be a non-empty string")
83
+ check_text(self.error_type, "issue error_type")
84
+ if not isinstance(self.message, str):
85
+ raise ValueError("issue message must be a string")
86
+ check_text(self.message, "issue message")
87
+ if self.source_id is not None:
88
+ if not isinstance(self.source_id, str):
89
+ raise ValueError("issue source_id must be a string or None")
90
+ check_text(self.source_id, "issue source_id")
91
+ if self.input_index is not None and (
92
+ type(self.input_index) is not int or self.input_index < 0
93
+ ):
94
+ raise ValueError("issue input_index must be a non-negative integer")
95
+
96
+ @classmethod
97
+ def from_exception(
98
+ cls,
99
+ error: BaseException,
100
+ *,
101
+ source_id: str | None = None,
102
+ input_index: int | None = None,
103
+ ) -> Self:
104
+ """Summarize an exception by its type name and message.
105
+
106
+ Args:
107
+ error: The exception raised by a parser.
108
+ source_id: Source document that failed.
109
+ input_index: Position of the failed input in a batch.
110
+
111
+ Returns:
112
+ The issue. Characters that are not valid Unicode are escaped.
113
+ """
114
+ message = (
115
+ str(error)
116
+ .encode("utf-8", errors="backslashreplace")
117
+ .decode("utf-8", errors="strict")
118
+ )
119
+ return cls(
120
+ error_type=type(error).__name__,
121
+ message=message,
122
+ source_id=source_id,
123
+ input_index=input_index,
124
+ )
125
+
126
+ def to_dict(self) -> dict[str, JSONValue]:
127
+ """Return the JSON-compatible representation."""
128
+ return {
129
+ "error_type": self.error_type,
130
+ "message": self.message,
131
+ "source_id": self.source_id,
132
+ "input_index": self.input_index,
133
+ }
134
+
135
+ @classmethod
136
+ def from_dict(cls, data: object) -> Self:
137
+ """Rebuild an issue from `to_dict` output.
138
+
139
+ Args:
140
+ data: A decoded JSON object.
141
+
142
+ Returns:
143
+ The validated issue.
144
+
145
+ Raises:
146
+ ValueError: If ``data`` does not have exactly the issue fields or
147
+ a field is invalid.
148
+ """
149
+ fields = require_object(data, "parse issue", _ISSUE_FIELDS)
150
+ return cls(**fields)
@@ -0,0 +1,15 @@
1
+ """Backends that run work on the event loop, in threads, in processes or elsewhere."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from parsefabric.execution.async_backend import AsyncExecutionBackend
6
+ from parsefabric.execution.base import ExecutionBackend
7
+ from parsefabric.execution.process_backend import ProcessExecutionBackend
8
+ from parsefabric.execution.thread_backend import ThreadExecutionBackend
9
+
10
+ __all__ = [
11
+ "AsyncExecutionBackend",
12
+ "ExecutionBackend",
13
+ "ProcessExecutionBackend",
14
+ "ThreadExecutionBackend",
15
+ ]