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,120 @@
1
+ """Python traceback parser."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import override
7
+
8
+ from parsefabric.capabilities import ParserCapabilities
9
+ from parsefabric.errors import ParseError
10
+ from parsefabric.models import JSONValue, ParseContext, ParsedEvent, ParseResult
11
+ from parsefabric.parser import Parser
12
+
13
+ _FRAME = re.compile(
14
+ r'^\s*File "(?P<file>.+)", line (?P<line>\d+), in (?P<function>.+)$'
15
+ )
16
+ _EXCEPTION = re.compile(r"^(?P<exception_type>[\w.]+)(?:: (?P<message>.*))?$")
17
+
18
+
19
+ class PythonTracebackParser(Parser):
20
+ """Extract the exception and stack frames from one Python traceback.
21
+
22
+ The whole input is one ``python_exception`` event with
23
+ ``exception_type``, ``message`` and ``frames`` (``file``, ``line``,
24
+ ``function``) attributes. The exception is the last non-frame line that
25
+ looks like ``ExceptionType: message``; the event's evidence spans the
26
+ whole input.
27
+ """
28
+
29
+ @property
30
+ @override
31
+ def name(self) -> str:
32
+ return "python-traceback"
33
+
34
+ @property
35
+ @override
36
+ def version(self) -> str:
37
+ return "1"
38
+
39
+ @property
40
+ @override
41
+ def capabilities(self) -> ParserCapabilities:
42
+ return ParserCapabilities(
43
+ deterministic=True,
44
+ parallel_safe=True,
45
+ aggregatable=True,
46
+ )
47
+
48
+ @override
49
+ async def parse(
50
+ self,
51
+ source: object,
52
+ context: ParseContext | None = None,
53
+ ) -> ParseResult:
54
+ """Parse one traceback.
55
+
56
+ Args:
57
+ source: Traceback text or UTF-8 bytes.
58
+ context: Source description; ``source_offset`` shifts offsets.
59
+
60
+ Returns:
61
+ A result with one ``python_exception`` event.
62
+
63
+ Raises:
64
+ TypeError: If ``source`` is not text or bytes.
65
+ ParseError: If no exception line is found or the text is not
66
+ valid Unicode.
67
+ """
68
+ if isinstance(source, bytes):
69
+ text = source.decode("utf-8", errors="strict")
70
+ elif isinstance(source, str):
71
+ text = source
72
+ else:
73
+ raise TypeError("traceback parser accepts only str or bytes")
74
+ try:
75
+ size = len(text.encode("utf-8"))
76
+ except UnicodeEncodeError as error:
77
+ raise ParseError("traceback text must be valid Unicode") from error
78
+
79
+ frames: list[JSONValue] = []
80
+ exception: re.Match[str] | None = None
81
+ for line in text.splitlines():
82
+ frame = _FRAME.match(line)
83
+ if frame:
84
+ frames.append(
85
+ {
86
+ "file": frame.group("file"),
87
+ "line": int(frame.group("line")),
88
+ "function": frame.group("function"),
89
+ }
90
+ )
91
+ continue
92
+ stripped = line.strip()
93
+ if stripped and not stripped.startswith("Traceback "):
94
+ candidate = _EXCEPTION.match(stripped)
95
+ if candidate:
96
+ exception = candidate
97
+ if exception is None:
98
+ raise ParseError("no Python exception summary found in traceback")
99
+ start = context.source_offset if context and context.source_offset else 0
100
+ event = self._with_parser_evidence(
101
+ ParsedEvent(
102
+ event_type="python_exception",
103
+ severity="ERROR",
104
+ attributes={
105
+ "exception_type": exception.group("exception_type"),
106
+ "message": exception.group("message") or "",
107
+ "frames": frames,
108
+ },
109
+ ),
110
+ context,
111
+ start_offset=start,
112
+ end_offset=start + size,
113
+ line_number=1,
114
+ )
115
+ return ParseResult(
116
+ events=(event,),
117
+ parser_name=self.name,
118
+ parser_version=self.version,
119
+ correlation_id=context.correlation_id if context else None,
120
+ )
@@ -0,0 +1,135 @@
1
+ """Ordered timestamped logs with lossless, source-referenced aggregation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from datetime import datetime
7
+ from typing import ClassVar, override
8
+
9
+ from parsefabric.capabilities import ParserCapabilities
10
+ from parsefabric.errors import ParseError
11
+ from parsefabric.models import ParseContext, ParsedEvent, ParseResult
12
+ from parsefabric.parser import Parser
13
+ from parsefabric.parser._text import iter_text_lines
14
+
15
+
16
+ class TimestampedLogParser(Parser):
17
+ """Parse a document of ``TIMESTAMP LEVEL message`` lines, one event per line.
18
+
19
+ Every line must match the line pattern and carry a timezone-aware ISO
20
+ 8601 timestamp; otherwise parsing fails with
21
+ `ParseError` naming the line. Each ``log``
22
+ event records ``level`` and ``message`` attributes, the timestamp, the
23
+ level as severity, and the line's exact byte span. The parser is
24
+ deterministic, so aggregates store line positions instead of events.
25
+
26
+ Args:
27
+ line_pattern: Regular expression, as text or compiled, with ``at``,
28
+ ``level`` and ``message`` named groups that must match a whole
29
+ line. Defaults to `DEFAULT_LINE_PATTERN`.
30
+
31
+ Raises:
32
+ TypeError: If ``line_pattern`` is not a text regex.
33
+ ValueError: If the pattern lacks a required group.
34
+ """
35
+
36
+ DEFAULT_LINE_PATTERN: ClassVar[re.Pattern[str]] = re.compile(
37
+ r"^(?P<at>\S+)\s+(?P<level>TRACE|DEBUG|INFO|WARN|WARNING|ERROR|FATAL|CRITICAL)"
38
+ r"\s+(?P<message>.+)$"
39
+ )
40
+ """Default line pattern: an ISO 8601 timestamp, a level and the message."""
41
+
42
+ def __init__(
43
+ self,
44
+ *,
45
+ line_pattern: str | re.Pattern[str] | None = None,
46
+ ) -> None:
47
+ if line_pattern is not None and not isinstance(line_pattern, (str, re.Pattern)):
48
+ raise TypeError("line_pattern must be a string or compiled text regex")
49
+ if isinstance(line_pattern, re.Pattern) and not isinstance(
50
+ line_pattern.pattern, str
51
+ ):
52
+ raise TypeError("line_pattern must be a text regex")
53
+ self._line_pattern = (
54
+ self.DEFAULT_LINE_PATTERN
55
+ if line_pattern is None
56
+ else (
57
+ re.compile(line_pattern)
58
+ if isinstance(line_pattern, str)
59
+ else line_pattern
60
+ )
61
+ )
62
+ if not {"at", "level", "message"} <= self._line_pattern.groupindex.keys():
63
+ raise ValueError("line_pattern requires at, level, and message groups")
64
+
65
+ @property
66
+ @override
67
+ def name(self) -> str:
68
+ return "timestamped-log"
69
+
70
+ @property
71
+ @override
72
+ def version(self) -> str:
73
+ return "1"
74
+
75
+ @property
76
+ @override
77
+ def capabilities(self) -> ParserCapabilities:
78
+ return ParserCapabilities(
79
+ deterministic=True, parallel_safe=True, aggregatable=True
80
+ )
81
+
82
+ @override
83
+ async def parse(
84
+ self, source: object, context: ParseContext | None = None
85
+ ) -> ParseResult:
86
+ if isinstance(source, bytes):
87
+ text = source.decode("utf-8", errors="strict")
88
+ elif isinstance(source, str):
89
+ text = source
90
+ else:
91
+ raise TypeError("timestamped log parser accepts only str or bytes")
92
+ offset = context.source_offset if context and context.source_offset else 0
93
+ events: list[ParsedEvent] = []
94
+ for line_number, (line, width) in enumerate(iter_text_lines(text), 1):
95
+ match = self._line_pattern.fullmatch(line)
96
+ if match is None:
97
+ raise ParseError(f"invalid timestamped log at line {line_number}")
98
+ if not all(match.group(name) for name in ("at", "level", "message")):
99
+ raise ParseError(f"incomplete timestamped log at line {line_number}")
100
+ try:
101
+ timestamp = datetime.fromisoformat(match["at"])
102
+ except ValueError as error:
103
+ raise ParseError(
104
+ f"invalid log timestamp at line {line_number}"
105
+ ) from error
106
+ if timestamp.utcoffset() is None:
107
+ raise ParseError(
108
+ f"log timestamp must have a timezone at line {line_number}"
109
+ )
110
+ event = ParsedEvent(
111
+ event_type="log",
112
+ timestamp=timestamp,
113
+ severity=match["level"],
114
+ attributes={
115
+ "level": match["level"],
116
+ "message": match["message"],
117
+ },
118
+ )
119
+ events.append(
120
+ self._with_parser_evidence(
121
+ event,
122
+ context,
123
+ line_number=line_number,
124
+ start_offset=offset,
125
+ end_offset=offset + width,
126
+ pattern_name="timestamped-log",
127
+ )
128
+ )
129
+ offset += width
130
+ return ParseResult(
131
+ events=tuple(events),
132
+ parser_name=self.name,
133
+ parser_version=self.version,
134
+ correlation_id=context.correlation_id if context else None,
135
+ )
@@ -0,0 +1,109 @@
1
+ """Parser capabilities that orchestration code checks before scheduling work."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, fields
6
+
7
+ from parsefabric.errors import CapabilityError
8
+
9
+ __all__ = [
10
+ "ParserCapabilities",
11
+ ]
12
+
13
+
14
+ @dataclass(frozen=True, slots=True)
15
+ class ParserCapabilities:
16
+ """Behavioral guarantees a parser makes to the code that runs it.
17
+
18
+ Attributes:
19
+ deterministic: The same input and context always produce the same
20
+ result.
21
+ incremental: The parser handles inputs one at a time from a stream.
22
+ stateful: Results depend on earlier inputs.
23
+ requires_order: Inputs must be parsed in order.
24
+ parallel_safe: One instance may parse several inputs concurrently.
25
+ partitionable: A document may be split and its chunks parsed
26
+ independently; requires a deterministic, parallel-safe, stateless,
27
+ order-independent parser and a ``partition_framing``.
28
+ partition_framing: Record framing of partitions, such as ``"line"``.
29
+ aggregatable: Events may be aggregated by the package.
30
+
31
+ Raises:
32
+ ValueError: If a flag is not a bool or the combination is unsafe.
33
+ """
34
+
35
+ deterministic: bool = False
36
+ incremental: bool = False
37
+ stateful: bool = False
38
+ requires_order: bool = False
39
+ parallel_safe: bool = False
40
+ partitionable: bool = False
41
+ partition_framing: str | None = None
42
+ aggregatable: bool = False
43
+
44
+ def __post_init__(self) -> None:
45
+ for item in fields(self):
46
+ if item.name != "partition_framing" and not isinstance(
47
+ getattr(self, item.name), bool
48
+ ):
49
+ raise ValueError(f"capability {item.name} must be a bool")
50
+ if self.partition_framing is not None and (
51
+ not isinstance(self.partition_framing, str) or not self.partition_framing
52
+ ):
53
+ raise ValueError("partition_framing must be a non-empty string or None")
54
+ if self.partitionable and not (
55
+ self.deterministic
56
+ and self.parallel_safe
57
+ and not self.stateful
58
+ and not self.requires_order
59
+ ):
60
+ raise ValueError(
61
+ "partitionable parsers must be deterministic, parallel-safe, "
62
+ "stateless, and order-independent"
63
+ )
64
+ if self.partitionable != (self.partition_framing is not None):
65
+ raise ValueError(
66
+ "partitionable parsers must declare a partition framing, "
67
+ "and only partitionable parsers may declare one"
68
+ )
69
+ if self.stateful and self.parallel_safe:
70
+ raise ValueError("stateful parsers cannot declare parallel_safe")
71
+ if self.requires_order and self.parallel_safe:
72
+ raise ValueError("order-dependent parsers cannot declare parallel_safe")
73
+
74
+ def require_partitionable(self) -> None:
75
+ """Raise unless independent partitions may be parsed.
76
+
77
+ Raises:
78
+ CapabilityError: If the parser is not partitionable.
79
+ """
80
+ if not self.partitionable:
81
+ raise CapabilityError(
82
+ "parser capabilities do not allow independent partition execution"
83
+ )
84
+
85
+ def require_framing(self, framing: str) -> None:
86
+ """Raise unless partitions with the given record framing may be parsed.
87
+
88
+ Args:
89
+ framing: Required framing, such as ``"line"``.
90
+
91
+ Raises:
92
+ CapabilityError: If the parser is not partitionable or uses a
93
+ different framing.
94
+ """
95
+ self.require_partitionable()
96
+ if self.partition_framing != framing:
97
+ raise CapabilityError(
98
+ f"parser partition framing {self.partition_framing!r} "
99
+ f"does not match {framing!r}"
100
+ )
101
+
102
+ def require_parallel_safe(self) -> None:
103
+ """Raise unless one instance may parse concurrently.
104
+
105
+ Raises:
106
+ CapabilityError: If the parser is not parallel-safe.
107
+ """
108
+ if not self.parallel_safe:
109
+ raise CapabilityError("parser capabilities do not allow parallel execution")
@@ -0,0 +1,118 @@
1
+ """Compare the size of a source with the output an application produced from it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass
7
+
8
+ __all__ = [
9
+ "CompressionMetrics",
10
+ "TokenEstimator",
11
+ "estimate_tokens",
12
+ "measure_compression",
13
+ ]
14
+
15
+ type TokenEstimator = Callable[[str], int]
16
+
17
+
18
+ def estimate_tokens(text: str) -> int:
19
+ """Approximate tokens as one per four UTF-8 bytes, rounded up.
20
+
21
+ Args:
22
+ text: Text to measure.
23
+
24
+ Returns:
25
+ The estimated token count.
26
+ """
27
+ return -(-len(text.encode("utf-8", errors="surrogatepass")) // 4)
28
+
29
+
30
+ def _percent(saved: int, total: int) -> float | None:
31
+ return 100 * saved / total if total else None
32
+
33
+
34
+ @dataclass(frozen=True, slots=True)
35
+ class CompressionMetrics:
36
+ """Signed size comparison; negative savings mean the output grew.
37
+
38
+ Attributes:
39
+ input_bytes: Size of the source in bytes (UTF-8 for text).
40
+ output_bytes: Size of the output in bytes (UTF-8 for text).
41
+ bytes_saved: ``input_bytes - output_bytes``.
42
+ reduction_percent: Bytes saved as a percentage of the input, or
43
+ ``None`` for an empty input.
44
+ input_tokens: Estimated tokens in the source.
45
+ output_tokens: Estimated tokens in the output.
46
+ tokens_saved: ``input_tokens - output_tokens``.
47
+ token_reduction_percent: Tokens saved as a percentage of the input
48
+ tokens, or ``None`` when the input has no tokens.
49
+ """
50
+
51
+ input_bytes: int
52
+ output_bytes: int
53
+ bytes_saved: int
54
+ reduction_percent: float | None
55
+ input_tokens: int
56
+ output_tokens: int
57
+ tokens_saved: int
58
+ token_reduction_percent: float | None
59
+
60
+
61
+ def _measure(
62
+ value: str | bytes, name: str, estimator: TokenEstimator | None
63
+ ) -> tuple[int, int]:
64
+ if isinstance(value, bytes):
65
+ size = len(value)
66
+ if estimator is None:
67
+ return size, -(-size // 4)
68
+ return size, estimator(value.decode("utf-8", errors="replace"))
69
+ if isinstance(value, str):
70
+ return len(value.encode("utf-8", errors="surrogatepass")), (
71
+ estimator or estimate_tokens
72
+ )(value)
73
+ raise TypeError(f"{name} must be str or bytes")
74
+
75
+
76
+ def measure_compression(
77
+ source: str | bytes,
78
+ output: str | bytes,
79
+ *,
80
+ token_estimator: TokenEstimator | None = None,
81
+ ) -> CompressionMetrics:
82
+ """Compare a source with the output an application produced from it.
83
+
84
+ ParseFabric aggregates are in-memory objects; how they are encoded for
85
+ storage or transport is the application's choice, so ``output`` is the
86
+ already-encoded result, typically ``parser.serialize(aggregates)``.
87
+ Verify losslessness with
88
+ `parsefabric.engine.ParseEngine.materialize` before relying on the
89
+ reduction.
90
+
91
+ Args:
92
+ source: The original input; text is measured as UTF-8.
93
+ output: The encoded output.
94
+ token_estimator: Function returning the token count of a text.
95
+ Defaults to `estimate_tokens`. Bytes that are not valid
96
+ UTF-8 are decoded with replacement characters before a custom
97
+ estimator sees them.
98
+
99
+ Returns:
100
+ The size comparison.
101
+
102
+ Raises:
103
+ TypeError: If ``source`` or ``output`` is not text or bytes.
104
+ """
105
+ input_bytes, input_tokens = _measure(source, "source", token_estimator)
106
+ output_bytes, output_tokens = _measure(output, "output", token_estimator)
107
+ saved = input_bytes - output_bytes
108
+ tokens_saved = input_tokens - output_tokens
109
+ return CompressionMetrics(
110
+ input_bytes=input_bytes,
111
+ output_bytes=output_bytes,
112
+ bytes_saved=saved,
113
+ reduction_percent=_percent(saved, input_bytes),
114
+ input_tokens=input_tokens,
115
+ output_tokens=output_tokens,
116
+ tokens_saved=tokens_saved,
117
+ token_reduction_percent=_percent(tokens_saved, input_tokens),
118
+ )