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,102 @@
1
+ """Shared implementation of the thread and process pool backends."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextvars
7
+ import inspect
8
+ from collections.abc import Awaitable, Callable, Coroutine
9
+ from concurrent.futures import Executor, ThreadPoolExecutor
10
+ from functools import partial
11
+ from typing import Any, overload, override
12
+
13
+ from parsefabric.execution.base import ExecutionBackend
14
+ from parsefabric.observability import LifecycleEvent, ObservabilitySink
15
+
16
+
17
+ async def _await(awaitable: Awaitable[Any]) -> Any:
18
+ return await awaitable
19
+
20
+
21
+ def _call_in_worker(
22
+ function: Callable[..., Any], args: tuple[object, ...], kwargs: dict[str, object]
23
+ ) -> Any:
24
+ """Call ``function`` in a worker and drive an awaitable result to completion."""
25
+ result = function(*args, **kwargs)
26
+ if inspect.isawaitable(result):
27
+ return asyncio.run(_await(result))
28
+ return result
29
+
30
+
31
+ def validated_workers(max_workers: object) -> int | None:
32
+ """Return ``max_workers`` if it is ``None`` or a positive integer."""
33
+ if max_workers is not None and (type(max_workers) is not int or max_workers < 1):
34
+ raise ValueError("max_workers must be a positive integer or None")
35
+ return max_workers
36
+
37
+
38
+ class _ExecutorBackend(ExecutionBackend):
39
+ def __init__(
40
+ self,
41
+ executor: Executor,
42
+ sink: ObservabilitySink | None = None,
43
+ ) -> None:
44
+ super().__init__(sink)
45
+ self._executor = executor
46
+ self._closed = False
47
+
48
+ @overload
49
+ async def run[R](
50
+ self,
51
+ function: Callable[..., Coroutine[Any, Any, R] | Awaitable[R]],
52
+ /,
53
+ *args: object,
54
+ **kwargs: object,
55
+ ) -> R: ...
56
+
57
+ @overload
58
+ async def run[R](
59
+ self,
60
+ function: Callable[..., R],
61
+ /,
62
+ *args: object,
63
+ **kwargs: object,
64
+ ) -> R: ...
65
+
66
+ @override
67
+ async def run(
68
+ self, function: Callable[..., Any], /, *args: object, **kwargs: object
69
+ ) -> Any:
70
+ if self._closed:
71
+ raise RuntimeError("execution backend is shut down")
72
+ self._sink.emit(LifecycleEvent("ExecutionSubmitted"))
73
+ call = partial(_call_in_worker, function, args, kwargs)
74
+ loop = asyncio.get_running_loop()
75
+ self._sink.emit(LifecycleEvent("ExecutionStarted"))
76
+ try:
77
+ if isinstance(self._executor, ThreadPoolExecutor):
78
+ context = contextvars.copy_context()
79
+ result = await loop.run_in_executor(self._executor, context.run, call)
80
+ else:
81
+ result = await loop.run_in_executor(self._executor, call)
82
+ except asyncio.CancelledError:
83
+ self._sink.emit(LifecycleEvent("ExecutionCancelled"))
84
+ raise
85
+ except Exception as error:
86
+ self._sink.emit(
87
+ LifecycleEvent(
88
+ "ExecutionFailed",
89
+ attributes={"error_type": type(error).__name__},
90
+ )
91
+ )
92
+ raise
93
+ self._sink.emit(LifecycleEvent("ExecutionCompleted"))
94
+ return result
95
+
96
+ @override
97
+ async def shutdown(self) -> None:
98
+ if not self._closed:
99
+ self._closed = True
100
+ await asyncio.to_thread(
101
+ self._executor.shutdown, wait=True, cancel_futures=True
102
+ )
@@ -0,0 +1,69 @@
1
+ """Asyncio execution backend."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import inspect
7
+ from collections.abc import Awaitable, Callable, Coroutine
8
+ from typing import Any, overload, override
9
+
10
+ from parsefabric.execution.base import ExecutionBackend
11
+ from parsefabric.observability import LifecycleEvent
12
+
13
+
14
+ class AsyncExecutionBackend(ExecutionBackend):
15
+ """Run callables directly on the current event loop.
16
+
17
+ Synchronous callables run inline and block the loop while they run, so
18
+ use this backend for asynchronous parsers or light work. Awaitable
19
+ results are awaited.
20
+
21
+ Args:
22
+ sink: Destination for ``Execution*`` lifecycle events.
23
+ """
24
+
25
+ @overload
26
+ async def run[R](
27
+ self,
28
+ function: Callable[..., Coroutine[Any, Any, R] | Awaitable[R]],
29
+ /,
30
+ *args: object,
31
+ **kwargs: object,
32
+ ) -> R: ...
33
+
34
+ @overload
35
+ async def run[R](
36
+ self,
37
+ function: Callable[..., R],
38
+ /,
39
+ *args: object,
40
+ **kwargs: object,
41
+ ) -> R: ...
42
+
43
+ @override
44
+ async def run(
45
+ self, function: Callable[..., Any], /, *args: object, **kwargs: object
46
+ ) -> Any:
47
+ self._sink.emit(LifecycleEvent("ExecutionSubmitted"))
48
+ self._sink.emit(LifecycleEvent("ExecutionStarted"))
49
+ try:
50
+ result = function(*args, **kwargs)
51
+ if inspect.isawaitable(result):
52
+ result = await result
53
+ except asyncio.CancelledError:
54
+ self._sink.emit(LifecycleEvent("ExecutionCancelled"))
55
+ raise
56
+ except Exception as error:
57
+ self._sink.emit(
58
+ LifecycleEvent(
59
+ "ExecutionFailed",
60
+ attributes={"error_type": type(error).__name__},
61
+ )
62
+ )
63
+ raise
64
+ self._sink.emit(LifecycleEvent("ExecutionCompleted"))
65
+ return result
66
+
67
+ @override
68
+ async def shutdown(self) -> None:
69
+ """Do nothing: the backend owns no resources."""
@@ -0,0 +1,143 @@
1
+ """Backend-neutral execution contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from abc import ABC, abstractmethod
7
+ from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine, Iterable
8
+ from typing import Any, Self, overload
9
+
10
+ from parsefabric.observability import NullObservabilitySink, ObservabilitySink
11
+
12
+
13
+ class ExecutionBackend(ABC):
14
+ """Where submitted work runs: the event loop, threads, processes or a cluster.
15
+
16
+ Parsers do not depend on the backend; applications choose one to bound
17
+ concurrency or isolate CPU-heavy work. Backends are asynchronous context
18
+ managers that release their resources on exit.
19
+
20
+ Args:
21
+ sink: Destination for ``Execution*`` lifecycle events. Defaults to a
22
+ sink that discards them.
23
+ """
24
+
25
+ def __init__(self, sink: ObservabilitySink | None = None) -> None:
26
+ self._sink = sink or NullObservabilitySink()
27
+
28
+ @overload
29
+ async def run[R](
30
+ self,
31
+ function: Callable[..., Coroutine[Any, Any, R] | Awaitable[R]],
32
+ /,
33
+ *args: object,
34
+ **kwargs: object,
35
+ ) -> R: ...
36
+
37
+ @overload
38
+ async def run[R](
39
+ self,
40
+ function: Callable[..., R],
41
+ /,
42
+ *args: object,
43
+ **kwargs: object,
44
+ ) -> R: ...
45
+
46
+ @abstractmethod
47
+ async def run(
48
+ self, function: Callable[..., Any], /, *args: object, **kwargs: object
49
+ ) -> Any:
50
+ """Run one callable and return its result, awaiting awaitable results.
51
+
52
+ Args:
53
+ function: Synchronous or asynchronous callable.
54
+ *args: Positional arguments for ``function``.
55
+ **kwargs: Keyword arguments for ``function``.
56
+
57
+ Returns:
58
+ The callable's result.
59
+
60
+ Raises:
61
+ Exception: Whatever the callable raises.
62
+ """
63
+
64
+ @abstractmethod
65
+ async def shutdown(self) -> None:
66
+ """Release resources owned by this backend; idempotent."""
67
+
68
+ @overload
69
+ def map[Input, Output](
70
+ self,
71
+ function: Callable[[Input], Coroutine[Any, Any, Output] | Awaitable[Output]],
72
+ items: Iterable[Input],
73
+ *,
74
+ max_in_flight: int = 1,
75
+ ) -> AsyncIterator[Output]: ...
76
+
77
+ @overload
78
+ def map[Input, Output](
79
+ self,
80
+ function: Callable[[Input], Output],
81
+ items: Iterable[Input],
82
+ *,
83
+ max_in_flight: int = 1,
84
+ ) -> AsyncIterator[Output]: ...
85
+
86
+ async def map[Input](
87
+ self,
88
+ function: Callable[[Input], Any],
89
+ items: Iterable[Input],
90
+ *,
91
+ max_in_flight: int = 1,
92
+ ) -> AsyncIterator[Any]:
93
+ """Apply a callable to every item with a bound on outstanding work.
94
+
95
+ At most ``max_in_flight`` calls are scheduled but not yet consumed.
96
+ Results are yielded in completion order. The first failure is raised
97
+ and outstanding calls are cancelled; work already running in a thread
98
+ or process cannot be interrupted.
99
+
100
+ Args:
101
+ function: Callable applied to each item.
102
+ items: Inputs, consumed lazily.
103
+ max_in_flight: Maximum number of scheduled, unconsumed calls.
104
+
105
+ Yields:
106
+ One result per item.
107
+
108
+ Raises:
109
+ ValueError: If ``max_in_flight`` is not a positive integer.
110
+ """
111
+ if type(max_in_flight) is not int or max_in_flight < 1:
112
+ raise ValueError("max_in_flight must be a positive integer")
113
+ iterator = iter(items)
114
+ pending: set[asyncio.Task[Any]] = set()
115
+ exhausted = False
116
+ try:
117
+ while pending or not exhausted:
118
+ while not exhausted and len(pending) < max_in_flight:
119
+ try:
120
+ item = next(iterator)
121
+ except StopIteration:
122
+ exhausted = True
123
+ break
124
+ pending.add(asyncio.create_task(self.run(function, item)))
125
+ if pending:
126
+ completed, _ = await asyncio.wait(
127
+ pending,
128
+ return_when=asyncio.FIRST_COMPLETED,
129
+ )
130
+ for task in completed:
131
+ pending.remove(task)
132
+ yield task.result()
133
+ finally:
134
+ for task in pending:
135
+ task.cancel()
136
+ if pending:
137
+ await asyncio.gather(*pending, return_exceptions=True)
138
+
139
+ async def __aenter__(self) -> Self:
140
+ return self
141
+
142
+ async def __aexit__(self, exc_type: object, exc: object, traceback: object) -> None:
143
+ await self.shutdown()
@@ -0,0 +1,41 @@
1
+ """Process pool execution backend."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from concurrent.futures import ProcessPoolExecutor
6
+ from multiprocessing import get_context
7
+
8
+ from parsefabric.execution._executor import _ExecutorBackend, validated_workers
9
+ from parsefabric.observability import ObservabilitySink
10
+
11
+
12
+ class ProcessExecutionBackend(_ExecutorBackend):
13
+ """Run CPU-heavy work in an owned, spawn-based process pool.
14
+
15
+ The callable, its arguments and its result must be picklable. Workers are
16
+ started with the ``spawn`` method on every platform, so they never
17
+ inherit the parent's threads or locks. An awaitable result is run to
18
+ completion in the worker. A process pool is not a security sandbox.
19
+
20
+ Args:
21
+ max_workers: Number of processes; defaults to the standard library's
22
+ choice.
23
+ sink: Destination for ``Execution*`` lifecycle events.
24
+
25
+ Raises:
26
+ ValueError: If ``max_workers`` is not a positive integer or ``None``.
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ *,
32
+ max_workers: int | None = None,
33
+ sink: ObservabilitySink | None = None,
34
+ ) -> None:
35
+ super().__init__(
36
+ ProcessPoolExecutor(
37
+ max_workers=validated_workers(max_workers),
38
+ mp_context=get_context("spawn"),
39
+ ),
40
+ sink,
41
+ )
@@ -0,0 +1,36 @@
1
+ """Thread pool execution backend."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from concurrent.futures import ThreadPoolExecutor
6
+
7
+ from parsefabric.execution._executor import _ExecutorBackend, validated_workers
8
+ from parsefabric.observability import ObservabilitySink
9
+
10
+
11
+ class ThreadExecutionBackend(_ExecutorBackend):
12
+ """Run blocking work in an owned thread pool.
13
+
14
+ Context variables of the caller are visible in the worker thread. An
15
+ awaitable result is run to completion on a new event loop in the worker.
16
+ Cancelling a call stops waiting for it but cannot interrupt a running
17
+ thread.
18
+
19
+ Args:
20
+ max_workers: Number of threads; defaults to the standard library's
21
+ choice.
22
+ sink: Destination for ``Execution*`` lifecycle events.
23
+
24
+ Raises:
25
+ ValueError: If ``max_workers`` is not a positive integer or ``None``.
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ *,
31
+ max_workers: int | None = None,
32
+ sink: ObservabilitySink | None = None,
33
+ ) -> None:
34
+ super().__init__(
35
+ ThreadPoolExecutor(max_workers=validated_workers(max_workers)), sink
36
+ )