structa-maestro 0.2.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 (55) hide show
  1. structa_maestro/__init__.py +294 -0
  2. structa_maestro/batch.py +564 -0
  3. structa_maestro/binding.py +206 -0
  4. structa_maestro/builder/__init__.py +0 -0
  5. structa_maestro/builder/result_builder.py +308 -0
  6. structa_maestro/cli.py +730 -0
  7. structa_maestro/confidence/__init__.py +49 -0
  8. structa_maestro/confidence/calibration.py +990 -0
  9. structa_maestro/confidence/normalizer.py +203 -0
  10. structa_maestro/config.py +111 -0
  11. structa_maestro/contracts/__init__.py +0 -0
  12. structa_maestro/contracts/enums.py +86 -0
  13. structa_maestro/contracts/models.py +229 -0
  14. structa_maestro/contracts/serialization.py +169 -0
  15. structa_maestro/documents/__init__.py +32 -0
  16. structa_maestro/documents/docx_parser.py +215 -0
  17. structa_maestro/documents/eml_parser.py +360 -0
  18. structa_maestro/documents/html_parser.py +337 -0
  19. structa_maestro/documents/inputs.py +277 -0
  20. structa_maestro/documents/loader.py +675 -0
  21. structa_maestro/documents/markdown_parser.py +225 -0
  22. structa_maestro/documents/models.py +33 -0
  23. structa_maestro/documents/normalization.py +24 -0
  24. structa_maestro/documents/pdf_parser.py +186 -0
  25. structa_maestro/documents/txt_parser.py +169 -0
  26. structa_maestro/engine.py +1201 -0
  27. structa_maestro/exceptions.py +38 -0
  28. structa_maestro/provenance/__init__.py +0 -0
  29. structa_maestro/provenance/associator.py +234 -0
  30. structa_maestro/py.typed +0 -0
  31. structa_maestro/review.py +1234 -0
  32. structa_maestro/schema/__init__.py +19 -0
  33. structa_maestro/schema/loader.py +616 -0
  34. structa_maestro/schema/models.py +269 -0
  35. structa_maestro/schema/pydantic_adapter.py +566 -0
  36. structa_maestro/schema/rules.py +526 -0
  37. structa_maestro/schema/serializer.py +156 -0
  38. structa_maestro/strategies/__init__.py +45 -0
  39. structa_maestro/strategies/base.py +101 -0
  40. structa_maestro/strategies/llm_anthropic.py +1142 -0
  41. structa_maestro/strategies/llm_config.py +154 -0
  42. structa_maestro/strategies/llm_gemini.py +1171 -0
  43. structa_maestro/strategies/llm_helpers.py +240 -0
  44. structa_maestro/strategies/llm_openai_compat.py +1183 -0
  45. structa_maestro/strategies/schema_compiler.py +248 -0
  46. structa_maestro/strategies/testing.py +71 -0
  47. structa_maestro/telemetry.py +800 -0
  48. structa_maestro/validation/__init__.py +0 -0
  49. structa_maestro/validation/cross_field.py +463 -0
  50. structa_maestro/validation/validator.py +531 -0
  51. structa_maestro-0.2.0.dist-info/METADATA +394 -0
  52. structa_maestro-0.2.0.dist-info/RECORD +55 -0
  53. structa_maestro-0.2.0.dist-info/WHEEL +4 -0
  54. structa_maestro-0.2.0.dist-info/entry_points.txt +2 -0
  55. structa_maestro-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,800 @@
1
+ """Privacy-safe observability models, observer protocols, built-in collectors, and dispatchers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import math
8
+ import statistics
9
+ import threading
10
+ from collections.abc import Mapping, Sequence
11
+ from dataclasses import dataclass, field
12
+ from datetime import UTC, datetime
13
+ from enum import StrEnum
14
+ from types import MappingProxyType
15
+ from typing import Any, Protocol, runtime_checkable
16
+
17
+ from structa_maestro.config import get_logger, sanitize_message
18
+ from structa_maestro.contracts.enums import ProcessingStatus, ValidationStatus
19
+ from structa_maestro.documents.inputs import sanitize_filename
20
+ from structa_maestro.exceptions import ConfigurationError
21
+
22
+ _logger = get_logger(__name__)
23
+
24
+ _STAGE_ORDER: tuple[str, ...] = ("document_load", "strategy", "finalization")
25
+
26
+
27
+ def utc_now_iso() -> str:
28
+ """Return a UTC ISO-8601 timestamp string."""
29
+ return datetime.now(UTC).isoformat()
30
+
31
+
32
+ def _validate_non_negative_int(value: Any, field_name: str) -> int:
33
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
34
+ raise ConfigurationError(f"{field_name} must be a non-negative integer.")
35
+ return value
36
+
37
+
38
+ def _validate_optional_non_negative_int(value: Any, field_name: str) -> int | None:
39
+ if value is None:
40
+ return None
41
+ return _validate_non_negative_int(value, field_name)
42
+
43
+
44
+ def _validate_non_negative_ms(value: Any, field_name: str) -> float:
45
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
46
+ raise ConfigurationError(f"{field_name} must be a non-negative finite number.")
47
+ fval = float(value)
48
+ if not math.isfinite(fval) or fval < 0.0:
49
+ raise ConfigurationError(f"{field_name} must be a non-negative finite number.")
50
+ return round(fval, 3)
51
+
52
+
53
+ def _validate_non_empty_str(value: Any, field_name: str) -> str:
54
+ if not isinstance(value, str) or not value.strip():
55
+ raise ConfigurationError(f"{field_name} must be a non-empty string.")
56
+ return value.strip()
57
+
58
+
59
+ class ExtractionEventKind(StrEnum):
60
+ """Closed lifecycle event enumeration for single-document and batch extraction."""
61
+
62
+ EXTRACTION_STARTED = "extraction_started"
63
+ DOCUMENT_LOADED = "document_loaded"
64
+ STRATEGY_COMPLETED = "strategy_completed"
65
+ EXTRACTION_COMPLETED = "extraction_completed"
66
+ BATCH_STARTED = "batch_started"
67
+ BATCH_ITEM_COMPLETED = "batch_item_completed"
68
+ BATCH_COMPLETED = "batch_completed"
69
+
70
+
71
+ @dataclass(frozen=True, slots=True)
72
+ class TokenUsage:
73
+ """Immutable, provider-independent LLM token accounting (`None` = unavailable)."""
74
+
75
+ prompt_tokens: int | None = None
76
+ completion_tokens: int | None = None
77
+ total_tokens: int | None = None
78
+
79
+ def __post_init__(self) -> None:
80
+ _validate_optional_non_negative_int(self.prompt_tokens, "TokenUsage.prompt_tokens")
81
+ _validate_optional_non_negative_int(self.completion_tokens, "TokenUsage.completion_tokens")
82
+ _validate_optional_non_negative_int(self.total_tokens, "TokenUsage.total_tokens")
83
+
84
+ def to_dict(self) -> dict[str, int | None]:
85
+ """Return a JSON-safe dictionary representation of token counts."""
86
+ return {
87
+ "prompt_tokens": self.prompt_tokens,
88
+ "completion_tokens": self.completion_tokens,
89
+ "total_tokens": self.total_tokens,
90
+ }
91
+
92
+ def to_json(self, *, indent: int | None = None) -> str:
93
+ """Serialize token usage to JSON."""
94
+ return json.dumps(self.to_dict(), indent=indent, ensure_ascii=False)
95
+
96
+
97
+ def parse_openai_token_usage(body: Any) -> TokenUsage | None:
98
+ """Parse an OpenAI-compatible `usage` payload without fabricating missing counts."""
99
+ if not isinstance(body, Mapping):
100
+ return None
101
+ raw_usage = body.get("usage")
102
+ if not isinstance(raw_usage, Mapping):
103
+ return None
104
+
105
+ def _safe_count(key: str) -> int | None:
106
+ val = raw_usage.get(key)
107
+ if isinstance(val, bool) or not isinstance(val, int) or val < 0:
108
+ return None
109
+ return val
110
+
111
+ prompt = _safe_count("prompt_tokens")
112
+ completion = _safe_count("completion_tokens")
113
+ total = _safe_count("total_tokens")
114
+ if prompt is None and completion is None and total is None:
115
+ return None
116
+ return TokenUsage(
117
+ prompt_tokens=prompt,
118
+ completion_tokens=completion,
119
+ total_tokens=total,
120
+ )
121
+
122
+
123
+ def parse_anthropic_token_usage(body: Any) -> TokenUsage | None:
124
+ """Parse an Anthropic Messages API `usage` payload without fabricating missing counts."""
125
+ if not isinstance(body, Mapping):
126
+ return None
127
+ raw_usage = body.get("usage")
128
+ if not isinstance(raw_usage, Mapping):
129
+ return None
130
+
131
+ def _safe_count(key: str) -> int | None:
132
+ val = raw_usage.get(key)
133
+ if isinstance(val, bool) or not isinstance(val, int) or val < 0:
134
+ return None
135
+ return val
136
+
137
+ prompt = _safe_count("input_tokens")
138
+ completion = _safe_count("output_tokens")
139
+ total = _safe_count("total_tokens")
140
+ if prompt is None and completion is None and total is None:
141
+ return None
142
+ return TokenUsage(
143
+ prompt_tokens=prompt,
144
+ completion_tokens=completion,
145
+ total_tokens=total,
146
+ )
147
+
148
+
149
+ def parse_gemini_token_usage(body: Any) -> TokenUsage | None:
150
+ """Parse a Gemini `usageMetadata` payload without fabricating missing counts."""
151
+ if not isinstance(body, Mapping):
152
+ return None
153
+ raw_usage = body.get("usageMetadata")
154
+ if not isinstance(raw_usage, Mapping):
155
+ return None
156
+
157
+ def _safe_count(key: str) -> int | None:
158
+ val = raw_usage.get(key)
159
+ if isinstance(val, bool) or not isinstance(val, int) or val < 0:
160
+ return None
161
+ return val
162
+
163
+ prompt = _safe_count("promptTokenCount")
164
+ completion = _safe_count("candidatesTokenCount")
165
+ total = _safe_count("totalTokenCount")
166
+ if prompt is None and completion is None and total is None:
167
+ return None
168
+ return TokenUsage(
169
+ prompt_tokens=prompt,
170
+ completion_tokens=completion,
171
+ total_tokens=total,
172
+ )
173
+
174
+
175
+ def merge_token_usage(a: TokenUsage | None, b: TokenUsage | None) -> TokenUsage | None:
176
+ """Cumulatively sum observed non-null token counts across strategy attempts."""
177
+ if a is None:
178
+ return b
179
+ if b is None:
180
+ return a
181
+
182
+ def _add(x: int | None, y: int | None) -> int | None:
183
+ if x is None:
184
+ return y
185
+ if y is None:
186
+ return x
187
+ return x + y
188
+
189
+ return TokenUsage(
190
+ prompt_tokens=_add(a.prompt_tokens, b.prompt_tokens),
191
+ completion_tokens=_add(a.completion_tokens, b.completion_tokens),
192
+ total_tokens=_add(a.total_tokens, b.total_tokens),
193
+ )
194
+
195
+
196
+ @dataclass(frozen=True, slots=True)
197
+ class StageTiming:
198
+ """Immutable duration record for a single pipeline stage."""
199
+
200
+ stage: str
201
+ elapsed_ms: float
202
+ succeeded: bool
203
+
204
+ def __post_init__(self) -> None:
205
+ object.__setattr__(self, "stage", _validate_non_empty_str(self.stage, "StageTiming.stage"))
206
+ object.__setattr__(
207
+ self,
208
+ "elapsed_ms",
209
+ _validate_non_negative_ms(self.elapsed_ms, "StageTiming.elapsed_ms"),
210
+ )
211
+ if not isinstance(self.succeeded, bool):
212
+ raise ConfigurationError("StageTiming.succeeded must be a boolean.")
213
+
214
+ def to_dict(self) -> dict[str, Any]:
215
+ """Return a JSON-safe dictionary representation of the stage timing."""
216
+ return {
217
+ "stage": self.stage,
218
+ "elapsed_ms": self.elapsed_ms,
219
+ "succeeded": self.succeeded,
220
+ }
221
+
222
+
223
+ @dataclass(frozen=True, slots=True)
224
+ class StageTimingSummary:
225
+ """Immutable aggregated timing statistics for a single pipeline stage (`count >= 1`)."""
226
+
227
+ stage: str
228
+ count: int
229
+ total_ms: float
230
+ mean_ms: float
231
+ p50_ms: float
232
+ max_ms: float
233
+
234
+ def __post_init__(self) -> None:
235
+ object.__setattr__(
236
+ self, "stage", _validate_non_empty_str(self.stage, "StageTimingSummary.stage")
237
+ )
238
+ if isinstance(self.count, bool) or not isinstance(self.count, int) or self.count < 1:
239
+ raise ConfigurationError("StageTimingSummary.count must be an integer >= 1.")
240
+ object.__setattr__(
241
+ self,
242
+ "total_ms",
243
+ _validate_non_negative_ms(self.total_ms, "StageTimingSummary.total_ms"),
244
+ )
245
+ object.__setattr__(
246
+ self, "mean_ms", _validate_non_negative_ms(self.mean_ms, "StageTimingSummary.mean_ms")
247
+ )
248
+ object.__setattr__(
249
+ self, "p50_ms", _validate_non_negative_ms(self.p50_ms, "StageTimingSummary.p50_ms")
250
+ )
251
+ object.__setattr__(
252
+ self, "max_ms", _validate_non_negative_ms(self.max_ms, "StageTimingSummary.max_ms")
253
+ )
254
+
255
+ def to_dict(self) -> dict[str, Any]:
256
+ """Return a JSON-safe dictionary representation of aggregated stage timings."""
257
+ return {
258
+ "stage": self.stage,
259
+ "count": self.count,
260
+ "total_ms": self.total_ms,
261
+ "mean_ms": self.mean_ms,
262
+ "p50_ms": self.p50_ms,
263
+ "max_ms": self.max_ms,
264
+ }
265
+
266
+
267
+ @dataclass(frozen=True, slots=True)
268
+ class StrategyTelemetry:
269
+ """Immutable operational metadata emitted by an extraction strategy alongside StrategyOutput."""
270
+
271
+ attempts: int
272
+ retry_count: int = 0
273
+ structured_output_mode_used: str | None = None
274
+ fallback_used: bool = False
275
+ truncated: bool = False
276
+ token_usage: TokenUsage | None = None
277
+
278
+ def __post_init__(self) -> None:
279
+ _validate_non_negative_int(self.attempts, "StrategyTelemetry.attempts")
280
+ _validate_non_negative_int(self.retry_count, "StrategyTelemetry.retry_count")
281
+ if self.structured_output_mode_used is not None:
282
+ object.__setattr__(
283
+ self,
284
+ "structured_output_mode_used",
285
+ _validate_non_empty_str(
286
+ self.structured_output_mode_used,
287
+ "StrategyTelemetry.structured_output_mode_used",
288
+ ),
289
+ )
290
+ if not isinstance(self.fallback_used, bool):
291
+ raise ConfigurationError("StrategyTelemetry.fallback_used must be a boolean.")
292
+ if not isinstance(self.truncated, bool):
293
+ raise ConfigurationError("StrategyTelemetry.truncated must be a boolean.")
294
+ if self.token_usage is not None and not isinstance(self.token_usage, TokenUsage):
295
+ raise ConfigurationError(
296
+ "StrategyTelemetry.token_usage must be a TokenUsage instance or None."
297
+ )
298
+
299
+ def to_dict(self) -> dict[str, Any]:
300
+ """Return a JSON-safe dictionary representation of strategy telemetry."""
301
+ return {
302
+ "attempts": self.attempts,
303
+ "retry_count": self.retry_count,
304
+ "structured_output_mode_used": self.structured_output_mode_used,
305
+ "fallback_used": self.fallback_used,
306
+ "truncated": self.truncated,
307
+ "token_usage": self.token_usage.to_dict() if self.token_usage is not None else None,
308
+ }
309
+
310
+
311
+ @dataclass(frozen=True, slots=True)
312
+ class BatchProgress:
313
+ """Immutable progress snapshot attached to batch lifecycle events."""
314
+
315
+ batch_id: str
316
+ total_documents: int
317
+ processed_documents: int
318
+ skipped_documents: int
319
+ item_index: int | None = None
320
+ completed_count: int = 0
321
+ partial_count: int = 0
322
+ failed_count: int = 0
323
+ aborted_early: bool = False
324
+
325
+ def __post_init__(self) -> None:
326
+ object.__setattr__(
327
+ self, "batch_id", _validate_non_empty_str(self.batch_id, "BatchProgress.batch_id")
328
+ )
329
+ total = _validate_non_negative_int(self.total_documents, "BatchProgress.total_documents")
330
+ processed = _validate_non_negative_int(
331
+ self.processed_documents, "BatchProgress.processed_documents"
332
+ )
333
+ if processed > total:
334
+ raise ConfigurationError(
335
+ "BatchProgress.processed_documents cannot exceed BatchProgress.total_documents."
336
+ )
337
+ _validate_non_negative_int(self.skipped_documents, "BatchProgress.skipped_documents")
338
+ _validate_optional_non_negative_int(self.item_index, "BatchProgress.item_index")
339
+ _validate_non_negative_int(self.completed_count, "BatchProgress.completed_count")
340
+ _validate_non_negative_int(self.partial_count, "BatchProgress.partial_count")
341
+ _validate_non_negative_int(self.failed_count, "BatchProgress.failed_count")
342
+ if not isinstance(self.aborted_early, bool):
343
+ raise ConfigurationError("BatchProgress.aborted_early must be a boolean.")
344
+
345
+ def to_dict(self) -> dict[str, Any]:
346
+ """Return a JSON-safe dictionary representation of batch progress."""
347
+ return {
348
+ "batch_id": self.batch_id,
349
+ "total_documents": self.total_documents,
350
+ "processed_documents": self.processed_documents,
351
+ "skipped_documents": self.skipped_documents,
352
+ "item_index": self.item_index,
353
+ "completed_count": self.completed_count,
354
+ "partial_count": self.partial_count,
355
+ "failed_count": self.failed_count,
356
+ "aborted_early": self.aborted_early,
357
+ }
358
+
359
+
360
+ @dataclass(frozen=True, slots=True)
361
+ class ExtractionEvent:
362
+ """Unified immutable, privacy-safe lifecycle event delivered to telemetry observers."""
363
+
364
+ event_kind: ExtractionEventKind
365
+ timestamp: str
366
+ extraction_id: str | None = None
367
+ batch_id: str | None = None
368
+ document_id: str | None = None
369
+ filename: str | None = None
370
+ media_type: str | None = None
371
+ schema_id: str | None = None
372
+ schema_version: str | None = None
373
+ strategy_name: str | None = None
374
+ elapsed_ms: float | None = None
375
+ status: ProcessingStatus | None = None
376
+ validation_status: ValidationStatus | None = None
377
+ record_count: int | None = None
378
+ error_count: int | None = None
379
+ warning_count: int | None = None
380
+ error_codes: tuple[str, ...] = ()
381
+ warning_codes: tuple[str, ...] = ()
382
+ stage_timing: StageTiming | None = None
383
+ stage_timings: tuple[StageTiming, ...] = ()
384
+ strategy_telemetry: StrategyTelemetry | None = None
385
+ batch_progress: BatchProgress | None = None
386
+
387
+ def __post_init__(self) -> None:
388
+ if not isinstance(self.event_kind, ExtractionEventKind):
389
+ raise ConfigurationError(
390
+ "ExtractionEvent.event_kind must be an ExtractionEventKind value."
391
+ )
392
+ object.__setattr__(
393
+ self,
394
+ "timestamp",
395
+ _validate_non_empty_str(self.timestamp, "ExtractionEvent.timestamp"),
396
+ )
397
+ if self.filename is not None:
398
+ object.__setattr__(self, "filename", sanitize_filename(self.filename))
399
+ if self.elapsed_ms is not None:
400
+ object.__setattr__(
401
+ self,
402
+ "elapsed_ms",
403
+ _validate_non_negative_ms(self.elapsed_ms, "ExtractionEvent.elapsed_ms"),
404
+ )
405
+ _validate_optional_non_negative_int(self.record_count, "ExtractionEvent.record_count")
406
+ _validate_optional_non_negative_int(self.error_count, "ExtractionEvent.error_count")
407
+ _validate_optional_non_negative_int(self.warning_count, "ExtractionEvent.warning_count")
408
+ object.__setattr__(self, "error_codes", tuple(self.error_codes))
409
+ object.__setattr__(self, "warning_codes", tuple(self.warning_codes))
410
+ object.__setattr__(self, "stage_timings", tuple(self.stage_timings))
411
+
412
+ def to_dict(self) -> dict[str, Any]:
413
+ """Return a JSON-safe, privacy-safe dictionary representation of the event."""
414
+ return {
415
+ "event_kind": self.event_kind.value,
416
+ "timestamp": self.timestamp,
417
+ "extraction_id": self.extraction_id,
418
+ "batch_id": self.batch_id,
419
+ "document_id": self.document_id,
420
+ "filename": self.filename,
421
+ "media_type": self.media_type,
422
+ "schema_id": self.schema_id,
423
+ "schema_version": self.schema_version,
424
+ "strategy_name": self.strategy_name,
425
+ "elapsed_ms": self.elapsed_ms,
426
+ "status": self.status.value if self.status is not None else None,
427
+ "validation_status": (
428
+ self.validation_status.value if self.validation_status is not None else None
429
+ ),
430
+ "record_count": self.record_count,
431
+ "error_count": self.error_count,
432
+ "warning_count": self.warning_count,
433
+ "error_codes": list(self.error_codes),
434
+ "warning_codes": list(self.warning_codes),
435
+ "stage_timing": (
436
+ self.stage_timing.to_dict() if self.stage_timing is not None else None
437
+ ),
438
+ "stage_timings": [st.to_dict() for st in self.stage_timings],
439
+ "strategy_telemetry": (
440
+ self.strategy_telemetry.to_dict() if self.strategy_telemetry is not None else None
441
+ ),
442
+ "batch_progress": (
443
+ self.batch_progress.to_dict() if self.batch_progress is not None else None
444
+ ),
445
+ }
446
+
447
+ def to_json(self, *, indent: int | None = None) -> str:
448
+ """Serialize the telemetry event to JSON."""
449
+ return json.dumps(self.to_dict(), indent=indent, ensure_ascii=False)
450
+
451
+
452
+ @dataclass(frozen=True, slots=True)
453
+ class TelemetrySummary:
454
+ """Immutable aggregated telemetry summary across observed extraction events."""
455
+
456
+ total_events: int
457
+ total_extractions: int
458
+ completed_count: int
459
+ partial_count: int
460
+ failed_count: int
461
+ valid_count: int
462
+ invalid_count: int
463
+ not_validated_count: int
464
+ skipped_documents: int
465
+ aborted_early_count: int
466
+ stage_timings: Mapping[str, StageTimingSummary] = field(
467
+ default_factory=lambda: MappingProxyType({})
468
+ )
469
+ total_attempts: int = 0
470
+ total_retries: int = 0
471
+ fallback_count: int = 0
472
+ truncated_count: int = 0
473
+ usage_reported_count: int = 0
474
+ prompt_tokens: int | None = None
475
+ completion_tokens: int | None = None
476
+ total_tokens: int | None = None
477
+ total_elapsed_ms: float = 0.0
478
+
479
+ def __post_init__(self) -> None:
480
+ _validate_non_negative_int(self.total_events, "TelemetrySummary.total_events")
481
+ _validate_non_negative_int(self.total_extractions, "TelemetrySummary.total_extractions")
482
+ _validate_non_negative_int(self.completed_count, "TelemetrySummary.completed_count")
483
+ _validate_non_negative_int(self.partial_count, "TelemetrySummary.partial_count")
484
+ _validate_non_negative_int(self.failed_count, "TelemetrySummary.failed_count")
485
+ _validate_non_negative_int(self.valid_count, "TelemetrySummary.valid_count")
486
+ _validate_non_negative_int(self.invalid_count, "TelemetrySummary.invalid_count")
487
+ _validate_non_negative_int(self.not_validated_count, "TelemetrySummary.not_validated_count")
488
+ _validate_non_negative_int(self.skipped_documents, "TelemetrySummary.skipped_documents")
489
+ _validate_non_negative_int(self.aborted_early_count, "TelemetrySummary.aborted_early_count")
490
+ _validate_non_negative_int(self.total_attempts, "TelemetrySummary.total_attempts")
491
+ _validate_non_negative_int(self.total_retries, "TelemetrySummary.total_retries")
492
+ _validate_non_negative_int(self.fallback_count, "TelemetrySummary.fallback_count")
493
+ _validate_non_negative_int(self.truncated_count, "TelemetrySummary.truncated_count")
494
+ _validate_non_negative_int(
495
+ self.usage_reported_count, "TelemetrySummary.usage_reported_count"
496
+ )
497
+ _validate_optional_non_negative_int(self.prompt_tokens, "TelemetrySummary.prompt_tokens")
498
+ _validate_optional_non_negative_int(
499
+ self.completion_tokens, "TelemetrySummary.completion_tokens"
500
+ )
501
+ _validate_optional_non_negative_int(self.total_tokens, "TelemetrySummary.total_tokens")
502
+ object.__setattr__(
503
+ self,
504
+ "total_elapsed_ms",
505
+ _validate_non_negative_ms(self.total_elapsed_ms, "TelemetrySummary.total_elapsed_ms"),
506
+ )
507
+ object.__setattr__(self, "stage_timings", MappingProxyType(dict(self.stage_timings)))
508
+
509
+ def to_dict(self) -> dict[str, Any]:
510
+ """Return a JSON-safe, privacy-safe dictionary representation of the telemetry summary."""
511
+ return {
512
+ "total_events": self.total_events,
513
+ "total_extractions": self.total_extractions,
514
+ "completed_count": self.completed_count,
515
+ "partial_count": self.partial_count,
516
+ "failed_count": self.failed_count,
517
+ "valid_count": self.valid_count,
518
+ "invalid_count": self.invalid_count,
519
+ "not_validated_count": self.not_validated_count,
520
+ "skipped_documents": self.skipped_documents,
521
+ "aborted_early_count": self.aborted_early_count,
522
+ "stage_timings": {k: v.to_dict() for k, v in self.stage_timings.items()},
523
+ "total_attempts": self.total_attempts,
524
+ "total_retries": self.total_retries,
525
+ "fallback_count": self.fallback_count,
526
+ "truncated_count": self.truncated_count,
527
+ "usage_reported_count": self.usage_reported_count,
528
+ "prompt_tokens": self.prompt_tokens,
529
+ "completion_tokens": self.completion_tokens,
530
+ "total_tokens": self.total_tokens,
531
+ "total_elapsed_ms": self.total_elapsed_ms,
532
+ }
533
+
534
+ def to_json(self, *, indent: int | None = None) -> str:
535
+ """Serialize the telemetry summary to JSON."""
536
+ return json.dumps(self.to_dict(), indent=indent, ensure_ascii=False)
537
+
538
+
539
+ @runtime_checkable
540
+ class ExtractionObserver(Protocol):
541
+ """Narrow synchronous observer protocol receiving privacy-safe ExtractionEvent notifications."""
542
+
543
+ def on_event(self, event: ExtractionEvent) -> None:
544
+ """Handle an emitted extraction lifecycle event."""
545
+ ...
546
+
547
+
548
+ @runtime_checkable
549
+ class AsyncExtractionObserver(Protocol):
550
+ """Narrow asyncio observer protocol receiving privacy-safe ExtractionEvent notifications."""
551
+
552
+ async def aon_event(self, event: ExtractionEvent) -> None:
553
+ """Asynchronously handle an emitted extraction lifecycle event."""
554
+ ...
555
+
556
+
557
+ AnyExtractionObserver = ExtractionObserver | AsyncExtractionObserver
558
+
559
+
560
+ class InMemoryTelemetryObserver:
561
+ """Thread-safe and asyncio-safe in-memory telemetry collector and summary aggregator."""
562
+
563
+ def __init__(self) -> None:
564
+ self._lock = threading.Lock()
565
+ self._events: list[ExtractionEvent] = []
566
+
567
+ def on_event(self, event: ExtractionEvent) -> None:
568
+ """Record an immutable ExtractionEvent safely under a lock."""
569
+ with self._lock:
570
+ self._events.append(event)
571
+
572
+ def events(self) -> tuple[ExtractionEvent, ...]:
573
+ """Return an immutable snapshot of all events recorded since creation or last reset()."""
574
+ with self._lock:
575
+ return tuple(self._events)
576
+
577
+ def reset(self) -> None:
578
+ """Clear all recorded events safely."""
579
+ with self._lock:
580
+ self._events.clear()
581
+
582
+ def summary(self) -> TelemetrySummary:
583
+ """Compute a deterministic aggregated TelemetrySummary from recorded events."""
584
+ snapshot = self.events()
585
+ total_extractions = 0
586
+ completed_count = 0
587
+ partial_count = 0
588
+ failed_count = 0
589
+ valid_count = 0
590
+ invalid_count = 0
591
+ not_validated_count = 0
592
+ skipped_documents = 0
593
+ aborted_early_count = 0
594
+
595
+ stage_samples: dict[str, list[float]] = {}
596
+ total_attempts = 0
597
+ total_retries = 0
598
+ fallback_count = 0
599
+ truncated_count = 0
600
+ usage_reported_count = 0
601
+ cumulative_usage: TokenUsage | None = None
602
+ total_elapsed_ms = 0.0
603
+
604
+ for ev in snapshot:
605
+ if ev.event_kind == ExtractionEventKind.EXTRACTION_COMPLETED:
606
+ total_extractions += 1
607
+ if ev.status == ProcessingStatus.COMPLETED:
608
+ completed_count += 1
609
+ elif ev.status == ProcessingStatus.PARTIAL:
610
+ partial_count += 1
611
+ elif ev.status == ProcessingStatus.FAILED:
612
+ failed_count += 1
613
+
614
+ if ev.validation_status == ValidationStatus.VALID:
615
+ valid_count += 1
616
+ elif ev.validation_status == ValidationStatus.INVALID:
617
+ invalid_count += 1
618
+ elif ev.validation_status == ValidationStatus.NOT_VALIDATED:
619
+ not_validated_count += 1
620
+
621
+ for st in ev.stage_timings:
622
+ stage_samples.setdefault(st.stage, []).append(st.elapsed_ms)
623
+
624
+ if ev.batch_id is None and ev.elapsed_ms is not None:
625
+ total_elapsed_ms += ev.elapsed_ms
626
+
627
+ elif ev.event_kind == ExtractionEventKind.STRATEGY_COMPLETED:
628
+ st_tel = ev.strategy_telemetry
629
+ if st_tel is not None:
630
+ total_attempts += st_tel.attempts
631
+ total_retries += st_tel.retry_count
632
+ if st_tel.fallback_used:
633
+ fallback_count += 1
634
+ if st_tel.truncated:
635
+ truncated_count += 1
636
+ if st_tel.token_usage is not None:
637
+ usage_reported_count += 1
638
+ cumulative_usage = merge_token_usage(cumulative_usage, st_tel.token_usage)
639
+
640
+ elif ev.event_kind == ExtractionEventKind.BATCH_COMPLETED:
641
+ if ev.batch_progress is not None:
642
+ skipped_documents += ev.batch_progress.skipped_documents
643
+ if ev.batch_progress.aborted_early:
644
+ aborted_early_count += 1
645
+ if ev.elapsed_ms is not None:
646
+ total_elapsed_ms += ev.elapsed_ms
647
+
648
+ ordered_stages: list[str] = [s for s in _STAGE_ORDER if s in stage_samples]
649
+ ordered_stages.extend(sorted(s for s in stage_samples if s not in _STAGE_ORDER))
650
+
651
+ stage_summaries: dict[str, StageTimingSummary] = {}
652
+ for stage_name in ordered_stages:
653
+ samples = stage_samples[stage_name]
654
+ if not samples:
655
+ continue
656
+ stage_total = sum(samples)
657
+ stage_summaries[stage_name] = StageTimingSummary(
658
+ stage=stage_name,
659
+ count=len(samples),
660
+ total_ms=round(stage_total, 3),
661
+ mean_ms=round(stage_total / len(samples), 3),
662
+ p50_ms=round(float(statistics.median(samples)), 3),
663
+ max_ms=round(max(samples), 3),
664
+ )
665
+
666
+ return TelemetrySummary(
667
+ total_events=len(snapshot),
668
+ total_extractions=total_extractions,
669
+ completed_count=completed_count,
670
+ partial_count=partial_count,
671
+ failed_count=failed_count,
672
+ valid_count=valid_count,
673
+ invalid_count=invalid_count,
674
+ not_validated_count=not_validated_count,
675
+ skipped_documents=skipped_documents,
676
+ aborted_early_count=aborted_early_count,
677
+ stage_timings=stage_summaries,
678
+ total_attempts=total_attempts,
679
+ total_retries=total_retries,
680
+ fallback_count=fallback_count,
681
+ truncated_count=truncated_count,
682
+ usage_reported_count=usage_reported_count,
683
+ prompt_tokens=cumulative_usage.prompt_tokens if cumulative_usage is not None else None,
684
+ completion_tokens=(
685
+ cumulative_usage.completion_tokens if cumulative_usage is not None else None
686
+ ),
687
+ total_tokens=cumulative_usage.total_tokens if cumulative_usage is not None else None,
688
+ total_elapsed_ms=round(total_elapsed_ms, 3),
689
+ )
690
+
691
+
692
+ class StructuredLoggingObserver:
693
+ """Zero-dependency observer emitting privacy-safe JSON telemetry records via stdlib logging."""
694
+
695
+ def __init__(
696
+ self,
697
+ *,
698
+ logger_name: str = "structa_maestro.telemetry",
699
+ level: int = logging.INFO,
700
+ ) -> None:
701
+ self._logger_name = _validate_non_empty_str(
702
+ logger_name, "StructuredLoggingObserver.logger_name"
703
+ )
704
+ if isinstance(level, bool) or not isinstance(level, int):
705
+ raise ConfigurationError("StructuredLoggingObserver.level must be an integer.")
706
+ self._level = level
707
+ self._log = get_logger(self._logger_name)
708
+
709
+ @property
710
+ def logger_name(self) -> str:
711
+ """Configured target logger name."""
712
+ return self._logger_name
713
+
714
+ @property
715
+ def level(self) -> int:
716
+ """Configured logging level."""
717
+ return self._level
718
+
719
+ def on_event(self, event: ExtractionEvent) -> None:
720
+ """Emit a compact, privacy-safe JSON log record for the event."""
721
+ self._log.log(
722
+ self._level,
723
+ event.to_json(),
724
+ extra={"structa_maestro_event": event.to_dict()},
725
+ )
726
+
727
+
728
+ def validate_observers(
729
+ observers: Sequence[Any] | None,
730
+ *,
731
+ require_sync: bool = False,
732
+ ) -> tuple[AnyExtractionObserver, ...]:
733
+ """Eagerly validate an optional observer sequence before any document I/O or strategy call."""
734
+ if observers is None:
735
+ return ()
736
+ if isinstance(observers, (str, bytes, bytearray)) or not isinstance(observers, Sequence):
737
+ raise ConfigurationError(
738
+ "observers must be a sequence of ExtractionObserver or AsyncExtractionObserver "
739
+ "instances, or None."
740
+ )
741
+
742
+ validated: list[AnyExtractionObserver] = []
743
+ for idx, obs in enumerate(observers):
744
+ is_sync = isinstance(obs, ExtractionObserver)
745
+ is_async = isinstance(obs, AsyncExtractionObserver)
746
+ if not is_sync and not is_async:
747
+ raise ConfigurationError(
748
+ f"Observer at index {idx} ({type(obs).__name__}) must implement "
749
+ "ExtractionObserver (on_event) or AsyncExtractionObserver (aon_event)."
750
+ )
751
+ if require_sync and not is_sync:
752
+ raise ConfigurationError(
753
+ f"Observer at index {idx} ({type(obs).__name__}) implements "
754
+ "AsyncExtractionObserver only; use 'await aextract(...)' / "
755
+ "'await aextract_batch(...)' or supply a synchronous ExtractionObserver."
756
+ )
757
+ validated.append(obs)
758
+ return tuple(validated)
759
+
760
+
761
+ def dispatch_event_sync(
762
+ observers: tuple[AnyExtractionObserver, ...],
763
+ event: ExtractionEvent,
764
+ ) -> None:
765
+ """Deliver an event to sync observers with strict fault isolation and secret scrubbing."""
766
+ for obs in observers:
767
+ if not isinstance(obs, ExtractionObserver):
768
+ continue
769
+ try:
770
+ obs.on_event(event)
771
+ except Exception as exc:
772
+ safe_detail = sanitize_message(f"{type(exc).__name__}: {exc}")
773
+ _logger.warning(
774
+ "Telemetry observer %s raised an error on %s: %s",
775
+ type(obs).__name__,
776
+ event.event_kind.value,
777
+ safe_detail,
778
+ )
779
+
780
+
781
+ async def dispatch_event_async(
782
+ observers: tuple[AnyExtractionObserver, ...],
783
+ event: ExtractionEvent,
784
+ ) -> None:
785
+ """Deliver an event to async/sync observers without swallowing BaseException/CancelledError."""
786
+ for obs in observers:
787
+ try:
788
+ if isinstance(obs, AsyncExtractionObserver):
789
+ await obs.aon_event(event)
790
+ elif isinstance(obs, ExtractionObserver):
791
+ obs.on_event(event)
792
+ except Exception as exc:
793
+ # BaseException (including asyncio.CancelledError) intentionally propagates immediately
794
+ safe_detail = sanitize_message(f"{type(exc).__name__}: {exc}")
795
+ _logger.warning(
796
+ "Telemetry observer %s raised an error on %s: %s",
797
+ type(obs).__name__,
798
+ event.event_kind.value,
799
+ safe_detail,
800
+ )