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,655 @@
1
+ """Mixed-content routing across built-in and custom parsers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Iterable, Mapping, Sequence
7
+ from dataclasses import replace
8
+ from typing import override
9
+
10
+ from parsefabric.aggregation import Aggregator, RoutingAggregator
11
+ from parsefabric.builtins.code_detection import DEFAULT_CODE_LANGUAGES, CodeDetector
12
+ from parsefabric.builtins.json_parser import JSONParser
13
+ from parsefabric.capabilities import ParserCapabilities
14
+ from parsefabric.errors import ParseError, ParseIssue
15
+ from parsefabric.models import (
16
+ JSONValue,
17
+ ParseContext,
18
+ ParsedEvent,
19
+ ParseResult,
20
+ PatternStatistic,
21
+ )
22
+ from parsefabric.parser import Parser
23
+ from parsefabric.parser._text import iter_text_lines
24
+ from parsefabric.patterns import ExactPattern, Pattern, RegexPattern
25
+
26
+
27
+ def _scan_json_brackets(
28
+ line: str, stack: list[str], in_string: bool, escaped: bool
29
+ ) -> tuple[bool, bool, bool]:
30
+ """Track JSON container boundaries without treating quoted braces as syntax."""
31
+ for character in line:
32
+ if in_string:
33
+ if escaped:
34
+ escaped = False
35
+ elif character == "\\":
36
+ escaped = True
37
+ elif character == '"':
38
+ in_string = False
39
+ elif character == '"':
40
+ in_string = True
41
+ elif character in "{[":
42
+ stack.append("}" if character == "{" else "]")
43
+ elif character in "}]" and (not stack or stack.pop() != character):
44
+ return True, in_string, escaped
45
+ return not stack, in_string, escaped
46
+
47
+
48
+ _FENCE = re.compile(r"^\s*(`{3,}|~{3,})")
49
+ # Lines that continue the block above them even when they are not indented.
50
+ _CONTINUATION = re.compile(r"^\s*(?:else\b|elif\b|except\b|finally\b|catch\b|[}\])])")
51
+ _MAX_BLOCK_EXTENSION = 50
52
+
53
+ _Line = tuple[int, str, int, int]
54
+
55
+
56
+ def _indent(line: str) -> int:
57
+ return len(line) - len(line.lstrip())
58
+
59
+
60
+ def _blocks(lines: Sequence[_Line]) -> list[list[int]]:
61
+ """Split unmatched lines into indentation blocks (indexes into ``lines``)."""
62
+ blocks: list[list[int]] = []
63
+ base = 0
64
+ for index, (_, line, _, _) in enumerate(lines):
65
+ if blocks and (
66
+ not line.strip()
67
+ or _indent(line) > base
68
+ or _CONTINUATION.match(line)
69
+ or lines[blocks[-1][-1]][1].lstrip().startswith("@")
70
+ ):
71
+ blocks[-1].append(index)
72
+ continue
73
+ blocks.append([index])
74
+ base = _indent(line)
75
+ return blocks
76
+
77
+
78
+ def _covered_lines(events: Iterable[ParsedEvent], lines: Sequence[_Line]) -> set[int]:
79
+ """Line numbers that routed events start on or whose byte spans include.
80
+
81
+ Adopted events always carry a line number and a byte span (see ``_adopt``).
82
+ """
83
+ covered: set[int] = set()
84
+ for event in events:
85
+ evidence = event.evidence
86
+ first, last = evidence.start_offset or 0, evidence.end_offset or 0
87
+ covered.add(evidence.line_number or 0)
88
+ covered.update(number for number, _, start, _ in lines if first <= start < last)
89
+ return covered
90
+
91
+
92
+ def _code_languages(detector: CodeDetector, lines: Sequence[_Line]) -> list[str | None]:
93
+ """Return the detected language of each line, ``None`` for non-code lines.
94
+
95
+ Code spans lines (``def f():`` alone is not valid), so whole indentation
96
+ blocks are parsed and extended with following blocks while the result stays
97
+ valid (multi-line SQL, decorators); blocks that are not code are retried
98
+ line by line.
99
+ """
100
+ languages: list[str | None] = [None] * len(lines)
101
+ blocks = _blocks(lines)
102
+
103
+ def detect(first: int, last: int) -> str | None:
104
+ indexes = [index for block in blocks[first : last + 1] for index in block]
105
+ return detector.detect("\n".join(lines[index][1] for index in indexes))
106
+
107
+ position = 0
108
+ while position < len(blocks):
109
+ last = position
110
+ language = detect(position, position)
111
+ if language is None and position + 1 < len(blocks):
112
+ language = detect(position, position + 1)
113
+ last = position + 1
114
+ if language is None:
115
+ if len(blocks[position]) > 1:
116
+ for index in blocks[position]:
117
+ languages[index] = detector.detect(lines[index][1])
118
+ position += 1
119
+ continue
120
+ while last + 1 < len(blocks) and last - position < _MAX_BLOCK_EXTENSION:
121
+ extended = detect(position, last + 1)
122
+ if extended is None:
123
+ break
124
+ language, last = extended, last + 1
125
+ indexes = [index for block in blocks[position : last + 1] for index in block]
126
+ while indexes and not lines[indexes[-1]][1].strip():
127
+ indexes.pop()
128
+ for index in indexes:
129
+ languages[index] = language
130
+ position = last + 1
131
+ return languages
132
+
133
+
134
+ class MixedContentParser(Parser):
135
+ """Parse documents that mix logs, JSON, code and free text, line by line.
136
+
137
+ Each line is classified in this order:
138
+
139
+ 1. A Markdown code fence (```` ``` ```` or ``~~~``) starts a fenced block.
140
+ Its body is parsed by the parser in ``fence_routes`` for the fence's
141
+ language tag; otherwise, or when that parser rejects the body, every
142
+ body line becomes a ``code`` event. Fence marker lines become
143
+ ``fence`` events.
144
+ 2. The first route whose selector matches sends the line to an existing
145
+ parser, whose events are kept with their own parser identity and
146
+ re-based to the line. A JSON route continues over following lines
147
+ until the JSON value is complete.
148
+ 3. The first matching pattern, in priority order, produces an event.
149
+ 4. Remaining lines are grouped into indentation blocks and become
150
+ ``code`` events (with ``language``) when a tree-sitter grammar parses
151
+ them as code, or ``other`` events with the line as ``text``.
152
+
153
+ No line is lost: every line produces at least one event.
154
+
155
+ Args:
156
+ patterns: Line patterns. Defaults to one ``log-level`` pattern that
157
+ recognizes ``LEVEL message`` lines, optionally after an ISO date,
158
+ and records ``level``, ``message``, ``text`` and severity.
159
+ routes: ``(selector, parser)`` pairs; routed parsers with the same
160
+ name must be the same instance.
161
+ fence_routes: Parser for each lowercase fence language tag.
162
+ code_languages: Grammars used to detect unfenced code;
163
+ ``()`` disables detection.
164
+
165
+ Raises:
166
+ TypeError: If a route is not a ``(Pattern, Parser)`` pair or routes to
167
+ this parser.
168
+ ValueError: If names repeat, a reserved name (``code``,
169
+ ``code_fence``, ``other``) is used, or a fence tag is invalid.
170
+ """
171
+
172
+ def __init__(
173
+ self,
174
+ patterns: Sequence[Pattern] | None = None,
175
+ *,
176
+ routes: Sequence[tuple[Pattern, Parser]] = (),
177
+ fence_routes: Mapping[str, Parser] | None = None,
178
+ code_languages: Sequence[str] = DEFAULT_CODE_LANGUAGES,
179
+ ) -> None:
180
+ self._code_detector = (
181
+ CodeDetector(code_languages)
182
+ if isinstance(code_languages, str) or code_languages
183
+ else None
184
+ )
185
+ selected = (
186
+ patterns
187
+ if patterns is not None
188
+ else (
189
+ RegexPattern(
190
+ "log-level",
191
+ r"^\s*(?:\d{4}-\d\d-\d\d[ T]\S+\s+)?"
192
+ r"(?P<level>TRACE|DEBUG|INFO|WARN(?:ING)?|ERROR|FATAL|CRITICAL)\b"
193
+ r"[:\s]*(?P<message>(?:\S|\s+\S)*)",
194
+ flags=re.IGNORECASE,
195
+ priority=20,
196
+ event_type="log",
197
+ ),
198
+ )
199
+ )
200
+ self._routes = tuple(routes)
201
+ self._fence_routes: dict[str, Parser] = {}
202
+ for language, parser in (fence_routes or {}).items():
203
+ if (
204
+ not isinstance(language, str)
205
+ or not language
206
+ or language != language.strip().lower()
207
+ or any(character.isspace() for character in language)
208
+ ):
209
+ raise ValueError(
210
+ "fence_routes keys must be lowercase language tags such as 'sql'"
211
+ )
212
+ if not isinstance(parser, Parser):
213
+ raise TypeError("fence_routes values must be Parser instances")
214
+ self._fence_routes[language] = parser
215
+ self._route_parsers: dict[str, Parser] = {}
216
+ route_parsers = self._route_parsers
217
+ for selector, parser in self._routes:
218
+ if not isinstance(selector, Pattern) or not isinstance(parser, Parser):
219
+ raise TypeError("routes must contain (Pattern, Parser) pairs")
220
+ if parser is self:
221
+ raise TypeError(
222
+ "mixed content routes cannot route to the parser itself"
223
+ )
224
+ if (
225
+ parser.name in route_parsers
226
+ and route_parsers[parser.name] is not parser
227
+ ):
228
+ raise ValueError("routed parsers with the same name must be identical")
229
+ route_parsers[parser.name] = parser
230
+ for parser in self._fence_routes.values():
231
+ if parser is self:
232
+ raise TypeError(
233
+ "mixed content routes cannot route to the parser itself"
234
+ )
235
+ if (
236
+ parser.name in route_parsers
237
+ and route_parsers[parser.name] is not parser
238
+ ):
239
+ raise ValueError("routed parsers with the same name must be identical")
240
+ route_parsers[parser.name] = parser
241
+ names = [pattern.name for pattern in selected] + [
242
+ selector.name for selector, _ in self._routes
243
+ ]
244
+ if len(names) != len(set(names)) or {"code", "code_fence", "other"} & set(
245
+ names
246
+ ):
247
+ raise ValueError(
248
+ "mixed content pattern names must be unique and reserved names unused"
249
+ )
250
+ self._patterns = tuple(
251
+ sorted(selected, key=lambda pattern: (-pattern.priority, pattern.name))
252
+ )
253
+ self._default_patterns = patterns is None
254
+
255
+ @override
256
+ def _build_aggregator(self) -> Aggregator:
257
+ """Fallback events use grouped evidence; routed events use their parser's."""
258
+ return RoutingAggregator(
259
+ super()._build_aggregator(),
260
+ {name: parser.aggregator for name, parser in self._route_parsers.items()},
261
+ )
262
+
263
+ @property
264
+ @override
265
+ def name(self) -> str:
266
+ return "mixed-content"
267
+
268
+ @property
269
+ @override
270
+ def version(self) -> str:
271
+ return "1"
272
+
273
+ @property
274
+ @override
275
+ def capabilities(self) -> ParserCapabilities:
276
+ """Capabilities derived from the patterns, selectors and routed parsers.
277
+
278
+ The parser is deterministic and parallel-safe only when every pattern
279
+ and route selector is a `RegexPattern` or
280
+ `ExactPattern` and every routed parser is deterministic and
281
+ parallel-safe, respectively. Mixed content is never partitionable:
282
+ code blocks, fences and multi-line JSON span lines.
283
+ """
284
+ routed = (
285
+ *(parser for _, parser in self._routes),
286
+ *self._fence_routes.values(),
287
+ )
288
+ pure = all(
289
+ isinstance(pattern, (RegexPattern, ExactPattern))
290
+ for pattern in (
291
+ *self._patterns,
292
+ *(selector for selector, _ in self._routes),
293
+ )
294
+ )
295
+ stateful = any(parser.capabilities.stateful for parser in routed)
296
+ requires_order = any(parser.capabilities.requires_order for parser in routed)
297
+ return ParserCapabilities(
298
+ deterministic=pure
299
+ and all(parser.capabilities.deterministic for parser in routed),
300
+ parallel_safe=pure
301
+ and not stateful
302
+ and not requires_order
303
+ and all(parser.capabilities.parallel_safe for parser in routed),
304
+ stateful=stateful,
305
+ requires_order=requires_order,
306
+ aggregatable=True,
307
+ )
308
+
309
+ @staticmethod
310
+ def _child_context(context: ParseContext | None, offset: int) -> ParseContext:
311
+ return ParseContext(
312
+ source_id=context.source_id if context else None,
313
+ correlation_id=context.correlation_id if context else None,
314
+ partition_id=context.partition_id if context else None,
315
+ source_offset=offset,
316
+ )
317
+
318
+ def _adopt(
319
+ self,
320
+ child: ParseResult,
321
+ route: str,
322
+ line_number: int,
323
+ start: int,
324
+ end: int,
325
+ context: ParseContext | None,
326
+ events: list[ParsedEvent],
327
+ counts: dict[str, int],
328
+ ) -> bool:
329
+ """Re-base a routed parser's events onto the mixed input's lines."""
330
+ for statistic in child.pattern_statistics:
331
+ name = f"{route}:{statistic.pattern_name}"
332
+ counts[name] = counts.get(name, 0) + statistic.matches
333
+ if not child.events:
334
+ return False
335
+ counts[route] = counts.get(route, 0) + 1
336
+ for child_event in child.events:
337
+ evidence = child_event.evidence
338
+ events.append(
339
+ self._with_parser_evidence(
340
+ child_event.with_evidence(
341
+ replace(
342
+ evidence,
343
+ line_number=(
344
+ line_number + evidence.line_number - 1
345
+ if evidence.line_number is not None
346
+ else line_number
347
+ ),
348
+ )
349
+ ),
350
+ context,
351
+ start_offset=(
352
+ evidence.start_offset
353
+ if evidence.start_offset is not None
354
+ else start
355
+ ),
356
+ end_offset=(
357
+ evidence.end_offset if evidence.end_offset is not None else end
358
+ ),
359
+ pattern_name=evidence.pattern_name or route,
360
+ )
361
+ )
362
+ return True
363
+
364
+ async def _route_fenced_body(
365
+ self,
366
+ language: str,
367
+ data: bytes,
368
+ source_start: int,
369
+ body: list[tuple[int, str, int, int]],
370
+ context: ParseContext | None,
371
+ counts: dict[str, int],
372
+ warnings: list[str],
373
+ ) -> list[ParsedEvent] | None:
374
+ """Parse a fenced body with its language's parser; ``None`` keeps code.
375
+
376
+ Only the fence's declared language selects a parser, never the body's
377
+ content. Fenced snippets are often illustrative, so a body the parser
378
+ rejects (a ``ParseError`` or parse issues) stays ``code`` instead of
379
+ failing the document.
380
+ """
381
+ parser = self._fence_routes.get(language)
382
+ if parser is None or not any(line.strip() for _, line, _, _ in body):
383
+ return None
384
+ start, end = body[0][2], body[-1][3]
385
+ routed_text = data[start - source_start : end - source_start]
386
+ try:
387
+ child = await parser.parse(
388
+ routed_text.decode("utf-8"), self._child_context(context, start)
389
+ )
390
+ except ParseError:
391
+ return None
392
+ if child.errors or not child.events:
393
+ return None
394
+ adopted: list[ParsedEvent] = []
395
+ self._adopt(
396
+ child,
397
+ f"code_fence:{language}",
398
+ body[0][0],
399
+ start,
400
+ end,
401
+ context,
402
+ adopted,
403
+ counts,
404
+ )
405
+ warnings.extend(child.warnings)
406
+ return adopted
407
+
408
+ @override
409
+ async def parse(
410
+ self,
411
+ source: object,
412
+ context: ParseContext | None = None,
413
+ ) -> ParseResult:
414
+ if isinstance(source, bytes):
415
+ text = source.decode("utf-8", errors="strict")
416
+ elif isinstance(source, str):
417
+ text = source
418
+ else:
419
+ raise TypeError("mixed content parser accepts only str or bytes")
420
+
421
+ events: list[ParsedEvent] = []
422
+ warnings: list[str] = []
423
+ errors: list[ParseIssue] = []
424
+ counts = {pattern.name: 0 for pattern in self._patterns}
425
+ counts.update({selector.name: 0 for selector, _ in self._routes})
426
+ counts["code_fence"] = 0
427
+ counts["code"] = 0
428
+ pending: list[_Line] = []
429
+ byte_offset = context.source_offset if context and context.source_offset else 0
430
+ source_start = byte_offset
431
+ source_bytes: bytes | None = None
432
+ lines = iter(enumerate(iter_text_lines(text), start=1))
433
+ line_item = next(lines, None)
434
+
435
+ def fallback(
436
+ line: str, kind: str = "other", language: str | None = None
437
+ ) -> ParsedEvent:
438
+ attributes: dict[str, JSONValue] = (
439
+ {} if language is None else {"language": language}
440
+ )
441
+ attributes["text"] = line
442
+ return ParsedEvent(kind, attributes=attributes)
443
+
444
+ def append(
445
+ event: ParsedEvent, line_number: int, start: int, end: int, pattern: str
446
+ ) -> None:
447
+ if pattern != "other":
448
+ counts[pattern] += 1
449
+ events.append(
450
+ self._with_parser_evidence(
451
+ event,
452
+ context,
453
+ start_offset=start,
454
+ end_offset=end,
455
+ line_number=line_number,
456
+ pattern_name=pattern,
457
+ )
458
+ )
459
+
460
+ def flush() -> None:
461
+ """Emit buffered unmatched lines as detected code or other text."""
462
+ if not pending:
463
+ return
464
+ languages = (
465
+ _code_languages(self._code_detector, pending)
466
+ if self._code_detector is not None
467
+ else [None] * len(pending)
468
+ )
469
+ for (number, line, start, end), language in zip(
470
+ pending, languages, strict=True
471
+ ):
472
+ if language is None:
473
+ append(fallback(line), number, start, end, "other")
474
+ else:
475
+ append(fallback(line, "code", language), number, start, end, "code")
476
+ pending.clear()
477
+
478
+ while line_item is not None:
479
+ line_number, (line, width) = line_item
480
+ line_item = next(lines, None)
481
+ start = byte_offset
482
+ byte_offset += width
483
+ marker = _FENCE.match(line)
484
+ if marker:
485
+ fence = marker.group(1)
486
+ info = line[marker.end() :].split()
487
+ language = info[0].lower() if info else ""
488
+ flush()
489
+ opening: _Line = (line_number, line, start, byte_offset)
490
+ body: list[tuple[int, str, int, int]] = []
491
+ closing: tuple[int, str, int, int] | None = None
492
+ while line_item is not None:
493
+ body_number, (body_line, body_width) = line_item
494
+ line_item = next(lines, None)
495
+ body_start = byte_offset
496
+ byte_offset += body_width
497
+ end_marker = _FENCE.match(body_line)
498
+ if (
499
+ end_marker
500
+ and end_marker.group(1)[0] == fence[0]
501
+ and len(end_marker.group(1)) >= len(fence)
502
+ and not body_line[end_marker.end() :].strip()
503
+ ):
504
+ closing = (body_number, body_line, body_start, byte_offset)
505
+ break
506
+ body.append((body_number, body_line, body_start, byte_offset))
507
+ fence_language = language or (
508
+ self._code_detector.detect("\n".join(item[1] for item in body))
509
+ if self._code_detector is not None and body
510
+ else None
511
+ )
512
+ append(
513
+ fallback(line, "fence", fence_language),
514
+ opening[0],
515
+ opening[2],
516
+ opening[3],
517
+ "code_fence",
518
+ )
519
+ if language in self._fence_routes and source_bytes is None:
520
+ source_bytes = text.encode("utf-8")
521
+ adopted = (
522
+ await self._route_fenced_body(
523
+ language,
524
+ source_bytes or b"",
525
+ source_start,
526
+ body,
527
+ context,
528
+ counts,
529
+ warnings,
530
+ )
531
+ if body
532
+ else None
533
+ )
534
+ covered = _covered_lines(adopted or (), body)
535
+ by_line: dict[int, list[ParsedEvent]] = {}
536
+ for routed_event in adopted or ():
537
+ by_line.setdefault(
538
+ routed_event.evidence.line_number or 0, []
539
+ ).append(routed_event)
540
+ for body_number, body_line, body_start, body_end in body:
541
+ events.extend(by_line.pop(body_number, ()))
542
+ if body_number not in covered:
543
+ append(
544
+ fallback(body_line, "code", fence_language),
545
+ body_number,
546
+ body_start,
547
+ body_end,
548
+ "code_fence",
549
+ )
550
+ if closing is not None:
551
+ closing_number, closing_line, closing_start, closing_end = closing
552
+ append(
553
+ fallback(closing_line, "fence", fence_language),
554
+ closing_number,
555
+ closing_start,
556
+ closing_end,
557
+ "code_fence",
558
+ )
559
+ continue
560
+ routed = False
561
+ for selector, parser in self._routes:
562
+ if selector.match(line) is None:
563
+ continue
564
+ routed_text = line
565
+ if isinstance(parser, JSONParser) and line.lstrip().startswith(
566
+ ("{", "[")
567
+ ):
568
+ stack: list[str] = []
569
+ complete, in_string, escaped = _scan_json_brackets(
570
+ line, stack, False, False
571
+ )
572
+ if not complete:
573
+ if source_bytes is None:
574
+ source_bytes = text.encode("utf-8")
575
+ while line_item is not None:
576
+ _, (next_line, next_width) = line_item
577
+ if (
578
+ _FENCE.match(next_line)
579
+ or any(
580
+ not isinstance(child_parser, JSONParser)
581
+ and next_selector.match(next_line) is not None
582
+ for next_selector, child_parser in self._routes
583
+ )
584
+ or any(
585
+ pattern.match(next_line) is not None
586
+ for pattern in self._patterns
587
+ )
588
+ ):
589
+ break
590
+ byte_offset += next_width
591
+ complete, in_string, escaped = _scan_json_brackets(
592
+ next_line, stack, in_string, escaped
593
+ )
594
+ line_item = next(lines, None)
595
+ if complete:
596
+ break
597
+ routed_text = source_bytes[
598
+ start - source_start : byte_offset - source_start
599
+ ].decode("utf-8")
600
+ flush()
601
+ child = await parser.parse(
602
+ routed_text, self._child_context(context, start)
603
+ )
604
+ warnings.extend(child.warnings)
605
+ errors.extend(child.errors)
606
+ if self._adopt(
607
+ child,
608
+ selector.name,
609
+ line_number,
610
+ start,
611
+ byte_offset,
612
+ context,
613
+ events,
614
+ counts,
615
+ ):
616
+ routed = True
617
+ break
618
+ if routed:
619
+ continue
620
+ matched = next(
621
+ (
622
+ (pattern, match)
623
+ for pattern in self._patterns
624
+ if (match := pattern.match(line)) is not None
625
+ ),
626
+ None,
627
+ )
628
+ if matched is None:
629
+ pending.append((line_number, line, start, byte_offset))
630
+ continue
631
+ flush()
632
+ pattern, match = matched
633
+ event = pattern.to_event(match)
634
+ if self._default_patterns:
635
+ attributes = dict(event.attributes)
636
+ level = attributes.get("level")
637
+ attributes["text"] = line
638
+ event = replace(
639
+ event,
640
+ attributes=attributes,
641
+ severity=level.upper() if isinstance(level, str) else None,
642
+ )
643
+ append(event, line_number, start, byte_offset, pattern.name)
644
+ flush()
645
+ return ParseResult(
646
+ events=tuple(events),
647
+ warnings=tuple(warnings),
648
+ errors=tuple(errors),
649
+ pattern_statistics=tuple(
650
+ PatternStatistic(name, count) for name, count in sorted(counts.items())
651
+ ),
652
+ parser_name=self.name,
653
+ parser_version=self.version,
654
+ correlation_id=context.correlation_id if context else None,
655
+ )