Artifact-Backed Indexes

How one full-text, vector, or graph index unions the records that enrichments generate, and how to tell when it is ready

An artifact-backed index consumes the records that named enrichments produce, rather than the source documents themselves. Its sources array unions up to 64 streams into one full-text, embeddings, or graph index, and full-text/embeddings members keep the stable identity (artifact, key), so records from those streams do not collide when their keys match. Graph sources instead reconcile by relationship identity: they may intentionally collide, with source declaration order determining precedence and producing-document ownership retained. The decision this page is read for: when to search whole documents and their extracted chunks as one index, and how to know when that index is actually serving all of them.

Confirm the deployment supports it first:

curl http://127.0.0.1:8080/db/v1/status

index_capabilities.artifact_sources must be true. Embedded, standalone, and distributed deployments support artifact sources. Serverless rejects them and does not emulate older artifact-index behavior.

Document and Chunk Vectors in One Index#

One document-level embedding captures the whole; the chunks that document extraction produces are more precise. Indexing both as members of one embeddings index closes that gap. Both embedding enrichments must share compatible dimensions and a compatible vector space.

{
  "type": "embeddings",
  "dimension": 768,
  "embedder": { "provider": "antfly", "model": "BAAI/bge-base-en-v1.5" },
  "sources": [
    { "artifact": "document_dense_v1" },
    { "artifact": "document_chunk_dense_v1" }
  ],
  "enrichments": [
    {
      "name": "document_chunks_v1",
      "kind": "chunk",
      "field": "semantic_content",
      "chunk_size": 512
    },
    {
      "name": "document_dense_v1",
      "kind": "embedding",
      "field": "semantic_content",
      "expected_dims": 768,
      "vector_space": "searchaf:v1"
    },
    {
      "name": "document_chunk_dense_v1",
      "kind": "embedding",
      "field": "text",
      "source_artifact_name": "document_chunks_v1",
      "expected_dims": 768,
      "vector_space": "searchaf:v1"
    }
  ]
}

Create it at POST /db/v1/tables/{table}/indexes/document_vectors. vector_space is an application-owned compatibility identifier: every source in a multi-source index must either use the same explicit identifier or use semantically identical producer configurations, and explicit and implicit modes cannot be mixed.

Query document_vectors through the normal semantic search API. Raw member results keep their artifact identity. When the UI needs one source document with its matching chunks nested beneath it, use hierarchy grouping and request the documented top-level field projection.

Full-Text Sources With Different Shapes#

A top-level field is inherited by every source that does not override it. A source-local field lets one index union artifact records with different JSON shapes:

{
  "type": "full_text",
  "field": "text",
  "sources": [
    { "artifact": "document_units_v1", "field": "summary" },
    { "artifact": "document_chunks_v1" }
  ]
}

document_units_v1 indexes summary; document_chunks_v1 inherits text. If neither level names a field, Antfly uses the default text projection. Missing, null, and non-text values add no postings.

To query a named full-text index, set full_text_index together with full_text_search or a scoring text clause in the recursive query AST:

{
  "full_text_index": "document_text",
  "full_text_search": { "query": "retrieval augmented generation" },
  "limit": 10
}

Filter-only and exclusion-only query trees are not scoring text queries and receive HTTP 422 when combined with full_text_index.

Graph Sources and Edge Ownership#

Graph sources are ordered. When two sources materialize the same edge identity, the earlier source wins. Mapping (path, format, nodes, edge, and context) belongs on each source, because streams can use different record shapes. The optional source object is the one-source convenience form and is mutually exclusive with sources.

Every materialized relationship belongs to the document that produced its artifact. By default that document is also the logical source endpoint, and nodes.target maps the target. An optional nodes.source template maps a different logical source; it requires an edge.edge_id mapping. Ownership still belongs to the producing document, so replay, deletion, and range transfers follow the fact even when neither endpoint is that document.

Without edge_id, identity is (index, source, type, target): repeated writes update the same relationship. With edge_id, identity also includes the producing document and the supplied ID. Two facts with the same endpoints and type therefore survive independently. A repeated explicit identity is an idempotent upsert. IDs are scoped to that identity, not globally unique, and a UUID stored only in metadata does not affect identity. Use a stable producer ID; random IDs generated during replay and array positions that change when input reorders are unsuitable.

Project searchable facts onto arbitrary endpoints#

This index keeps each fact as a normal document and projects its relations field into the graph:

{
  "type": "graph",
  "source": {
    "artifact": "fact_relations_v1",
    "path": "$",
    "nodes": {
      "source": "{{ _item.source }}",
      "target": "{{ _item.target }}"
    },
    "edge": {
      "edge_id": "{{ _doc.key }}",
      "type": "RELATES_TO",
      "weight": "{{ _item.confidence }}"
    }
  },
  "artifact": {
    "name": "fact_relations_v1",
    "kind": "asset",
    "source": { "type": "field", "value": "relations" },
    "content_type": "application/json"
  }
}

Insert these documents under keys fact:works and fact:founded:

{
  "fact": "Alice works at Acme",
  "relations": [{ "source": "alice", "target": "acme", "confidence": 0.9 }]
}
{
  "fact": "Alice co-founded Acme",
  "relations": [{ "source": "alice", "target": "acme", "confidence": 0.8 }]
}

Both relationships have type RELATES_TO, so type filters continue to work. Their edge_id values distinguish the facts; owner_document in edge and path results identifies the producing document when it differs from the logical source. Fetch that document from the graph index's table for its text, embeddings, provenance, and validity fields. Endpoint hydration continues to return entity documents. For several same-pair relationships produced by one document, map a per-item UUID instead of _doc.key.

Updating a fact's artifact replaces its previous relationship projection, including retiring relationships whose endpoints changed. Deleting the fact or removing its source artifact removes its relationships. Updating or deleting an endpoint document does not delete independently owned fact relationships; endpoints can exist without stored entity documents. Deleting one of several facts leaves the pair connected until its last relationship disappears. Ordered source precedence applies to the same complete relationship identity within one owner.

Endpoint cleanup covers relationships stored on the deleting shard. It retires incident source-owned relationships, including parallel IDs and self loops. Retirement survives graph replay, reconstruction, and snapshot restore. Independently owned fact relationships keep their fact-document lifecycle. An explicit relationship write can revive that exact identity; a meaningful update to the producing document starts a new projection lifecycle. Rewriting an identical document preserves retirement. Explicit relationship deletion also survives replay and restore. Deleting a graph index clears its retirements before an index with the same name can be recreated.

Node traversal returns distinct reached nodes; relationship matches and paths retain relationship IDs. K-shortest paths can differ only by fact ID. Type, weight, and metadata predicates apply to relationships before neighbor admission. Graph degree counts relationships, and existing unweighted PageRank, eigenvector, and HITS use relationship multiplicity; connectivity treats parallel relationships as the same connection. These metrics do not aggregate confidence weights. To compute distinct-neighbor degree or aggregate confidence, materialize a separate pair projection with an application-chosen aggregation rule. Tree types allow one parent relationship, including its ID, per source and type.

For source-owned indexes, outgoing traversal routes directly to the source's shard. Incoming traversal uses an exact, bounded route directory fenced by topology and per-shard read generations; a cold entry uses compact reverse-index probes. When an index maps arbitrary source endpoints, outgoing and bidirectional expansion consult the pinned shard set because the fact can belong to any shard. Work and retained-byte budgets still apply. The owner shard maintains both endpoint adjacency directions locally; range transfer copies owner records and reconstructs endpoint adjacency.

Fact predicates, weighted paths, and counts#

Project traversal-relevant properties into each relation item alongside its endpoints:

{
  "fact": "Alice works at Acme",
  "relations": [{
    "source": "alice", "target": "acme", "confidence": 0.9,
    "group_id": "team-a",
    "valid_at": "2020-01-01T00:00:00Z", "invalid_at": null,
    "created_at": "2020-02-01T00:00:00Z", "expired_at": null
  }]
}

Without an explicit metadata mapping, the relation item becomes edge metadata, preserving JSON nulls and numeric literals through field extraction, projection, repair, and restore. Edge weights are converted separately to double precision. These projected fields are updated with the fact document. Entity or fact hydration does not supply traversal predicates: the edge projection must carry them.

Use edge_filter on traverse, shortest_path, k_shortest_paths, or on each MATCH edge. Every relationship in a variable-length MATCH edge must pass its filter. Filters apply before node deduplication, path ranking, OPTIONAL matching, NOT EXISTS checks, and counting. They work in either direction and across shards.

{
  "graph_queries": {
    "fact_paths": {
      "index": "facts",
      "k_shortest_paths": {
        "from": { "key": "alice" }, "to": { "key": "acme" },
        "k": 2, "objective": "max_weight_product",
        "edge_types": ["RELATES_TO"],
        "edge_filter": {
          "valid_at": "2022-01-01T00:00:00Z",
          "known_at": "2023-01-01T00:00:00Z",
          "properties": [{ "field": "/metadata/group_id", "op": "eq", "value": "team-a" }]
        }
      }
    }
  }
}

valid_at tests the fact's [valid_at, invalid_at) interval; known_at tests its [created_at, expired_at) interval. Missing or null valid-time bounds are open. A knowledge-time test requires a non-null created_at. Invalid timestamp properties fail the filter. These names refer to metadata fields, distinct from the graph's physical creation/update timestamps. RFC3339 timezone offsets and fractions are compared as instants, including dates before 1970.

Property predicates use JSON pointers, including ~0 and ~1 escaping and array indices, and combine with AND. Operators are eq, ne, lt, lte, gt, gte, is_null, and is_not_null. Supply a non-null scalar value for comparisons; omit it for null tests. Missing/null properties fail all comparisons, including ne, matching Cypher's WHERE behavior. Different scalar types do not compare. Numeric metadata literals compare exactly, including large integers, long decimals, and exponent notation. Stored edge weights compare using their shortest round-trip decimal, so a stored double-precision 0.1 matches /weight equal to 0.1; distinct literals remain distinct. Strings compare lexically unless value_type is datetime, which requires RFC3339 strings. At most 64 predicates totaling 64 KiB are accepted, with up to 256 components per JSON pointer. Array indices use canonical unsigned decimal spelling. Metadata numbers retain their precision in graph responses. Filters prepare constants once and scan only the requested metadata paths; temporary decoding uses the graph query memory budget.

Relationship IDs and owner document keys have no separate 64 KiB limit; they consume the existing request, storage, and graph work budgets. HTTP identities are nonempty UTF-8 strings. An explicit owner equal to the logical source is canonicalized to implicit source ownership, so specifying it does not create a second relationship identity.

Embedded C ABI traversal, shortest-path, K-path, and named graph-query requests accept the same edge_filter object as HTTP. Edge and path responses carry edge_id_b64 and owner_document_b64, preserving opaque native identifiers just like source_b64 and target_b64. Path edges also expose metadata_json and traversal_direction (0 outgoing, 1 incoming, 2 both; null for an unoriented self-loop). Traversal paths retain the exact selected fact relationship. Native Zig callers can use findShortestPathWithOptions and findKShortestPathsWithOptions; the original positional methods remain available.

Path objectives are explicit: min_hops, min_weight_sum for nonnegative costs, or max_weight_product for confidence weights in [0,1]. Same-type parallel facts remain separate candidates, with their own weights and metadata. K paths can differ only by relationship ID and owner. Predicates choose the traversable graph first; they are not applied after selecting the cheapest path. Filtered queries use exact edge expansion when an algebraic optimization cannot prove equivalent results.

Algebraic provenance labels are opaque strings. Versioned labels use the prefix antfly:graph-provenance:v1: and a lossless base64url payload. Read relationship IDs, owners, and endpoints from the structured path_edges fields rather than parsing provenance labels.

For a fixed one-hop MATCH, count(*) counts relationship matches, while a distinct target alias counts connected entities. MATCH anchors enumerate stored documents: store entity documents alongside facts when using those entities as anchors. Direct traversal can start from a graph key without a stored entity document. For joins or variable-length patterns, count(*) counts complete matches, not globally unique relationships. For example:

{
  "graph_queries": {
    "counts": {
      "index": "facts",
      "match": {
        "anchor": "a",
        "nodes": { "a": { "filter": { "ids": ["alice"] } }, "b": {} },
        "edges": [{ "from": "a", "to": "b", "types": ["RELATES_TO"],
          "edge_filter": { "valid_at": "2022-01-01T00:00:00Z" } }]
      },
      "return": { "aggregates": {
        "facts": { "count": "*" },
        "entities": { "count": "b", "distinct": true }
      } }
    }
  }
}

Neo4j also allows multiple same-type relationships between two nodes. Its Cypher shortest-path selectors select by hop count and support relationship prefilters; weighted K paths are supplied by GDS Yen's algorithm. Antfly exposes these behaviors through its graph query API rather than accepting Cypher. The two temporal intervals follow Graphiti's fact model.

Storage compatibility#

Implicit relationships retain their existing keys. Explicit identities use a versioned key suffix, and derived journal records containing them use format v8; ordinary batches continue to use v7. New readers accept existing v2–v7 journal records. Upgrade every replica, coordinator, and backup/restore reader before creating explicit relationships or enabling nodes.source. An older reader cannot interpret the new relationship keys, so downgrade requires removing the new projections and rebuilding compatible indexes and replay state. Relationship IDs remain scoped identities rather than globally unique UUIDs. Data-Raft admission rejects document and relationship writes until every applying replica supports protocol version 21, before catalog-dependent graph effects are extracted. HA replay independently requires batch envelope version 20 for these graph apply effects, including document-derived relationships; older standbys reject the envelope before applying any rows. The envelope preserves each control’s original schema and exact Raft receipts.

Portable backups preserve each explicit relationship’s owner, logical endpoints, ID, weight, timestamps, and metadata in a dedicated relationship block. Such archives require AFB reader version 6 or later; older readers reject them before import. Backups containing only implicit relationships retain the legacy edge blocks and reader version 2 requirement. Archives containing durable endpoint retirements require reader version 7. Explicit relationships use derived journal version 8 and data-Raft protocol version 21; existing owner and TTL journals remain readable.

Readiness Is Two Flags, Not One#

Creation starts materialization and replay; it does not mean coverage is complete. Poll GET /db/v1/tables/{table}/indexes/{index}:

  • readiness.queryable is the serving authority: the index can answer queries.
  • readiness.complete is convergence at the captured target revision: required source production and index publication have completed according to the configured policies. It is not a promise about future writes.
  • readiness.pending_reasons gives typed aggregate blockers or failure reasons.
  • readiness.sources lists each artifact stream in configuration order with its state, completeness, and typed blockers, so document-vector lag and chunk-vector lag show up separately.

Every index kind also reports a catalog-assigned incarnation, at the status root and inside readiness. A waiter succeeds only on a runtime observation of that same definition, so dropping and recreating an index under the same name cannot reuse stale readiness or searchable counts.

The document-level coverage object belongs to embedding indexes. Full-text and graph indexes report completion through readiness, including readiness.sources for artifact-backed projections, and replay status. They do not publish embedding producer counters: an absent counter cannot distinguish unfinished extraction from an intentional empty output. Source extraction failures remain visible in source readiness and repair status, including after restart.

Artifact source readiness also waits for verified completion of that source's producer dependencies. A caught-up replay cursor cannot mark unfinished OCR, transcription, chunking, or relation extraction complete before its output is published. Producer work uses durable, revision-fenced summaries; status polling does not scan documents. Each source is checked independently, so relation extraction debt does not block a text stream that has finished. Intentional empty outputs can complete; extraction failures remain unhealthy.

Existing stores establish these summaries through bounded background discovery and verification of retained artifacts. Local producers use the durable paged source-recovery owner and retain the published generation once its receipts and native checkpoint agree. Until discovery finishes, producer-backed sources remain pending. Restart, source edits, and catalog changes retain or reopen the appropriate completion fences. Known terminal failures remain with their repair/retry owner rather than being regenerated on every open.

Full-text indexes remain queryable while extraction is incomplete or replay is catching up, provided the current runtime observation and physical checkpoint are valid. Failed OCR is a source-coverage problem; a missing runtime, stale or mismatched shard observation, blocked physical checkpoint, or serving failure is a queryability problem. Equal replay watermarks alone do not prove complete OCR.

target_revision and published_revision describe the captured consumer replay observation. Producer completion also depends on its own durable revision fences; these sequence domains are not interchangeable. A later write may reopen completion without invalidating an existing retained query snapshot. Status observations are not certificates of extraction coverage for an arbitrary query snapshot.

Hierarchy member navigation enumerates published logical members in the retained store even when a different source is incomplete. An empty member page is not a producer-completion certificate. Selected immutable chunk heads still shadow legacy rows and unpublished tails; staging data is not exposed as a logical member. Parent authorization, retention, cursor validation and cancellation checks continue to apply.

Antfly-grep searches available artifact content when the index is queryable. It retains the query snapshot across pages and checks the artifact binding before and after scanning. Incomplete source coverage emits a coverage JSON event with the observed incarnation and replay revisions, plus a human-readable warning. The summary separates scan_complete from coverage_complete; complete is their conjunction, and incomplete coverage exits 2 even when matches were found. A changed observation during the scan also prevents a complete-coverage claim; ordinary revision progress does not invalidate the retained scan. Definition changes and query failures still invalidate the scan. --require-complete rejects known gaps before searching and requires stable, complete observations through the scan. This is an operational observation check, not a snapshot-bound coverage certificate. It does not wait for a permanently idle table.

A document that exhausts its extraction retries remains in the artifact repair queue. Other documents can continue to publish, and default grep reports the coverage gap while searching published text. Use the artifact repair queue to inspect and retry failed work. A failure that blocks the pipeline itself can also prevent Antfly from opening a consistent snapshot. In that case grep reports a query error, and an empty result carries no no-match guarantee.

After a quiet-mode match, grep stops fetching content but checks readiness for remaining selected artifact streams within the request budget. A gap or unknown readiness still exits 2; cancellation stops further checks.

Successful artifact grep scans also emit a coverage JSON observation with complete: true, the table/index/field, incarnation, and target/published revisions, including when there are no matches. This qualifies the observation behind the summary boolean; it does not turn the observation into a snapshot-bound extraction certificate.

Internal replay watermarks are diagnostics only.

Changing source membership, projection fields, analyzer semantics, embedding space, or graph mapping changes what the index means and requires a new materialized generation. Execution batching fields tune work without changing artifact identity.

Canonical, Alternative, and Compatibility Forms#

sources is the canonical multi-source API. Three one-source alternatives are supported and not deprecated: full-text artifact_name, embeddings embedding_name, and graph source. Normalized responses expose canonical sources where the released contract requires it.

The released v0.2 embeddings fields remain supported for v0.2 compatibility, with no removal release scheduled. source_artifact_name is descriptive when paired with embedding_name; the matching enrichment is authoritative. Internal graph manifest and edge materialization fields are engine-owned, not alternate public APIs. No graph status aliases were released, and the released Go v0.2 SDK surface (go/pkg/sdk/v0.2.0) creates no additional compatibility obligation.

Use Agent Skills#

Everything above is also encoded in the Antfly skill, so a coding agent can execute this guide for you:

npx skills add antflydb/antfly-skills

Then prompt it with the outcome, for example "Create an artifact-backed embeddings index over my docs table that unions document-level and chunk-level vectors", and use this page to judge the result.

Producer changes, freshness, and model upgrades#

A named producer definition selects how subsequent work executes. Replacing its model or revision does not, by itself, request table-wide reprocessing of every existing descendant artifact. A metadata-only document update can reuse an embedding when its effective input, producer configuration, resolved revision, and reprocess generation still match. This reuse also applies to synchronous enrichments and full_index writes.

For an in-place producer upgrade, replace the producer with an immutable model revision and explicitly request table-wide reprocessing with POST /db/v1/tables/{table}/artifacts/{artifact}/reprocess. Follow the returned continuations until reprocess_status is complete; inspect failures and the consumer index's readiness before using the new space. A successful request that starts a bounded pass is not proof that the whole table has migrated. Source updates, deletions, and producer generations fence delayed work at publication, so a late response must pass the current source and producer guards. Each explicit embedding reprocess advances a document/producer epoch that is never reset by model configuration changes or rollbacks. The epoch is checked in the transaction that publishes a vector; unchanged source bytes and an identical model revision do not make an old A completion part of a later A reprocess generation. Synchronous repair retries also bind computed work to the target captured before inference. A changed producer definition fences older completions even when the source bytes and model revision stay the same. Cleanup and coverage updates carry the same source and reprocess guards, so obsolete work cannot retire a newer vector or credit that work as ready.

publication_policy: "atomic" controls validation and activation of a new index generation. It does not make arbitrary producer mapping edits a transaction across every document or shard. To keep a serving application on one model space throughout an upgrade, create a separately named producer, artifact, and index for the new revision and wait for that index's readiness. A table-scoped index alias lets native HTTP queries name a stable target while the database selects the concrete index and its query embedder together:

PUT /db/v1/tables/docs/index-aliases/chunk_vectors
Content-Type: application/json

{
  "index": "chunk_vectors_gemma2",
  "expected_index": "chunk_vectors_bge",
  "require": "complete",
  "idempotency_key": "upgrade-gemma2-2026-11-14"
}

Create an alias by omitting expected_index; replace it by supplying its exact current target. require defaults to complete; queryable also permits the existing partial-serving readiness state. A swap rejects an unready target, a different index kind, or a dense/sparse mismatch. Alias names cannot shadow concrete indexes, refer to another alias, or use reserved metadata names.

Artifact-backed indexes pin their entire producer dependency chain. Changing an embedding model or an upstream enrichment requires rebuilding its dependent physical indexes under new incarnations. Remove retired consumers before changing their producers, even after moving an alias: an earlier query may still hold the retired consumer's incarnation fence. Credential and pacing changes that preserve the producer's stable semantic identity remain allowed. Graph definitions are validated after resolving alias names; swaps that would map overlapping relationships to the same physical edge index are rejected.

Use the alias in full_text_index, indexes, embedding map keys, canonical graph_queries index fields, or graph metric requests. Resolution happens before embedding and shard dispatch. Native requests carry the selected index incarnation into storage admission; a retired target that is reconfigured or recreated cannot serve an older model’s query vector. Such a query fails with a catalog conflict and can be retried as a new query. Native query results include resolved_indexes with the concrete names used. Filters, documents, and prompts are never rewritten. GET /db/v1/tables/docs/index-aliases/chunk_vectors returns the current and previous targets, swap timestamp, and the recorded readiness proof. Mutations require table administration permission; reads require table read permission. The database/namespace-qualified table routes support the same operations. Finish upgrading metadata and data nodes before enabling aliases in a distributed cluster. Admission checks peer capabilities, and the replicated catalog rejects older data-store registrations once aliases are present.

Retry an ambiguous mutation with the identical body and idempotency key. The recorded response is returned even after another swap or rollback; a retry does not reactivate its original target. Receipts are retained for at least 24 hours, with at most 128 retained receipts per alias, 64 aliases per table, and a 512 KiB table-wide budget for alias resources and retry receipts. Each mutation reclaims expired receipts across the table. Admission returns a conflict if that window is full, rather than evicting a receipt that a caller may still need. Do not reuse keys for new operations. Read the alias to inspect the live target independently of an older operation's receipt.

Keep the old resources for rollback. Swap back with a new idempotency key and the current target as expected_index. Deleting or changing the configuration of a currently referenced concrete index is rejected. Alias state and receipts are part of the table catalog and travel with its existing persistence and replication paths.

SQL graph mappings may name an alias: each execution binds a copy of the mapping to the concrete graph index and its incarnation from the statement's catalog cut. SQL HTTP and Cypher responses also report resolved_indexes. Fixed mappings continue to pin their original incarnations. SQL SEARCH hosts that supply a table catalog use the same structural binding. Embedded alias management is not exposed by the C ABI; embedded applications must continue using concrete index names. Schema-owned relational indexes are not alias targets yet; alias mutations naming one return HTTP 501.

An asynchronous source write can be acknowledged while its previous published vector is still queryable. Aggregate coverage.complete describes processing progress; it is not a promise that each result reflects the latest acknowledged source version. Use sync_level: "full_index" when the write response must wait for indexed visibility. sync_level: "enrichments" already supports computing configured enrichments before the source commits and rejecting the write if a synchronous producer fails; it does not wait for every index to publish.

An unpinned provider alias can change its model behind an unchanged endpoint. Antfly cannot infer a common vector space from an alias or matching dimensions. Use an immutable provider revision and, where supported by the provider, an explicit model_identity pin that can be verified against its response. Changing an alias without an enforceable revision is not a fenced model upgrade.

Keep an enrichment current with data from another table#

A support ticket summary can use both the ticket body and the customer's current plan. Declare the customer record as a live context_sources entry. When the plan changes, Antfly queues the affected summaries for regeneration.

Run this example against an Antfly HTTP server with OPENAI_API_KEY set in the server's environment. The requests assume local development with authentication disabled. If your server requires authentication, include credentials with permission to create, write, and read both tables.

Create the tables and register the enrichment#

api=http://127.0.0.1:8080/db/v1

curl -fsS "$api/tables/context_customers" --json '{"num_shards":1}'
curl -fsS "$api/tables/context_tickets" --json '{"num_shards":1}'

curl -fsS "$api/tables/context_customers/batch" --json '{
  "inserts": {"acme": {"plan": "Standard"}},
  "sync_level": "write"
}'

curl -fsS -X PUT "$api/tables/context_tickets/artifacts/summary/enrichment" --json '{
  "kind": "asset",
  "field": "body",
  "content_type": "application/json",
  "producer": {
    "type": "generator",
    "config": {
      "generator": {"provider": "openai", "model": "gpt-4.1"},
      "output": "auto",
      "output_schema": {
        "type": "object",
        "properties": {"summary": {"type": "string"}},
        "required": ["summary"],
        "additionalProperties": false
      }
    }
  },
  "context_sources": {
    "customer": {
      "document": {"table": "context_customers", "key_from": "/customer_id"},
      "fields": ["plan"],
      "required": true,
      "tracking": "live"
    }
  }
}'

key_from is a JSON Pointer into each ticket. It supplies the customer document key. The generator receives the ticket body and the customer's plan field. The registration response reports customer as a live document source.

Write a ticket and check its dependencies#

curl -fsS "$api/tables/context_tickets/batch" --json '{
  "inserts": {
    "ticket-1": {
      "customer_id": "acme",
      "body": "Summarize this ticket and include the customer plan from context. The customer cannot export a report."
    }
  },
  "sync_level": "write"
}'

ticket="$api/tables/context_tickets/documents/ticket-1"
deps="$ticket/artifacts/summary/dependencies"
current="$deps?freshness=require_current&wait_timeout_ms=30000"

curl --fail-with-body -sS -i "$current" &&
  curl -fsS "$ticket?fields=_artifacts.summary"

The dependency endpoint reports the source, freshness, and retained lineage. When the first request returns HTTP 200 with current: true, the document read shows the generated value under _artifacts.summary.value. If the dependency request returns HTTP 409 with artifact_not_current, retry it before reading the generated value.

Update the customer and wait for the rebuilt summary#

curl -fsS "$api/tables/context_customers/batch" --json '{
  "inserts": {"acme": {"plan": "Premium"}},
  "sync_level": "write"
}'

curl -fsS "$deps"
curl --fail-with-body -sS -i "$current" &&
  curl -fsS "$ticket?fields=_artifacts.summary"

The customer write can return while Antfly is still rebuilding the summary. The plain dependency request shows the available freshness and lineage immediately. Wait for current: true from the second request before comparing the new summary and lineage with the first version.

Use live document lookups or supported filters when changes should trigger rebuilds. Ranked search, SQL, and Cypher context sources use snapshots and report unverified. Refresh those on a schedule or on demand.

Next Steps#

Private GCS source artifacts#

Native document extraction can fetch gs:// sources through the same named external-I/O connections used by object storage. Grant content.fetch explicitly; objects.read alone does not authorize artifact downloads. For example:

{
  "connections": {
    "source-pdfs": {
      "kind": "external_io",
      "capabilities": ["content.fetch"],
      "external_io": {
        "protocol": "gcs",
        "buckets": ["private-originals"],
        "prefix": "objects/sha256",
        "credentials": {"source": "default"}
      }
    }
  }
}

Here default uses Google application default credentials, including GKE Workload Identity. The selected workload needs read permission on the bucket. Keep credential values in the server keystore, never in source documents. Set the document-extraction producer's config.credentials to source-pdfs. When omitted, Antfly selects the most specific matching connection; equally specific matches fail closed and require an explicit name. URLs outside the bucket/prefix scope fail before credential discovery.

Store an immutable source URL such as gs://private-originals/objects/sha256/CONTENT_HASH.pdf?generation=1793305553268935. The generation is sent to Google's JSON API and verified on the response. An unavailable or mismatched generation fails rather than falling back to latest. Only the optional generation query parameter is accepted, never URL credentials or signed query strings. Fetches retain the configured download byte, deadline, cancellation and destination restrictions. A bare gs:// URL without an applicable configured connection never opts into ambient Google credentials.

Cloud uses this same runtime configuration: configure a read-only instance GCS provider connection and bind its verified Workload Identity principal to the source bucket. Self-hosted deployments configure connections directly. This artifact transport requires a release containing native GCS content fetching; GCS external-I/O support in v0.3.0-rc.6 alone is insufficient.

Raise an OCR budget without regenerating complete files#

An output budget belongs under execution, not in a replacement OCR recipe. For an existing artifact, retain its public descriptor fields and omit the write-only producer fields so Antfly preserves the stored recipe and credentials. An explicit transcriber, producer, or producer_json replaces the producer; only omission inherits it:

PUT /db/v1/tables/documents/artifacts/document_units_v1/enrichment
Content-Type: application/json

{
  "name": "document_units_v1",
  "kind": "asset",
  "field": "url",
  "content_type": "application/json",
  "execution": {"max_output_tokens_per_item": 8192}
}

This changes future invocations. It preserves complete existing artifacts, including output longer than a subsequently lowered budget. The node/provider's request limits still apply. Do not remove max_tokens from the old stored producer while applying this update: changing the recipe changes its identity.

To retry only missing or incomplete document-extraction artifacts, submit a bounded job with an explicit selection:

POST /db/v1/tables/documents/artifacts/document_units_v1/reprocess-jobs
Content-Type: application/json

{"selection":"incomplete","limit":25,"advance":false}

Advance and inspect the returned job using its existing job routes. Complete artifacts are skipped; converged manifests with failed OCR pages are incomplete. The selection survives pagination and job recovery. Selection is per source record, so pages within an incomplete multi-page record may be processed again. Use selection: all only when regeneration of accepted output is intended. Omitting selection retains that existing all behavior. Other producer kinds reject incomplete selection. Upgrade the coordinator and data owners before using this field; older owners must not silently interpret it as all.

Acceptance is not completion: inspect manifests and all consumer-index readiness before declaring recovery successful. Model, prompt, rendering and extraction policy changes can invalidate existing results. Chunking, embeddings and graph changes rebuild their downstream artifacts while reusing extracted text.

Policy-only updates are persisted separately from the frozen publication catalog, so they preserve accepted publication proofs as well as extraction fingerprints. Incomplete-only retries inspect coverage and generation from one manifest snapshot. Changing a model, prompt or source recipe still changes semantic identity.