bhyve-workflow / app /engine.py
akashdahad's picture
Deploy bhyve-workflow (FastAPI + embedded Postgres)
74d4552 verified
Raw History Blame Contribute Delete
8.75 kB
"""The engine: runs a workflow definition over one parsed document.
GENERIC β€” it knows only the step types (extract, enrich) and how to assemble the
output from the definition. All audit specifics live in the definition (data).
Fail-closed: a run either succeeds with grounded values, or fails with a stored
reason β€” it never emits an unverified row.
"""
from dataclasses import dataclass
from dataclasses import field as dc_field
from .blocks.enrich import MATCH_REVIEW_FLOOR
from .blocks.enrich import enrich as enrich_block
from .blocks.extract import extract as extract_block
from .parsing import ParsedDoc
@dataclass
class RunResult:
status: str # "succeeded" | "failed" | "needs_review"
rows: list[dict] # list of {column_name: cell}
failure_reason: str = ""
warnings: list[str] = dc_field(default_factory=list)
stats: dict = dc_field(default_factory=dict)
review: dict | None = None # set on "needs_review": the near-match awaiting confirm
def _resolve(spec: dict, ctx: dict, card: dict, ri: int, doc: ParsedDoc, row_no: int) -> dict:
src = spec["from"]
if src == "__source__":
return {"value": doc.filename, "grounded": True, "source_quote": "", "page": ""}
if src == "__row_number__":
# Number by OUTPUT position so a gated-out row never leaves a gap (1,3,5 reads
# like data went missing); ri still drives field/page resolution below.
return {"value": str(row_no), "grounded": True, "source_quote": "", "page": ""}
sid, _, fname = src.partition(".")
recs = ctx.get(sid, [])
if not recs:
return {"value": "", "grounded": False}
rec = recs[ri] if card.get(sid) == "many" else recs[0] # broadcast doc-level fields
cell = rec.get(fname) or {"value": "", "grounded": False}
if spec.get("attr") == "page": # a provenance column (the page of another field)
return {
"value": cell.get("page", ""),
"grounded": cell.get("grounded", False),
"source_quote": cell.get("source_quote", ""),
"page": cell.get("page", ""),
}
return cell
def run_workflow(definition: dict, doc: ParsedDoc, references: dict, dry_run: bool = False, aliases: dict | None = None, extracted: dict | None = None) -> RunResult:
"""`extracted` (optional) injects already-extracted records keyed by step id,
so the draft/preview path can reuse this engine (enrich + gate + assembly) over
cached extraction without re-calling the LLM. Steps not present are extracted live."""
if not doc.has_text:
return RunResult(
"failed", [],
failure_reason=(
"No readable text layer β€” the document appears to be scanned. OCR is "
"not supported yet, so the workflow stopped rather than guess."
),
)
ctx: dict[str, list[dict]] = {}
card: dict[str, str] = {}
enrich_warnings: list[str] = []
pending_review: dict | None = None # a non-blocking near-match offered for confirm (flag mode)
for step in definition["steps"]:
sid, stype = step["id"], step["type"]
if stype == "extract":
if extracted is not None and sid in extracted:
ctx[sid] = extracted[sid] # injected from the draft cache β€” no LLM call
else:
ctx[sid] = extract_block(
doc,
step["fields"],
cardinality=step.get("cardinality", "many"),
item_label=step.get("item_label", "item"),
model=step.get("model"),
purpose=f"extract:{sid}",
)
card[sid] = step.get("cardinality", "many")
elif stype == "enrich":
src = step["input"]
ref = references.get(step["reference"])
if ref is None:
return RunResult("failed", [], failure_reason=f"Reference sheet '{step['reference']}' is not available.")
recs, info = enrich_block(
ctx.get(src, []), ref, step["match"], step["pull"],
on_miss=step.get("on_miss", "fail"),
aliases=(aliases or {}).get(step["reference"], {}),
)
ctx[sid] = recs
card[sid] = card.get(src, "one")
if not info["matched"]:
refname = ref.get("name", "the reference sheet")
left_value = info["left_value"]
cand = info.get("candidate")
near = bool(cand and cand["score"] >= MATCH_REVIEW_FLOOR)
review = {"left_value": left_value, "candidate": cand["name"],
"score": cand["score"], "reference": step["reference"]} if near else None
if step.get("on_miss", "fail") == "fail":
# Opt-in strict: stop the whole document rather than emit blank master cells.
if near:
return RunResult(
"needs_review", [],
failure_reason=(
f'"{left_value}" is not an exact match in {refname}. '
f'Closest: "{cand["name"]}". Confirm they are the same to continue.'
),
review=review,
)
return RunResult(
"failed", [],
failure_reason=(
f'"{left_value}" was not found in {refname} (no confident match). '
"Stopped rather than attach the wrong record."
),
)
# Decoupled default ("flag"): keep the rows, blank+flag the master cells
# (the enrich block already did), and offer a near-match for an optional confirm.
pulled = ", ".join(step["pull"])
enrich_warnings.append(
f'"{left_value}" not found in {refname} β€” {pulled} left blank for its rows'
+ (f' (closest: "{cand["name"]}" β€” confirm to fill)' if near else "")
)
if near:
pending_review = review
else:
return RunResult("failed", [], failure_reason=f"Unknown step type '{stype}'.")
out = definition["output"]
row_source = out["row_source"]
row_records = ctx.get(row_source, [])
if not row_records:
return RunResult("failed", [], failure_reason="No records were extracted from the document.")
# Required-field gate, PER ROW: keep the rows we can verify, drop (never emit) the
# ones missing a required, citable field β€” instead of rejecting the whole document.
def _row_verified(ri: int) -> bool:
for rf in definition.get("required_fields", []):
sid, _, fname = rf.partition(".")
recs = ctx.get(sid, [])
rec = recs[ri] if card.get(sid) == "many" else (recs[0] if recs else {})
cell = rec.get(fname) if rec else None
if not cell or not cell.get("grounded"):
return False
return True
kept = [ri for ri in range(len(row_records)) if _row_verified(ri)]
dropped = len(row_records) - len(kept)
if not kept:
return RunResult(
"failed", [],
failure_reason=(
"No row could be confidently verified β€” every row was missing a required "
"field with a citable source. Stopped rather than emit unverified rows."
),
)
# Assemble the kept rows; warn on blank OPTIONAL fields (their schema's Warnings column).
rows: list[dict] = []
blank_counts: dict[str, int] = {}
for out_no, ri in enumerate(kept, 1):
orow = {}
for col in out["columns"]:
cell = _resolve(col, ctx, card, ri, doc, out_no)
orow[col["name"]] = cell
# Skip master (from_reference) blanks here β€” already explained by enrich_warnings.
if not cell.get("grounded") and not cell.get("value") and not cell.get("from_reference"):
blank_counts[col["name"]] = blank_counts.get(col["name"], 0) + 1
rows.append(orow)
warnings = list(enrich_warnings)
warnings += [f"{n} row(s) had no value for '{c}' (not stated in the source)" for c, n in sorted(blank_counts.items())]
if dropped:
warnings.insert(0, f"{dropped} row(s) dropped β€” a required field had no citable source (kept the {len(kept)} verified rows).")
stats = {"rows": len(rows), "warnings": len(warnings), "dropped": dropped}
return RunResult("succeeded", rows, warnings=warnings, stats=stats, review=pending_review)