Introducing a new way to review your PRs.

Read the announcement

zipstack / unstract

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

View on GitHub

28 documents · Updated Nov 23, 2026

docs / agent-kv-extraction

Agent key-value extraction

Agent key-value extraction is a tenant-scoped service for asynchronous document extraction. A client uses an organization key to submit one supported extractor request, follows the job state, and reads the result while the service manages dispatch, usage limits, cancellation, notifications, and data retention.

Service boundary

The service has two related surfaces. Organization admins manage client keys through the platform API, while extraction clients use a bearer-key API whose job access is limited to the key's organization. The same execution API supports the kv and table extractors. Deployment settings decide which routed extractors can accept work.

SurfacePurposeMain outcome
Key managementCreate, list, update, rotate, enable, disable, and delete organization keysA client credential for extraction
Execution APISubmit, inspect, retrieve, cancel, and delete jobsA bounded extraction lifecycle
Internal APIReceive progress and terminal reports and run maintenanceBackend-owned job state and cleanup

kv and table share the submit, staging, rate, and result flow. A request selects the extractor inside extractors[].name; it does not use a separate endpoint. kv is accepted only when its deployment gate is enabled and its worker fleet can drain the matching queue. table is accepted without that feature flag. Both extractors use adapter resources named by the caller and owned by the caller's organization.

The backend API platform page gives the wider platform context. Key use also relates to API key usage, while job and platform concerns connect to workflow management, platform audit, platform metrics, resource usage, inbox domain, and MCP server.

References: backend/…/execution_serializers.py• L68-181 backend/…/execution_serializers.py• L400-454 backend/…/execution_views.py• L531-630

Key validation

The bearer key is the first tenant boundary for every public job request. The validator accepts only an active UUID key with an organization, then uses that organization for all later job and resource checks. Invalid, unknown, inactive, and unusable keys share one forbidden response so callers cannot probe key records.

Key administration is separate from job execution. An organization admin sees masked values in a key list, while a deliberate create, retrieve, or rotate action returns the full value needed by a client.

Every job-scoped operation applies the key's organization to the job lookup. An unknown job and a job owned by another organization therefore have the same not-found result.

References: backend/…/models.py• L12-41 backend/…/execution_views.py• L32-45 backend/…/test_job_views.py• L57-75

Job admission

Submission turns a document and one extractor request into a job only after the service confirms that the request can run safely and that the organization may spend against it. Validation happens before a concurrency slot, staged file, or dispatch is created, so malformed or unauthorized work does not become paid work.

The admission sequence is:

  1. Validate the bearer key, engine availability, request rate, subscription access, file limits, and page rules.
  2. Parse one extractor entry and validate its name, keys, options, and adapter roles. Unknown fields are rejected instead of being ignored.
  3. Resolve each named adapter against the key's organization and check its type, availability, and usage state.
  4. Reserve one organization concurrency slot.
  5. Stage the uploaded document in object storage and create the job with its expiry time.
  6. Dispatch the job. A dispatch failure marks the job failed and releases the slot.

The API accepts PDFs and Excel files only when the file bytes match the extension. A PDF page range chooses the pages the extractor reads, but the page cap still applies to the whole PDF because the full document is scanned first. Excel has no pre-scan page count, so the worker applies its page limit after processing. A webhook must pass the same public HTTPS checks used at delivery.

The request keeps job fields at the top level and puts extractor-specific keys, options, and adapters inside one entry. kv uses a compiled key schema and KV options. table requires a named target_table and uses table options. Both shipped extractors require the caller's llm, lite_llm, and x2text adapter roles. The service currently requires exactly one extractor entry so it never accepts a multi-extractor request while running only part of it.

The service also bounds multipart extractor data before it is fully read and reports malformed nested JSON as a client validation error. This keeps caller-controlled input from causing excess memory use or an unexpected server error.

This diagram shows how a request becomes either an accepted asynchronous job or a bounded failure.

flowchart LR
    A[Bearer key and document] --> B[Admission checks]
    B -->|rejected| X[No paid job]
    B --> C[Reserve organization slot]
    C -->|limit reached| Y[429 response]
    C --> D[Stage input and create job]
    D -->|storage failure| Z[Failed job and slot release]
    D --> E[Dispatch selected extractor]
    E -->|dispatch failure| Z
    E --> F[202 job response]

References: backend/…/execution_serializers.py• L224-589 backend/…/execution_serializers.py• L592-801 backend/…/execution_views.py• L309-376 backend/…/execution_views.py• L531-630 backend/…/test_submit_serializer.py• L137-190 backend/…/test_submit_view.py• L863-925

Extractor routing

Extractor routing connects the request name to the executor operation and to the job's status and result shape. The route table includes kv and table, while a separate acceptance gate prevents a route from being used before its deployment is ready.

ExtractorRequest identityProgress viewDeployment condition
kvSchema-shaped keys and KV optionsAgent stages such as extraction and QAAGENT_KV_KV_EXTRACTOR_ENABLED must be true
tablekeys.target_table and table optionstable_extractionAccepted by default

The job records the extractor that ran. Status and result payloads use that value, which keeps table progress and table output from being filed under the KV name. Queue names derive from the executor route, so each routed extractor must have a consumer in every worker fleet.

The acceptance map is explicit. A missing decision for a routed extractor refuses the request instead of silently accepting work that no worker can drain. An undefined deployment setting is also treated as a wiring fault and refuses the request.

References: backend/…/execution_serializers.py• L68-181 backend/…/execution_serializers.py• L495-589 backend/…/models.py• L44-111 backend/…/test_submit_serializer.py• L137-196

Dispatch and progress

Dispatch separates the public request from the extraction engine. The backend sends the staged input, validated schema, options, adapters, organization context, page limits, and callback data to the selected executor. The job then moves from pending to dispatched and becomes running when the executor reports its first stage.

The internal progress endpoint accepts a stage name, a running or done state, and safe scalar counters. It updates only non-terminal jobs and ignores late reports for finished jobs. The backend keeps stage names per extractor, so clients see progress that matches the engine they selected.

This sequence shows the relationship between the client, the backend, the queue, and the executor.

sequenceDiagram
    participant Client
    participant API as Agent-KV API
    participant Queue
    participant Executor
    participant Callback as Callback worker

    Client->>API: Submit document and extractor request
    API->>Queue: Dispatch job with callbacks
    API-->>Client: Job id and status URL
    Executor->>API: Report stage progress
    Client->>API: Poll status
    API-->>Client: Job and stage state
    Executor->>Callback: Complete or error callback
    Callback->>API: Finalize job
    API-->>Callback: Terminal state and webhook ownership

References: backend/…/execution_views.py• L225-250 backend/…/execution_views.py• L601-630 backend/…/test_submit_view.py• L277-321 backend/…/test_submit_view.py• L773-827

Result retrieval

Result retrieval combines the terminal job state with the result object named by that state. A non-terminal job returns a conflict because it has no stable outcome. A completed job returns the extractor result and usage data. A failed job returns a safe error and can also include an already-paid extraction when a later calculation step failed.

When a failed job contains that extraction, the response keeps success: false and adds extraction_salvaged: true with the extractor payload. This lets clients keep their failure path while still receiving data that the service already produced and billed.

Cancellation has a distinct result contract. An ordinary cancellation returns no result. If extraction finished before cancellation was observed, the result remains available with success: true and status: cancelled; clients should use success to decide whether data exists and status to understand the job state. A purged, expired, or already-swept result returns not found.

The same terminal result rules apply to inline responses when a submit request waits for completion. A failed job in the wait window receives its normal failure body rather than an empty or not-found response.

References: backend/…/execution_views.py• L253-277 backend/…/execution_views.py• L834-861 backend/…/test_failed_result_salvage.py• L113-196 backend/…/test_failed_result_salvage.py• L263-350 backend/…/test_cancelled_result_salvage.py• L578-649

Cancellation recovery

Cancellation is cooperative. The API marks the job cancelled, but it does not revoke an executor that is already running. The executor reports its end later, and the backend's guarded terminal write ensures that cancel, finalize, duplicate callbacks, and sweeps cannot overwrite the first terminal decision.

The service preserves a result when a billed extraction finishes during a cancellation race. It attaches that result to the cancelled row without changing the cancelled status. The attach is allowed only when the row is still cancelled, has no result, and has not been purged. A duplicate callback or a purged row cannot attach a second result.

The purge marker is separate from the result reference. This matters because a failed object delete leaves its reference as a retry handle. The marker still tells both result reads and late callbacks that the caller asked for the files to be destroyed.

Slots follow the work that can still spend:

  • A job cancelled before dispatch releases its slot at once.
  • A dispatched job keeps its slot until finalization or recovery confirms that the executor has ended.
  • A cancelled job with no callback can have its slot released by the abandoned-job sweep after its safety window.

The cancellation notification is sent by the request that wins the terminal guard. A later salvaged result can cause one additive result_available notification, but it does not compete with the cancellation notification.

References: backend/…/models.py• L147-186 backend/…/models.py• L270-375 backend/…/execution_views.py• L101-153 backend/…/execution_views.py• L686-921 backend/…/test_cancelled_result_salvage.py• L157-321 backend/…/test_job_views.py• L844-965

Rate limits and slot recovery

The service applies a per-key request rate and a per-organization count of in-flight jobs. Redis holds both limits, and the concurrency claim is atomic so simultaneous submissions cannot all pass the same capacity check. The default behavior fails closed when Redis is unavailable; an explicit availability setting can choose fail-open behavior.

Slots are released when admission fails, a terminal callback wins, an undispatched job is cancelled, or maintenance recovers stranded work. Release is safe to repeat, which lets finalization and maintenance repair the same job without creating a second capacity claim.

Cancellation checks fresh database evidence before releasing a slot. A dispatch timestamp or a reported stage means an executor may exist, even when the request holds an older job object. This prevents a cancel race from returning a live slot while the worker still spends against it.

References: backend/…/execution_views.py• L101-153 backend/…/execution_views.py• L583-599 backend/…/execution_views.py• L725-761 backend/…/execution_views.py• L871-896 backend/…/test_job_views.py• L296-351 backend/…/test_job_views.py• L893-965

Storage retention and cleanup

Object storage holds the staged input, result, and OCR document cache outside the message queue. Each job has organization- and job-specific references for its input and result. The job row remains as an audit record after its files are removed, while the result API stops serving data after purge or expiry.

Cleanup has three related paths:

  • Terminal finalization removes the staged input as soon as it wins the terminal guard. A failed delete keeps its reference for retry.
  • Explicit deletion cancels live work before marking the files purged. The purge marker blocks a late callback from making deleted data readable again.
  • TTL cleanup handles expired terminal jobs. It marks purge intent before deletion, keeps failed references, and reserves part of each batch for retry work so old storage faults cannot starve new expirations.

The purge marker was added as a direct record of deletion intent. It is written before delete attempts and remains true when a delete fails. This prevents a retained retry reference from being mistaken for permission to serve the result.

The OCR document cache has no job row because one cached document can serve many jobs. Maintenance sweeps cache entries by age, examines a bounded rotating set, and treats a cache delete as safe to repeat because a miss only causes reprocessing. A cache listing or object failure does not fail the rest of the job cleanup tick.

References: backend/…/models.py• L147-208 backend/…/models.py• L211-268 backend/…/0008_agentkvjob_files_purged.py• L1-43 backend/…/execution_views.py• L769-826 backend/…/execution_views.py• L840-861 backend/…/test_cancelled_result_salvage.py• L219-463

Internal worker coordination

The backend owns job state. Executors perform extraction and report progress and terminal outcomes through internal calls, while callback workers deliver terminal webhooks and scheduler or CronJob workers invoke platform-wide maintenance.

Terminal notification ownership follows the winning terminal write. The backend queues the webhook when finalization or a sweep wins, and the cancel path queues its own notification. The callback worker uses the enqueue result to avoid both duplicate delivery and silent loss. If backend queueing fails, the worker retains delivery responsibility. This separates durable job completion from delivery of an external notification.

Maintenance exposes one shared implementation through internal endpoints and management commands. Its sweep reports never-dispatched jobs, timed-out in-flight jobs, and recovered cancelled-job slots. Its TTL path reports cleaned and retained job files plus document-cache results.

References: backend/…/execution_views.py• L762-767 backend/…/execution_views.py• L896-907 backend/…/test_job_views.py• L761-842 backend/…/test_cancelled_result_salvage.py• L464-577

Public route boundary

The execution path is excluded from the platform's normal authentication middleware because its views authenticate bearer keys themselves. Its configured path prefix is therefore a security boundary, not only a URL preference.

An empty prefix or a prefix that is an ancestor of another API surface is refused at startup. Such a value could exempt every request or bypass authentication for a wider API. The shipped prefix is checked against the mounted route and documented examples so a path change does not look like an invalid client key.

References: backend/…/test_path_prefix_guard.py• L1-17 backend/…/test_path_prefix_guard.py• L48-98 backend/…/test_docs_examples.py• L129-227

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the extractor route, acceptance gate, worker queue, option and adapter rules, stage list, job extractor value, and result key aligned. A route without an enabled consumer can accept work that only times out later.
  • Keep the submit-time page measure aligned with the executor's page measure. A mismatch moves a rejected job failure after staging, slot acquisition, and the 202 response.
  • Keep the terminal write guard and the fresh dispatch evidence aligned with slot ownership. Every new terminal or recovery path must define who owns the slot and the terminal webhook.
  • Keep files_purged separate from input and result references. A failed delete must retain its reference for retry while the API still treats the job as purged.
  • Keep cancellation salvage limited to an unpurged cancelled row with no existing result. A wider attach rule can revive deleted data or overwrite a real outcome.
  • Keep job cleanup and cache cleanup on their correct axes. Job files follow terminal job rows; shared OCR cache entries follow age.
  • Keep every internal report scoped by the same organization identifier used when dispatch creates the job. A mismatch turns valid callbacks into unknown-job no-ops.
  • Keep adapter role names, organization ownership, type checks, and recorded job IDs aligned. A change can otherwise move a caller's spend to a different resource or fail only in the worker.
  • Keep the configured route prefix disjoint from wider authenticated surfaces and update the mounted path and customer examples together.
  • Keep customer-facing request examples valid for each enabled extractor. The examples are checked through the real submit serializer.

Important failure modes

TriggerConsequenceGuard
A routed extractor has no enabled consumerThe submit succeeds, then the job remains in flight until the stuck sweep fails itUse an explicit acceptance gate and keep it aligned with worker queue wiring
A gated extractor has no defined deployment settingWork is refused for a wiring fault or accepted under the wrong deployment assumptionTreat a missing gate decision as refusal and report the wiring fault
A PDF page range is used to bypass the document capA large document reaches paid scanning workCompare the cap with the whole measured PDF
A caller names another organization's adapter or the wrong adapter typeThe job can spend against the wrong resource or fail after stagingResolve adapters with the key's organization and expected role type before slot acquisition
A callback uses the wrong organization identifierProgress and finalization become no-ops and the job is later reported as timed outScope internal reports with the job's organization identifier
Cancellation wins after extraction has finishedThe caller can lose an already-paid answer or receive a misleading empty resultAttach one result to an unpurged cancelled row and keep status: cancelled
A failed calculation follows a successful extractionThe caller gets a failure with no access to the extraction already billedReturn the additive extraction_salvaged result while keeping success: false
A late callback follows explicit deletionDeleted output becomes readable again or an untracked result file remainsRecord purge intent before deletion and reject late attachment and reads
Object deletion fails and the reference is blankedThe object remains in storage with no retry pathBlank only confirmed deletions and retain failed references
A cancellation releases a slot from a stale pre-dispatch rowA live executor runs outside the organization limitRe-read dispatch or stage evidence before releasing the slot
A cache listing or delete failsMaintenance stops or leaves shared OCR data without an age-based cleanup passBound the cache sweep and report per-object failures without failing job cleanup
The route prefix is empty or swallows another API prefixBearer-key authentication is skipped for a wider surfaceReject unsafe prefixes during configuration validation

Key files

FileWhy to read it
backend/…/execution_views.pyPublic submit, status, result, cancellation, deletion, adapter checks, and slot ownership
backend/…/execution_serializers.pyFile admission, extractor selection, request shape, page limits, webhook checks, deployment gates, and adapter shape rules
backend/…/models.pyJob states, terminal write guard, cancellation salvage, purge marker, and organization scope
backend/…/dispatch.pyExecutor dispatch and terminal webhook ownership
backend/…/internal_views.pyWorker progress, finalization, salvage, and maintenance entry points
backend/…/execution_views_result.pyTerminal result and failure payload rules
backend/…/maintenance.pyStranded-job recovery, cancelled-slot recovery, TTL cleanup, and cache cleanup coordination
backend/…/storage.pyInput, result, and shared document-cache retention
backend/…/0008_agentkvjob_files_purged.pyThe explicit purge intent contract
backend/…/test_adapter_scoping.pyOrganization-scoped adapter resolution without request-local tenant context
backend/…/test_cancelled_result_salvage.pyCancellation races, purge ordering, and salvaged result serving
backend/…/test_failed_result_salvage.pyFailed-job extraction recovery and retention rules
backend/…/test_job_views.pyJob endpoint scope, result states, cancellation, deletion, and slot recovery
backend/…/test_path_prefix_guard.pySecurity checks for the public route prefix
backend/…/test_submit_serializer.pyFile, schema, extractor, adapter, page, and webhook admission rules
backend/…/test_submit_view.pyAdmission ordering, staging cleanup, dispatch cleanup, and end-to-end submit contracts
backend/…/test_docs_examples.pyContract between customer examples, mounted paths, and submit validation
docs/backend-api-platform.mdParent page for backend API boundaries and platform services
docs/api-key-usage.mdRelated API key usage context