graph-knowledge-doc-parser 0.2.14__tar.gz → 0.2.15__tar.gz
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.
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/PKG-INFO +1 -1
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/semantic_document_splitting_layerwise_edits.py +62 -25
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/__init__.py +10 -1
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/handlers.py +47 -4
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/layered_contracts.py +60 -10
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/layerwise_llm.py +17 -5
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/models.py +124 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/page_index.py +120 -1
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/parser_core.py +658 -118
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/parsing.py +5 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/runners.py +5 -1
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/semantics.py +179 -20
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/service.py +2 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/pyproject.toml +1 -1
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/README.md +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/__init__.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/cast_hinting.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/document_ingest_log_config.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/document_ingester_logger.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/llm_structured_output.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/models.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/ocr.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/pdf2png.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/text_processing_utils.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/utils/__init__.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/utils/bounded_threadpool_executor.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/utils/file_loaders.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/utils/langchain.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/utils/log.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/utils/version_chaining.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/_kogwistar.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/adapters.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/cache.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/cli.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/clients.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/demo_harness.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/design.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/ocr_pipeline.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/probe.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/providers.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/serialization.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/smoke_assets.py +0 -0
- {graph_knowledge_doc_parser-0.2.14 → graph_knowledge_doc_parser-0.2.15}/kg_doc_parser/workflow_ingest/strategy.py +0 -0
|
@@ -12,7 +12,7 @@ Usage
|
|
|
12
12
|
>>> document_tree, source_map = parse_doc(doc_id="my_doc", raw_doc_dict=doc_data)
|
|
13
13
|
>>> # Convert to KGE Payload
|
|
14
14
|
>>> from kg_doc_parser.semantic_document_splitting_layerwise_edits import semantic_tree_to_kge_payload
|
|
15
|
-
>>> graph_payload = semantic_tree_to_kge_payload(document_tree)
|
|
15
|
+
>>> graph_payload = semantic_tree_to_kge_payload(document_tree, parser_source_map=source_map)
|
|
16
16
|
|
|
17
17
|
Pipeline Flow
|
|
18
18
|
-------------
|
|
@@ -138,6 +138,7 @@ from kg_doc_parser.llm_structured_output import build_structured_output_runnable
|
|
|
138
138
|
|
|
139
139
|
from .document_ingest_log_config import configured_document_ingest_log_db
|
|
140
140
|
from .workflow_ingest.providers import WorkflowProviderSettings, build_chat_model
|
|
141
|
+
from .workflow_ingest.semantics import validate_semantic_tree_integrity
|
|
141
142
|
|
|
142
143
|
_LAYERWISE_TRACE_ENV = "KG_DOC_LAYERWISE_TRACE_FILE"
|
|
143
144
|
|
|
@@ -193,7 +194,7 @@ cb = DocumentIngestSQLiteCallback(db_path=_DOCUMENT_INGEST_LOG_DB,
|
|
|
193
194
|
include_traceback = True)
|
|
194
195
|
|
|
195
196
|
|
|
196
|
-
|
|
197
|
+
TPartitionItem = TypeVar("TPartitionItem")
|
|
197
198
|
|
|
198
199
|
def memory_cached(
|
|
199
200
|
memory: Memory, *arg: object, **kwarg: object
|
|
@@ -204,8 +205,9 @@ def memory_cached(
|
|
|
204
205
|
|
|
205
206
|
|
|
206
207
|
def partition(
|
|
207
|
-
iterable: Iterable[
|
|
208
|
-
|
|
208
|
+
iterable: Iterable[TPartitionItem],
|
|
209
|
+
predicate: Callable[[TPartitionItem], bool],
|
|
210
|
+
) -> tuple[list[TPartitionItem], list[TPartitionItem]]:
|
|
209
211
|
t1 = []
|
|
210
212
|
t2 = []
|
|
211
213
|
for x in iterable:
|
|
@@ -2133,19 +2135,19 @@ class ChildrenCorrectionResult(NamedTuple):
|
|
|
2133
2135
|
# ============================================================================
|
|
2134
2136
|
from typing import Any, Protocol, TypeVar
|
|
2135
2137
|
|
|
2136
|
-
|
|
2138
|
+
TStructuredModel = TypeVar("TStructuredModel", bound=BaseModel)
|
|
2137
2139
|
|
|
2138
2140
|
class StructuredLLMCaller(Protocol):
|
|
2139
2141
|
def __call__(
|
|
2140
2142
|
self,
|
|
2141
2143
|
prompt: str,
|
|
2142
2144
|
model_names: list[str],
|
|
2143
|
-
schema: type[
|
|
2145
|
+
schema: type[TStructuredModel],
|
|
2144
2146
|
doc_id: str,
|
|
2145
2147
|
model_json_schema: dict,
|
|
2146
2148
|
event_name: str,
|
|
2147
2149
|
i_attempt: int
|
|
2148
|
-
) ->
|
|
2150
|
+
) -> TStructuredModel:
|
|
2149
2151
|
...
|
|
2150
2152
|
|
|
2151
2153
|
# Cache completed provider calls, not the correction orchestrator. Joblib does
|
|
@@ -2153,8 +2155,14 @@ class StructuredLLMCaller(Protocol):
|
|
|
2153
2155
|
# successful structured response can be replayed without another LLM call.
|
|
2154
2156
|
@parser_llm_cache
|
|
2155
2157
|
def _default_call_llm_structured(
|
|
2156
|
-
prompt: str,
|
|
2157
|
-
|
|
2158
|
+
prompt: str,
|
|
2159
|
+
model_names: list[str],
|
|
2160
|
+
schema: type[TStructuredModel],
|
|
2161
|
+
doc_id: str,
|
|
2162
|
+
model_json_schema: dict,
|
|
2163
|
+
event_name: str,
|
|
2164
|
+
i_attempt: int,
|
|
2165
|
+
) -> TStructuredModel:
|
|
2158
2166
|
"""Default implementation using LangChain Google Generative AI stack.
|
|
2159
2167
|
Swap this out if you prefer OpenAI or another provider.
|
|
2160
2168
|
"""
|
|
@@ -2195,8 +2203,7 @@ def _default_call_llm_structured(
|
|
|
2195
2203
|
# ============================================================================
|
|
2196
2204
|
# Iterative level correction orchestrator
|
|
2197
2205
|
# ============================================================================
|
|
2198
|
-
|
|
2199
|
-
from typing import Any, TypeVar
|
|
2206
|
+
from typing import Any
|
|
2200
2207
|
|
|
2201
2208
|
|
|
2202
2209
|
def iterative_correct_children_for_level(
|
|
@@ -3147,10 +3154,17 @@ def reconstruct_text_from_pointers(pointers: list[HydratedTextPointer], source_m
|
|
|
3147
3154
|
|
|
3148
3155
|
def print_tree(node: SemanticNode, indent: str = "") -> None:
|
|
3149
3156
|
"""Visualizes the hydrated tree. No longer needs source_map."""
|
|
3150
|
-
|
|
3151
|
-
|
|
3152
|
-
|
|
3153
|
-
|
|
3157
|
+
pending: list[tuple[SemanticNode, str]] = [(node, indent)]
|
|
3158
|
+
while pending:
|
|
3159
|
+
current, current_indent = pending.pop()
|
|
3160
|
+
reconstructed_text = "".join(
|
|
3161
|
+
pointer.verbatim_text or "" for pointer in current.total_content_pointers
|
|
3162
|
+
)
|
|
3163
|
+
print(
|
|
3164
|
+
f"{current_indent} L- {current.title} ({current.node_type}) | "
|
|
3165
|
+
f"Text: '{reconstructed_text[:150].strip()}...'"
|
|
3166
|
+
)
|
|
3167
|
+
pending.extend((child, current_indent + " ") for child in reversed(current.child_nodes))
|
|
3154
3168
|
@parser_llm_cache
|
|
3155
3169
|
def parse_doc(
|
|
3156
3170
|
doc_id: str,
|
|
@@ -3189,6 +3203,11 @@ def parse_doc(
|
|
|
3189
3203
|
model_names=model_names,
|
|
3190
3204
|
)
|
|
3191
3205
|
_emit_layerwise_trace("parse_doc.build_document_tree.done", doc_id=doc_id)
|
|
3206
|
+
validate_semantic_tree_integrity(
|
|
3207
|
+
document_tree,
|
|
3208
|
+
parser_source_map=source_map,
|
|
3209
|
+
max_depth=max_depth,
|
|
3210
|
+
)
|
|
3192
3211
|
cov: CoverageResponse = compute_pointer_coverage(document_tree, source_map)
|
|
3193
3212
|
print("Overall coverage:", cov.overall)
|
|
3194
3213
|
for cid, r in cov.per_cluster.items():
|
|
@@ -3235,9 +3254,23 @@ def parse_doc(
|
|
|
3235
3254
|
def semantic_tree_to_kge_payload(
|
|
3236
3255
|
root: "SemanticNode",
|
|
3237
3256
|
*,
|
|
3257
|
+
parser_source_map: dict[str, dict[str, object]] | None = None,
|
|
3238
3258
|
doc_id: str | None = None,
|
|
3239
3259
|
insertion_method: str = "semantic_document_parser_v1",
|
|
3240
3260
|
) -> dict[str, Any]:
|
|
3261
|
+
# Legacy export is a persistence boundary: historical unary trees fail
|
|
3262
|
+
# closed rather than being silently rewritten into a different graph.
|
|
3263
|
+
pending_nodes = [root]
|
|
3264
|
+
has_source_pointers = False
|
|
3265
|
+
while pending_nodes:
|
|
3266
|
+
node = pending_nodes.pop()
|
|
3267
|
+
if node.total_content_pointers or getattr(node, "aggregate_content_pointers", []):
|
|
3268
|
+
has_source_pointers = True
|
|
3269
|
+
break
|
|
3270
|
+
pending_nodes.extend(node.child_nodes)
|
|
3271
|
+
if parser_source_map is None and has_source_pointers:
|
|
3272
|
+
raise ValueError("source-grounded graph export requires parser_source_map")
|
|
3273
|
+
validate_semantic_tree_integrity(root, parser_source_map=parser_source_map)
|
|
3241
3274
|
if doc_id is None:
|
|
3242
3275
|
doc_id = str(
|
|
3243
3276
|
stable_id(
|
|
@@ -3289,7 +3322,10 @@ def semantic_tree_to_kge_payload(
|
|
|
3289
3322
|
"source_cluster_id": p.source_cluster_id,
|
|
3290
3323
|
"verification": None
|
|
3291
3324
|
} for p in ptrs]
|
|
3292
|
-
|
|
3325
|
+
pending: list[tuple[SemanticNode, int]] = [(root, 0)]
|
|
3326
|
+
while pending:
|
|
3327
|
+
node, depth = pending.pop()
|
|
3328
|
+
node.level_from_root = depth
|
|
3293
3329
|
ptrs = list(node.total_content_pointers)
|
|
3294
3330
|
pointers_payload = [p.model_dump(field_mode = 'backend') for p in ptrs]
|
|
3295
3331
|
|
|
@@ -3313,7 +3349,6 @@ def semantic_tree_to_kge_payload(
|
|
|
3313
3349
|
nodes.append(node_dict)
|
|
3314
3350
|
|
|
3315
3351
|
for child in node.child_nodes:
|
|
3316
|
-
child.level_from_root = node.level_from_root + 1
|
|
3317
3352
|
edge_ptr_refs = _pointers_to_references(ptrs) # parent’s pointers as provenance
|
|
3318
3353
|
edge_ptr_mentions= _spans_to_groundings_to_mentions(_pointers_to_spans(ptrs))
|
|
3319
3354
|
edge_dict = {
|
|
@@ -3343,9 +3378,7 @@ def semantic_tree_to_kge_payload(
|
|
|
3343
3378
|
}
|
|
3344
3379
|
edges.append(edge_dict)
|
|
3345
3380
|
|
|
3346
|
-
|
|
3347
|
-
root.level_from_root = 0
|
|
3348
|
-
walk(root)
|
|
3381
|
+
pending.extend((child, depth + 1) for child in reversed(node.child_nodes))
|
|
3349
3382
|
nodes[0].update({"properties": {"kind": "document_root"}}) # document root
|
|
3350
3383
|
return {
|
|
3351
3384
|
"doc_id": doc_id,
|
|
@@ -3482,12 +3515,14 @@ def kge_payload_to_semantic_tree(payload: dict[str, Any]) -> "SemanticNode":
|
|
|
3482
3515
|
|
|
3483
3516
|
root_candidates = [s for s in sem_nodes.values() if s.parent_id is None]
|
|
3484
3517
|
if root_candidates:
|
|
3485
|
-
|
|
3518
|
+
root = root_candidates[0]
|
|
3486
3519
|
else:
|
|
3487
3520
|
all_child_ids = {cid for cids in children_by_parent.values() for cid in cids}
|
|
3488
3521
|
all_ids = set(sem_nodes.keys())
|
|
3489
3522
|
root_ids = list(all_ids - all_child_ids)
|
|
3490
|
-
|
|
3523
|
+
root = sem_nodes[root_ids[0]] if root_ids else list(sem_nodes.values())[0]
|
|
3524
|
+
validate_semantic_tree_integrity(root)
|
|
3525
|
+
return root
|
|
3491
3526
|
|
|
3492
3527
|
def all_child_from_root(
|
|
3493
3528
|
root: SemanticNode,
|
|
@@ -3495,9 +3530,11 @@ def all_child_from_root(
|
|
|
3495
3530
|
) -> list[SemanticNode]:
|
|
3496
3531
|
if results is None:
|
|
3497
3532
|
results = []
|
|
3498
|
-
|
|
3499
|
-
|
|
3500
|
-
|
|
3533
|
+
pending = list(reversed(root.child_nodes))
|
|
3534
|
+
while pending:
|
|
3535
|
+
node = pending.pop()
|
|
3536
|
+
results.append(node)
|
|
3537
|
+
pending.extend(reversed(node.child_nodes))
|
|
3501
3538
|
return results
|
|
3502
3539
|
|
|
3503
3540
|
available_node_ids = ContextVar("indexing_nodes", default=set())
|
|
@@ -36,6 +36,7 @@ from .models import (
|
|
|
36
36
|
LayerDuplicateChildNote,
|
|
37
37
|
LayerFrontierItem,
|
|
38
38
|
LayerSpanConflict,
|
|
39
|
+
LayerValidationDiagnostic,
|
|
39
40
|
NormalizedPage,
|
|
40
41
|
NormalizedSourceCollection,
|
|
41
42
|
ParseSessionState,
|
|
@@ -109,7 +110,12 @@ from .runners import (
|
|
|
109
110
|
run_page_index_batch_workflow,
|
|
110
111
|
run_page_index_source_workflow,
|
|
111
112
|
)
|
|
112
|
-
from .semantics import
|
|
113
|
+
from .semantics import (
|
|
114
|
+
HydratedTextPointer,
|
|
115
|
+
SemanticNode,
|
|
116
|
+
validate_semantic_tree_integrity,
|
|
117
|
+
validate_semantic_tree_shape,
|
|
118
|
+
)
|
|
113
119
|
from .service import build_default_engines, build_runtime, run_ingest_workflow
|
|
114
120
|
from .smoke_assets import generate_ocr_smoke_assets
|
|
115
121
|
from .strategy import (
|
|
@@ -146,6 +152,8 @@ __all__ = [
|
|
|
146
152
|
"HierarchicalSummaryAssignment",
|
|
147
153
|
"HierarchicalSummaryBatch",
|
|
148
154
|
"HydratedTextPointer",
|
|
155
|
+
"validate_semantic_tree_shape",
|
|
156
|
+
"validate_semantic_tree_integrity",
|
|
149
157
|
"IngestExecutionClient",
|
|
150
158
|
"IngestRunHandle",
|
|
151
159
|
"IngestRunResult",
|
|
@@ -154,6 +162,7 @@ __all__ = [
|
|
|
154
162
|
"LayerDuplicateChildNote",
|
|
155
163
|
"LayerFrontierItem",
|
|
156
164
|
"LayerSpanConflict",
|
|
165
|
+
"LayerValidationDiagnostic",
|
|
157
166
|
"LayerwiseWorkflowCommandResult",
|
|
158
167
|
"NormalizedPage",
|
|
159
168
|
"NormalizedSourceCollection",
|
|
@@ -227,7 +227,11 @@ def _build_export_bundle(
|
|
|
227
227
|
normalized = WorkflowIngestInput.model_validate(ctx.state_view["normalized_input"])
|
|
228
228
|
collection = select_primary_collection(normalized)
|
|
229
229
|
tree = SemanticNode.model_validate(ctx.state_view["semantic_tree"])
|
|
230
|
-
graph_payload = semantic_tree_to_kge_payload(
|
|
230
|
+
graph_payload = semantic_tree_to_kge_payload(
|
|
231
|
+
tree,
|
|
232
|
+
doc_id=collection.collection_id,
|
|
233
|
+
parser_source_map=_parser_source_map(ctx.state_view["parser_source_map"]),
|
|
234
|
+
)
|
|
231
235
|
deps = runtime_deps or {}
|
|
232
236
|
persistence_mode = str(ctx.state_view.get("persistence_mode", deps.get("persistence_mode", "local_debug")))
|
|
233
237
|
kg_authority = str(ctx.state_view.get("kg_authority", deps.get("kg_authority", "local")))
|
|
@@ -688,11 +692,11 @@ def register_layerwise_parser_steps(
|
|
|
688
692
|
result = CurrentLayerResult(
|
|
689
693
|
children=candidates,
|
|
690
694
|
satisfied=bool(candidates),
|
|
695
|
+
atomic_retained=not bool(candidates),
|
|
691
696
|
metadata={
|
|
692
697
|
"parse_strategy": "page_index",
|
|
693
698
|
"page_index_layer_only": True,
|
|
694
699
|
"allow_empty_layer": not bool(candidates),
|
|
695
|
-
"atomic_retained": not bool(candidates),
|
|
696
700
|
},
|
|
697
701
|
)
|
|
698
702
|
with ctx.state_write as st:
|
|
@@ -854,7 +858,35 @@ def register_layerwise_parser_steps(
|
|
|
854
858
|
current_layer_review.overlap_conflicts
|
|
855
859
|
or current_layer_review.coverage_gap_notes
|
|
856
860
|
or current_layer_review.duplicate_child_notes
|
|
861
|
+
or current_layer_review.structural_issues
|
|
862
|
+
or current_layer_review.validation_diagnostics
|
|
857
863
|
)
|
|
864
|
+
# A mixed batch may contain valid refinements for some parents and a
|
|
865
|
+
# rejected refinement for others. Do not discard the valid subset or
|
|
866
|
+
# let the provider's aggregate verdict hide the failed parents. Run
|
|
867
|
+
# the deterministic commit gate here so the next steps can commit the
|
|
868
|
+
# validated subset and requeue only the failed parents.
|
|
869
|
+
if (
|
|
870
|
+
not current_layer_review.metadata.get("review_failure")
|
|
871
|
+
and (current_layer_result.satisfied is False or not coverage_ok or has_conflicts)
|
|
872
|
+
):
|
|
873
|
+
partial_review = validate_layer_commit(
|
|
874
|
+
current_layer_context=current_layer_context,
|
|
875
|
+
current_layer_result=current_layer_result,
|
|
876
|
+
parser_source_map=_parser_source_map(ctx.state_view.get("parser_source_map")),
|
|
877
|
+
)
|
|
878
|
+
if (
|
|
879
|
+
partial_review.committable_parent_node_ids
|
|
880
|
+
and partial_review.failed_parent_node_ids
|
|
881
|
+
):
|
|
882
|
+
with ctx.state_write as st:
|
|
883
|
+
st["current_layer_result"] = (
|
|
884
|
+
partial_review.updated_result or current_layer_result
|
|
885
|
+
).model_dump(field_mode="backend", dump_format="json")
|
|
886
|
+
st["current_layer_review"] = partial_review.model_dump(
|
|
887
|
+
field_mode="backend", dump_format="json"
|
|
888
|
+
)
|
|
889
|
+
return _success("repair_layer_pointers")
|
|
858
890
|
if current_layer_result.satisfied is False or not coverage_ok or has_conflicts:
|
|
859
891
|
# Disable the failed operator for this parent layer. When triage
|
|
860
892
|
# is enabled, even PageIndex may be retried through the remaining
|
|
@@ -869,8 +901,14 @@ def register_layerwise_parser_steps(
|
|
|
869
901
|
reasons.append(
|
|
870
902
|
f"layer has {len(current_layer_review.overlap_conflicts)} overlap conflicts, "
|
|
871
903
|
f"{len(current_layer_review.coverage_gap_notes)} coverage gaps, "
|
|
872
|
-
f"{len(current_layer_review.duplicate_child_notes)} duplicates"
|
|
904
|
+
f"{len(current_layer_review.duplicate_child_notes)} duplicates, "
|
|
905
|
+
f"{len(current_layer_review.structural_issues)} structural issues, "
|
|
906
|
+
f"{len(current_layer_review.validation_diagnostics)} validation diagnostics"
|
|
873
907
|
)
|
|
908
|
+
reasons.extend(
|
|
909
|
+
f"{diagnostic.phase} validation: {diagnostic.message}"
|
|
910
|
+
for diagnostic in current_layer_review.validation_diagnostics
|
|
911
|
+
)
|
|
874
912
|
strategy = str(current_layer_context.metadata.get("parse_strategy", "layer_excerpt"))
|
|
875
913
|
raw_disabled = current_layer_context.metadata.get("disabled_strategies")
|
|
876
914
|
disabled = {
|
|
@@ -996,11 +1034,14 @@ def register_layerwise_parser_steps(
|
|
|
996
1034
|
current_layer_context = CurrentLayerContext.model_validate(ctx.state_view["current_layer_context"])
|
|
997
1035
|
current_layer_result = CurrentLayerResult.model_validate(ctx.state_view["current_layer_result"])
|
|
998
1036
|
current_layer_review = CurrentLayerReview.model_validate(ctx.state_view["current_layer_review"])
|
|
1037
|
+
parse_session = ParseSessionState.model_validate(ctx.state_view["parse_session"])
|
|
999
1038
|
updated_tree = commit_layer_children(
|
|
1000
1039
|
semantic_tree=semantic_tree,
|
|
1001
1040
|
current_layer_result=current_layer_result,
|
|
1002
1041
|
current_depth=current_layer_context.depth,
|
|
1003
|
-
parent_node_ids=
|
|
1042
|
+
parent_node_ids=current_layer_review.committable_parent_node_ids,
|
|
1043
|
+
parser_source_map=_parser_source_map(ctx.state_view.get("parser_source_map")),
|
|
1044
|
+
max_depth=parse_session.max_depth,
|
|
1004
1045
|
)
|
|
1005
1046
|
with ctx.state_write as st:
|
|
1006
1047
|
st["semantic_tree"] = updated_tree.model_dump()
|
|
@@ -1053,9 +1094,11 @@ def register_layerwise_parser_steps(
|
|
|
1053
1094
|
|
|
1054
1095
|
@_register_step(resolver, step_name="finalize_semantic_tree", runtime_deps=runtime_deps)
|
|
1055
1096
|
def _finalize_semantic_tree(ctx: StepContext) -> StepRunResult:
|
|
1097
|
+
parse_session = ParseSessionState.model_validate(ctx.state_view["parse_session"])
|
|
1056
1098
|
tree = finalize_semantic_tree(
|
|
1057
1099
|
SemanticNode.model_validate(ctx.state_view["semantic_tree"]),
|
|
1058
1100
|
parser_source_map=_parser_source_map(ctx.state_view.get("parser_source_map")),
|
|
1101
|
+
max_depth=parse_session.max_depth,
|
|
1059
1102
|
)
|
|
1060
1103
|
with ctx.state_write as st:
|
|
1061
1104
|
st["semantic_tree"] = tree.model_dump()
|
|
@@ -12,7 +12,7 @@ from dataclasses import dataclass
|
|
|
12
12
|
from datetime import UTC, datetime
|
|
13
13
|
from typing import cast
|
|
14
14
|
|
|
15
|
-
from pydantic import BaseModel, ConfigDict, Field
|
|
15
|
+
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
|
16
16
|
|
|
17
17
|
from .models import (
|
|
18
18
|
CurrentLayerResult,
|
|
@@ -22,13 +22,16 @@ from .models import (
|
|
|
22
22
|
)
|
|
23
23
|
from .parser_core import (
|
|
24
24
|
ProposeLayerFn,
|
|
25
|
+
commit_layer_children,
|
|
25
26
|
enqueue_next_layer_frontier,
|
|
26
27
|
initialize_parse_session,
|
|
27
28
|
legacy_children_for_context,
|
|
28
29
|
prepare_layer_frontier,
|
|
29
30
|
propose_layer_breakdown,
|
|
31
|
+
requeue_failed_frontier_items,
|
|
32
|
+
validate_layer_commit,
|
|
30
33
|
)
|
|
31
|
-
from .semantics import SemanticNode
|
|
34
|
+
from .semantics import SemanticNode, validate_semantic_tree_integrity
|
|
32
35
|
from .serialization import JsonValue
|
|
33
36
|
|
|
34
37
|
|
|
@@ -79,6 +82,11 @@ class LayeredParseSeedResult(BaseModel):
|
|
|
79
82
|
diagnostics: LayeredPayload = Field(default_factory=dict)
|
|
80
83
|
usage: LayeredParseUsage = Field(default_factory=LayeredParseUsage)
|
|
81
84
|
|
|
85
|
+
@model_validator(mode="after")
|
|
86
|
+
def _validate_root(self) -> "LayeredParseSeedResult":
|
|
87
|
+
validate_semantic_tree_integrity(self.root, max_depth=self.session.max_depth)
|
|
88
|
+
return self
|
|
89
|
+
|
|
82
90
|
|
|
83
91
|
class LayeredParseExpandRequest(BaseModel):
|
|
84
92
|
model_config = ConfigDict(extra="forbid", frozen=True)
|
|
@@ -91,6 +99,15 @@ class LayeredParseExpandRequest(BaseModel):
|
|
|
91
99
|
source_map: LayeredSourceMap
|
|
92
100
|
limits: LayeredParseLimits = Field(default_factory=LayeredParseLimits)
|
|
93
101
|
|
|
102
|
+
@model_validator(mode="after")
|
|
103
|
+
def _validate_input_tree(self) -> "LayeredParseExpandRequest":
|
|
104
|
+
validate_semantic_tree_integrity(
|
|
105
|
+
SemanticNode.model_validate(self.semantic_tree),
|
|
106
|
+
parser_source_map=cast(dict[str, dict[str, object]], self.source_map),
|
|
107
|
+
max_depth=min(self.limits.max_depth, self.session.max_depth),
|
|
108
|
+
)
|
|
109
|
+
return self
|
|
110
|
+
|
|
94
111
|
|
|
95
112
|
class LayeredParseExpandResult(BaseModel):
|
|
96
113
|
model_config = ConfigDict(extra="forbid")
|
|
@@ -104,6 +121,11 @@ class LayeredParseExpandResult(BaseModel):
|
|
|
104
121
|
diagnostics: LayeredPayload = Field(default_factory=dict)
|
|
105
122
|
usage: LayeredParseUsage = Field(default_factory=LayeredParseUsage)
|
|
106
123
|
|
|
124
|
+
@model_validator(mode="after")
|
|
125
|
+
def _validate_result_tree(self) -> "LayeredParseExpandResult":
|
|
126
|
+
validate_semantic_tree_integrity(self.semantic_tree, max_depth=self.session.max_depth)
|
|
127
|
+
return self
|
|
128
|
+
|
|
107
129
|
|
|
108
130
|
def initialize_layered_parse(request: LayeredParseSeedRequest) -> LayeredParseSeedResult:
|
|
109
131
|
"""Create a coarse root and one bounded frontier item."""
|
|
@@ -199,13 +221,34 @@ def expand_layered_frontier(
|
|
|
199
221
|
semantic_tree=semantic_tree,
|
|
200
222
|
propose_layer_fn=propose_layer_fn,
|
|
201
223
|
)
|
|
224
|
+
commit_review = validate_layer_commit(
|
|
225
|
+
current_layer_context=context,
|
|
226
|
+
current_layer_result=layer_result,
|
|
227
|
+
parser_source_map=_parser_source_map(request.source_map),
|
|
228
|
+
)
|
|
229
|
+
if not commit_review.satisfied:
|
|
230
|
+
reasons = "; ".join(commit_review.review_notes[:4])
|
|
231
|
+
raise ValueError(f"layered parse refinement failed structural validation: {reasons}")
|
|
232
|
+
committed_result = commit_review.updated_result or layer_result
|
|
233
|
+
updated_tree = commit_layer_children(
|
|
234
|
+
semantic_tree=semantic_tree,
|
|
235
|
+
current_layer_result=committed_result,
|
|
236
|
+
current_depth=context.depth,
|
|
237
|
+
parent_node_ids=commit_review.committable_parent_node_ids,
|
|
238
|
+
parser_source_map=_parser_source_map(request.source_map),
|
|
239
|
+
max_depth=request.limits.max_depth,
|
|
240
|
+
)
|
|
202
241
|
next_frontier = enqueue_next_layer_frontier(
|
|
203
242
|
frontier_queue=remaining,
|
|
204
243
|
current_layer_context=context,
|
|
205
|
-
current_layer_result=
|
|
244
|
+
current_layer_result=committed_result,
|
|
206
245
|
parse_session=session,
|
|
207
246
|
)
|
|
208
|
-
|
|
247
|
+
next_frontier = requeue_failed_frontier_items(
|
|
248
|
+
frontier_queue=next_frontier,
|
|
249
|
+
parent_node_ids=commit_review.failed_parent_node_ids,
|
|
250
|
+
depth=context.depth,
|
|
251
|
+
)
|
|
209
252
|
elapsed_ms = int((time.monotonic() - started) * 1000)
|
|
210
253
|
if (
|
|
211
254
|
request.limits.wall_time_seconds is not None
|
|
@@ -228,13 +271,13 @@ def expand_layered_frontier(
|
|
|
228
271
|
session=updated_session,
|
|
229
272
|
consumed_frontier=selected,
|
|
230
273
|
remaining_frontier=next_frontier,
|
|
231
|
-
children=list(
|
|
274
|
+
children=list(committed_result.children),
|
|
232
275
|
semantic_tree=updated_tree,
|
|
233
276
|
stable=stable,
|
|
234
277
|
diagnostics={
|
|
235
278
|
"phase": "parsed_graph_persisted" if stable else "parse_expanding",
|
|
236
279
|
"frontier_batch_size": len(selected),
|
|
237
|
-
"child_count": len(
|
|
280
|
+
"child_count": len(committed_result.children),
|
|
238
281
|
},
|
|
239
282
|
usage=LayeredParseUsage(
|
|
240
283
|
parser_calls=0 if session.mode == "legacy_compat" else 1,
|
|
@@ -292,12 +335,19 @@ def _attach_children(tree: SemanticNode, result: CurrentLayerResult) -> Semantic
|
|
|
292
335
|
)
|
|
293
336
|
)
|
|
294
337
|
|
|
295
|
-
|
|
296
|
-
|
|
338
|
+
rebuilt: dict[int, SemanticNode] = {}
|
|
339
|
+
pending: list[tuple[SemanticNode, bool]] = [(tree, False)]
|
|
340
|
+
while pending:
|
|
341
|
+
node, exiting = pending.pop()
|
|
342
|
+
if not exiting:
|
|
343
|
+
pending.append((node, True))
|
|
344
|
+
pending.extend((child, False) for child in reversed(node.child_nodes))
|
|
345
|
+
continue
|
|
346
|
+
updated_children = [rebuilt[id(child)] for child in node.child_nodes]
|
|
297
347
|
updated_children.extend(children_by_parent.get(str(node.node_id), []))
|
|
298
|
-
|
|
348
|
+
rebuilt[id(node)] = node.model_copy(update={"child_nodes": updated_children})
|
|
299
349
|
|
|
300
|
-
return
|
|
350
|
+
return rebuilt[id(tree)]
|
|
301
351
|
|
|
302
352
|
|
|
303
353
|
__all__ = [
|
|
@@ -1507,11 +1507,11 @@ def _assemble_layer_result_from_boundaries(
|
|
|
1507
1507
|
return CurrentLayerResult(
|
|
1508
1508
|
children=[],
|
|
1509
1509
|
satisfied=True,
|
|
1510
|
+
atomic_retained=True,
|
|
1510
1511
|
reasoning_history=[LayerReasoningEntry(source="boundary_first_deterministic_empty")],
|
|
1511
1512
|
metadata={
|
|
1512
1513
|
"fallback": "boundary_empty",
|
|
1513
1514
|
"allow_empty_layer": True,
|
|
1514
|
-
"atomic_retained": True,
|
|
1515
1515
|
},
|
|
1516
1516
|
), [], []
|
|
1517
1517
|
|
|
@@ -1720,7 +1720,19 @@ def _structured_invoke(
|
|
|
1720
1720
|
else:
|
|
1721
1721
|
parsed_dump = getattr(parsed, "model_dump", None)
|
|
1722
1722
|
if callable(parsed_dump):
|
|
1723
|
-
|
|
1723
|
+
# Internal adapters and test doubles may return a
|
|
1724
|
+
# richer Pydantic model than the provider DTO.
|
|
1725
|
+
# Narrow only that trusted model instance to the
|
|
1726
|
+
# declared schema; mappings from the provider stay
|
|
1727
|
+
# strict so extra fields cannot bypass validation.
|
|
1728
|
+
payload = parsed_dump()
|
|
1729
|
+
if isinstance(payload, dict):
|
|
1730
|
+
payload = {
|
|
1731
|
+
field_name: payload[field_name]
|
|
1732
|
+
for field_name in schema.model_fields
|
|
1733
|
+
if field_name in payload
|
|
1734
|
+
}
|
|
1735
|
+
result = schema.model_validate(payload)
|
|
1724
1736
|
else:
|
|
1725
1737
|
result = schema.model_validate(parsed)
|
|
1726
1738
|
else:
|
|
@@ -1762,11 +1774,11 @@ def _fallback_layer_result(
|
|
|
1762
1774
|
return CurrentLayerResult(
|
|
1763
1775
|
children=[],
|
|
1764
1776
|
satisfied=True,
|
|
1777
|
+
atomic_retained=True,
|
|
1765
1778
|
reasoning_history=[LayerReasoningEntry(source="deterministic_depth_stop")],
|
|
1766
1779
|
metadata={
|
|
1767
1780
|
"fallback": "depth_stop",
|
|
1768
1781
|
"allow_empty_layer": True,
|
|
1769
|
-
"atomic_retained": True,
|
|
1770
1782
|
},
|
|
1771
1783
|
)
|
|
1772
1784
|
parent_ids = list(getattr(current_layer_context, "parent_node_ids", []) or [])
|
|
@@ -2337,7 +2349,7 @@ def build_layerwise_llm_callbacks(
|
|
|
2337
2349
|
target_cut_offset=target.cut_offset,
|
|
2338
2350
|
refined_cutpoint_count=len(refinement_decisions),
|
|
2339
2351
|
)
|
|
2340
|
-
except Exception as refinement_exc:
|
|
2352
|
+
except Exception as refinement_exc:
|
|
2341
2353
|
refinement_notes.append(
|
|
2342
2354
|
f"boundary refinement skipped for {target.parent_node_id}:{target.source_cluster_id}:{target.cut_offset} "
|
|
2343
2355
|
f"due to {refinement_exc!r}"
|
|
@@ -2471,13 +2483,13 @@ def build_layerwise_llm_callbacks(
|
|
|
2471
2483
|
fallback = CurrentLayerResult(
|
|
2472
2484
|
children=[],
|
|
2473
2485
|
satisfied=True,
|
|
2486
|
+
atomic_retained=True,
|
|
2474
2487
|
reasoning_history=list(fallback.reasoning_history),
|
|
2475
2488
|
metadata=cast(
|
|
2476
2489
|
dict[str, JsonValue],
|
|
2477
2490
|
{
|
|
2478
2491
|
**dict(fallback.metadata),
|
|
2479
2492
|
"allow_empty_layer": True,
|
|
2480
|
-
"atomic_retained": True,
|
|
2481
2493
|
"boundary_rejected_child_ids": fallback_identical_ids,
|
|
2482
2494
|
},
|
|
2483
2495
|
),
|