Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 11 additions & 50 deletions backend/agent_kv/execution_views_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,7 @@ def result_payload(job) -> dict:

- COMPLETED: ``{success, status, extractors, usage_summary}`` -- the stored
engine result namespaced per extractor (spec §7.3), not the bare blob.
- FAILED: ``{"success": False, "status": "failed", "error": <user-safe>}``,
plus ``extraction_salvaged: True`` and ``extractors`` when the run failed
only at a later stage and handed over the extraction it had already
completed and billed (today: a failed ``calculations`` run). ``success``
stays False -- part of what the caller asked for did not happen.
- FAILED: ``{"success": False, "status": "failed", "error": <user-safe>}``.
- CANCELLED: ``{"success": False, "status": "cancelled"}`` -- unless the
cancel lost a race to an extraction that had already finished and been
billed, in which case the paid-for result is served with ``success: True``
Expand All @@ -52,26 +48,15 @@ def result_payload(job) -> dict:
# carry it. This is the ONLY `success` describing the job.
#
# This used to add "each extractor keeps its own `success` inside
# its own block", and the correction that replaced it over-reached
# in the other direction: it said "No extractor does", which is
# true of `table` and false of `kv`.
#
# `table` writes `tables`, `page_count`, `table_pages`, `headers`,
# `row_count`, `detected` and `reason`, and its only nested
# `success` belongs to `code_execution`, describing that step
# rather than the extraction. That half stands, and it is the half
# that cost real time -- an e2e scenario asserted a per-extractor
# `success` and would have failed a successful Excel run.
#
# `kv` DOES carry one (`agentic_kv/src/engine/kv_extractor.py`
# sets it), so a strict response model built from the stronger
# claim would reject a valid `kv` result. It is only ever True in
# a COMPLETED body: the engine sets it False on a failed
# `calculations` run, and that fails the job, so the shape is the
# FAILED one below.
#
# Either way this is the only `success` describing the JOB, which
# is the part a client needs.
# its own block". No extractor does: `table` writes `tables`,
# `page_count`, `table_pages`, `headers`, `row_count`, `detected`
# and `reason`, and the sole nested `success` belongs to
# `code_execution`, describing that step rather than the
# extraction. The claim read as a contract and cost real time --
# an e2e scenario asserted it and would have failed a successful
# Excel run. A per-extractor `success` can be added if a
# multi-extractor job ever needs partial failure; until then do
# not document one.
"success": True,
"status": JobStatus.COMPLETED.lower(),
"extractors": {job.extractor: read_result(job.result_ref)},
Expand All @@ -84,35 +69,11 @@ def result_payload(job) -> dict:
},
}
if job.status == JobStatus.FAILED:
failed: dict = {
return {
"success": False,
"status": "failed",
"error": job.error or "Job failed",
}
# A FAILED job can carry an extraction, and `success` stays False when
# it does.
#
# The job really did fail -- a `calculations` run the caller asked for
# did not produce output -- so saying otherwise would be a lie, and it
# would be a BREAKING one: a client branching on `success` to decide
# whether to run its error path would stop running it. The cancelled
# race flips `success` to True for the opposite reason: nothing the
# caller asked for failed there, the cancel was honoured and the answer
# is whole. Here part of the request genuinely did not happen.
#
# So the extraction is additive instead, and `extraction_salvaged`
# states it rather than leaving a client to probe for `extractors` on a
# shape that has never carried it. Present only when it applies, the
# same convention as the engine's advisory markers.
#
# No `usage_summary`: neither executor path that salvages has computed
# one by the time it gives up. Its absence is not "free" -- the
# extraction was billed; the figures are in `usage_v2`, which the
# caller cannot read.
if job.result_ref:
failed["extraction_salvaged"] = True
failed["extractors"] = {job.extractor: read_result(job.result_ref)}
return failed
# A cancel that lost the race to a finished extraction keeps its result
# (`AgentKVJob.attach_result_to_cancelled`). The engine had already spent
# and flushed the OCR and LLM usage by the time the cancel could collide
Expand Down
80 changes: 7 additions & 73 deletions backend/agent_kv/internal_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,10 +201,7 @@ def post(self, request, *args, job_id=None, **kwargs):


class FinalizeView(APIView):
"""Terminalize a job: write its result, if it has one, then mark it done.

"If it has one" rather than "on success": a FAILED job can carry an
extraction too -- see ``_fail``.
"""Terminalize a job: write its result (on success) then mark it done.

Idempotent: a job already in a terminal state short-circuits before any
write, with ONE exception -- a success callback for an already-``CANCELLED``
Expand Down Expand Up @@ -299,80 +296,17 @@ def _complete(job, job_id, org_id: str, body) -> tuple[bool, bool]:

@staticmethod
def _fail(job, job_id, org_id: str, body) -> tuple[bool, bool]:
"""Terminalize as FAILED, keeping a salvaged extraction if one came.

Returns ``(guard won, False)``. The second element is always False:
``result_attached`` means "kept on a row this request did NOT
terminalize", which is the cancelled-race case alone. A result stored
here is stored by the request that won the guard, so it needs no
separate signal and owes no follow-up notification.

**A failure can carry a result, and this used to assume it could not.**
The docstring here read "there is no result to attach to anything on a
failure", which is true of every failure except the one that matters:
the `kv` engine fails a job whose `calculations` run failed, because
the caller asked for calculations and did not get them -- while the
extraction itself succeeded and its OCR and LLM spend was already
flushed. The executor hands that record over deliberately rather than
destroying it, and both this method and the callback worker dropped it,
so the customer paid for an extraction and got
``{"success": false, "status": "failed", "error": ...}``.

``mark_terminal`` already took ``result_ref``/``usage_summary`` for any
terminal status, so storing it needs no new write path and no new
column -- the result is written and the ref goes into the same guarded
UPDATE that sets FAILED, as one decision rather than two.

**The orphan case is ``_complete``'s, for the same reason.**
``write_result`` has to run before the guard to have a ref to pass in,
so a cancel or a duplicate landing in between leaves a file with
nothing pointing at it; it is deleted here, best-effort, exactly as
``_complete`` does.

**Unlike ``_salvage``, this needs no pre-flight read.** That one is
called precisely when the row was ALREADY terminal, so every
redelivered callback reached it and the write-then-refuse storm was the
ordinary case. ``post`` only calls this handler for a row that read as
non-terminal, so a redelivered failure callback short-circuits before
getting here and never touches storage.

**Known residual:** if a cancel wins the guard against a salvaging
failure, the extraction is discarded -- ``_salvage`` stays success-only,
so a CANCELLED row will not take a failed run's partial record. That
window is narrow (it needs the cancel to land between the write and the
UPDATE) and it is no worse than before this change. Widening
``_salvage`` to failures would put a partial record on a cancelled row
through the attach path, which section 6 of ``docs/agent-kv-api.md``
records as reverted three times; it is not worth that for this window.
"""Terminalize as FAILED. ``(guard won, False)``.

The second element is always False: there is no result to attach to
anything on a failure. It exists so both handlers share one shape and
``post`` can call whichever it picked without knowing which it got.
"""
# `salvaged` is empty on every ordinary failure, and THAT guard is
# load-bearing: without it every failure writes an empty result file to
# object storage and gives the row a ref to a document holding nothing.
#
# `result_ref=""` is then passed through unguarded, because
# `mark_terminal` already does `if result_ref:` and an empty one cannot
# change the UPDATE. A conditional here would be the dead branch the
# executor removed for exactly this reason after mutation testing found
# it ("an untested branch that cannot change the outcome is worse than
# no branch") -- so the same standard is applied here.
salvaged = body.get("result") or {}
result_ref = write_result(org_id, str(job_id), salvaged) if salvaged else ""
finalized = AgentKVJob.mark_terminal(
job_id,
org_id,
JobStatus.FAILED,
error=body.get("error") or "",
result_ref=result_ref,
job_id, org_id, JobStatus.FAILED, error=body.get("error") or ""
)
if finalized:
job.status = JobStatus.FAILED
job.result_ref = result_ref
elif result_ref:
# Guard lost after the write: another terminalization won, so
# nothing references this file. Same best-effort delete as
# `_complete`'s discard path, and `storage.delete_job_files` reaps
# the directory later if it fails.
delete_result_file(result_ref)
return finalized, False

@staticmethod
Expand Down
Loading
Loading