Quick start
context_entity_versions (one version row), context_entity_heads (one head row), context_entity_fragments (one preview + N section rows), context_entity_refs (one row per [[e:id]] / [[e:entity_key]] and per source: entry), context_commits (one commit row tagging the whole upsert with a fresh snapshot_version).
Markdown references
[[e:<X>]] is the inline reference syntax for citing another entity from a markdown body. <X> is accepted in two shapes; both produce the same context_entity_refs row after resolution:
The same union applies to YAML frontmatter ref lists (
source:, source_pages:, refs:, links:, references:). Scalar, inline-list, and block-list forms all accept either shape, and a single list may mix them:
'foo' / "foo") are unwrapped before classification.
Strict resolution
If any[[e:<key>]] cannot be resolved to a live entity in the same contextbase, the entire UPSERT is rejected with ENTITY_NOT_FOUND — nothing is persisted. This applies to both:
- Forward references: writing entity A that cites B by key, where B does not yet exist. Bulk imports must order rows so leaves are written before citing entities, or use
CONTEXT UPSERT INTO ... BULK(one batched lookup covers the whole batch, so intra-batch forward references resolve via Phase 3 allocation — A cites B and B is row N+1, both succeed). - Tombstoned targets: a soft-deleted entity does not resolve. Reviving its
entity_keyvia UPSERT before citing it is the supported recovery path.
Banned: digit-only entity_key
An entity_key that matches ^\d+$ (e.g. "12345") is rejected at write time with INVALID_ENTITY_KEY. Without this constraint, [[e:12345]] would be ambiguous (numeric id vs digit-only key) — the extractor always picks the numeric branch first, so a digit-only key could never be cited from markdown anyway. Allowed shapes start with a letter or _ and may contain [A-Za-z0-9_./:-]:
When you want explicit (key-based) edges that bypass markdown
The SQLEDGES (...) clause accepts either bigint literals or string literals; the latter goes through the same entity_key resolution path as inline markdown refs. Use this when the citing entity’s body is empty / non-markdown but you still want graph edges:
EDGES rows land with ref_kind = 'explicit' instead of 'inline'; both kinds participate in graph_expand by default.
Object model
CollectionTypePolicy. See the table in the architecture doc §4.2; the analyzer rejects illegal combinations at CONTEXT UPSERT time.
Internal tables
The module persists everything in eight Primary Key tables under the hidden database__internal_context. You don’t need to read them directly — every supported user surface (DDL/DML, SHOW, TVF, REST) goes through them — but operators do query them for forensic / observability work.
Authorization
Two layers of access control. Both are enforced by the analyzer / REST handlers — there is no way to call a write or admin endpoint without passing them. System-level privilege — required for every CREATE / ALTER / DROP / write entry point:CREATE/ALTER/DROP CONTEXTBASE, CREATE/DROP CONTEXT COLLECTION, CREATE/DROP WORKSPACE, CREATE/DROP RETRIEVAL PROFILE, CONTEXT UPSERT, CONTEXT DELETE, WORKSPACE UPSERT, and the matching REST endpoints. The built-in roles OPERATE and SECURITY continue to bypass it.
Per-base ownership / grants — CREATE CONTEXTBASE stamps _owner_user into the metadata. From then on ALTER, DROP, and any write inside the base require either ownership or a per-base grant. The grant grammar:
/api/context/health, cluster-wide /api/context/stats) require system-level CREATE CONTEXTBASE — these surface counts across every base in the deployment, so they’re admin-gated.
SQL surface
DDL
DML
The REST layer also exposes filesystem-style CRUD semantics on top of the same storage model:
POST /api/context/getacceptsfields,options = "-L...",options = "--history",version, andas_of_time.-Lselectors count body lines only and return the sliced body payload.POST /api/context/upsertaccepts either a fullentitypayload or an existingid/entity_keypluswrite_options(-a,-L10-20,-L15i) for body-only append / line replace / insert-before-line updates.POST /api/context/deleteacceptshard_delete=truefor physical purge; the default soft-delete path preserves body/raw markdown/frontmatter/source and only deprecates the current version withconfidence = 0.0.
SHOW
Table functions (TVF)
The module ships nine SQL-callable table functions. Use them anywhere a relation is allowed:ContextGet operator stays a schema-only fallback. Common named args (scope, contextbase, collection, collections, collection_type, as_of_time, snapshot_version) are accepted everywhere a scope is meaningful.
Read TVFs
read_collection and read_contextbase rewrite to a SubqueryRelation against __internal_context.context_entity_heads JOIN context_entity_versions, so result rows scan natively on BE rather than materializing through FE heap.
Search TVFs
Graph / pack TVFs
REST surface
The REST layer mirrors the SQL surface and adds batch + retrieval operations that don’t have SQL counterparts today. Metadata changes and data writes run on the leader. This applies to Context Base creation/deletion, collection/workspace/retrieval-profile creation, workspace start/discard, and theupsert, update-metadata, delete, bulk-import, bulk-delete, and workspace upsert endpoints. A non-leader FE returns HTTP 307 Temporary Redirect with the leader URL in Location, preserving the escaped path and query parameters. Native HTTPS requests redirect to HTTPS on https_port; all FEs must enable HTTPS and use the same HTTPS port. Resend the same method and body to that URL with authentication, or address the leader directly. Read and search endpoints continue to use the receiving FE.
Management
POST /api/contextbases— body{"name": "...", "properties": {...}}GET /api/contextbases— returnscollection_count,entity_count,updated_time,statusDELETE /api/contextbases/{name}[?if_exists=true]POST /api/collections— body{"contextbase": "...", "name": "...", "collection_type": "knowledge", "properties": {...}}GET /api/collections[?contextbase=<name>&collection_type=<type>]— returnsentity_count,updated_time,statusPOST /api/workspacesGET /api/workspaces[?contextbase=<name>]— lists workspaces withmemory/scratch/outputcounts andlast_activityPOST /api/retrieval-profilesGET /api/context/health— operator-only readiness probe (is_leader,internal_tables_ready, four metadata counts, four internal-table row counts). Returns 200 even on partial readiness so dashboards can render the shape rather than a binary up/down.GET /api/context/stats[?contextbase=<name>]— capacity metrics. Per-base form is callable by anyone holdingUSAGEon the base; cluster-wide form (no query string) is admin-only. Returns-1for any underlying table that hasn’t materialized yet so dashboards render “n/a” instead of erroring.
Workspace lifecycle
Workspaces are short-lived per-session scratch areas under a collection. The lifecycle endpoints model a deliberate start → commit/discard flow;POST /api/workspaces is the legacy direct-create path.
POST /api/workspaces/start— body{"qualified_name": "<cb.col.ws>", "collection_id": <id>, "properties": {...}}. Idempotent: an existing workspace resumes (returns its id,resumed=true); a missing one is created. Response also returnsmemory/scratch/outputcounts andlast_activityso the agent can decide whether to keep working in the resumed state.POST /api/workspaces/commit— body{"qualified_name": "<cb.col.ws>", "target_collection": "..."}. Promotes every non-tombstoned workspace object into the target collection. The endpoint enqueues aWORKSPACE_COMMITbackground task and returns its task id; pollSHOW CONTEXT TASKSfor completion.POST /api/workspaces/discard— body{"qualified_name": "<cb.col.ws>"}. Tombstones every active object in the workspace then drops the workspace metadata. Shared collections are unaffected. Not reversible.
Data
POST /api/context/upsert— single-row upsert, or write-style update byid/entity_keyPOST /api/context/bulk-import— batch upsert; per-row success/failure isolation. The whole batch commits under a singlesnapshot_version(onecontext_commitsrow), so an as-of read either sees the entire batch or none of it; every per-row result reports that samesnapshot_version.POST /api/context/delete— soft delete by default;hard_delete=truefor physical purgePOST /api/context/bulk-delete— batch soft-delete. Body{"selectors": [{"id": 301}, {"entity_key": "smb_baseline"}, ...]}. Each row is independently tombstoned; selectors carrying justentity_keyare resolved toid, and rows that fail resolution surface in the response with a per-row error rather than aborting the batch.POST /api/context/get— body{"id": 123}or{"entity_key": "..."}or{"id": 123, "version": 5}; also supportsas_of_time,fields,options, andlevelPOST /api/context/history— all versions of an entity (equivalent tooptions="--history"on/api/context/get)POST /api/context/read-collection— full collection dump (body, raw markdown, frontmatter, source, timestamps, confidence, vector state), optionalas_of_time. Paginates bylimitplus eitheroffsetorafter_entity_id(cursor). See Pagination below.POST /api/context/read-contextbase— full contextbase dump with the same entity payload, optionalas_of_time. Same pagination contract asread-collection.POST /api/workspace/upsert— acceptsworkspace_scope = memory|scratch|output
Disclosure level
POST /api/context/get and the context_get TVF accept a level parameter that controls how much per-entity payload is returned:
Pagination
POST /api/context/read-collection and POST /api/context/read-contextbase page over their result set ordered by entity_id ASC (allocated monotonically and uniquely by the FE — total order, stable tiebreak in a distributed plan). Two pagination primitives are exposed:
Response carries
next_after_entity_id — the last row’s entity_id, or null when the page returned fewer than limit rows (end-of-scan). Drive cursor loops from this field:
LIMIT N OFFSET M requires the coordinator BE to merge-sort the first M + N rows in order before discarding the first M. Cost grows linearly with offset, and the sort key must be a unique total order or different replicas will resolve ties differently on retries (the very bug that drove next_after_entity_id to exist). Keyset cursors on the PK avoid both costs: a WHERE entity_id > $cursor predicate is pushed to the OlapScan with a LIMIT N early-stop, and concurrent upserts cannot shift the cursor because new ids are always allocated past it.
Retrieval
POST /api/context/search— text + vector + reference fusion with explain output; acceptsscope,collections,collection_type,workspace,retrieval_profile,consistency, andas_of_time.max_tokensnow drives a budget-aware packed view (packed_text,used_tokens_estimate,included_entities,truncated_entities,disclosure_levels).POST /api/context/graph-expand— bounded BFS over references (compatibility name forGRAPH_EXPAND); acceptsscope,collections, orcollection_typePOST /api/context/pack— token-budgeted packingPOST /api/context/text-search— entity-level text hits with real grep-style-A/-B/-C/-n/-i/-c/-lsnippet behaviorPOST /api/context/vector-search— standalone semantic vector retrieval over preview embeddings by default and section embeddings withoptions="-d"; the FE materializer is the user-facing execution path, while the BE TVF remains schema-compatible fallback only
Search explain output
POST /api/context/search returns a explain object alongside candidates. Fields:
Graph fusion: auto-derived seeds
CONTEXT_SEARCH does not require the caller to supply seed_ids. With graph_mode=AUTO (default), the top text/vector candidates are picked as graph seeds by partial fusion score, then fed to the reference-expansion path. This is what makes the graph_weight actually contribute when the caller only has a query string.
graph_mode=AUTO(default) — derive seeds from text/vector top-K (union with explicitseed_idsif any) and run reference expansion. If the seed set is empty (no hits, no explicit seeds), the path is skipped silently andgraph_status="skipped_no_seeds"is reported.graph_mode=OFF— skip reference expansion;graph_score=0for every candidate.graph_seed_topk(optional, defaultmin(max_results, 10)) — caps how many text/vector candidates seed the expansion. Smaller values keep the frontier bounded; larger values are useful for programmatic profiling.direction(optional, defaultBOTH) — reference-expansion BFS direction, one ofFORWARD,BACKWARD,BOTH. Edges are stored assrc=document → dst=referenced entity, so two documents that share a referenced entity (doc1 → entityX ← doc2) are only mutually reachable withBOTH;FORWARD-only expansion strands the second document and makesgraph_weightcontribute ~0. The default is controlled by thecontext_search_default_graph_directionFE config; setdirection=FORWARDto restore the legacy single-direction behavior.BOTHroughly doubles per-hop expansion work and may hitmax_frontiertruncation sooner.seed_ids(optional) — power-user override that composes (union, dedup) with auto-derived seeds. Most callers do not need to set this.
CONTEXT_GRAPH_EXPAND TVF / POST /api/context/graph-expand endpoint. It accepts require_complete=true for strict callers that want truncation to surface as an error.
Note:graph_mode=REQUIREDwas removed when fusion gained auto-seed-derivation — it is rejected withINVALID_ARGUMENT. Use thegraph_expandendpoint withrequire_complete=truefor strict semantics instead.
Synthesis demotion (derived_page and friends)
Synthesis entities — currently only derived_page — are aggregations of multiple leaf entities. Their preview/title text-matches the query well, vector embeddings of the synthesis match well, and they’re hubs in the reference graph, so a naive linear fusion places them above the leaf evidence agents actually need to ground answers. Three layered defenses, all routed through CollectionTypePolicy.isSynthesisType():
- Seed filter. A synthesis entity is never picked as a graph-expansion seed: it would just walk back to leaves we already discovered and inflate its own
graph_scorefrom converging inbound paths. The number of seeds filtered this way is reported inexplain.synthesis_filtered_seeds. - Graph score discount. A synthesis entity’s
graph_scoreis multiplied by0.5before entering the linear fusion sum, breaking the correlation between the three retrieval signals for hub entities. (SYNTHESIS_GRAPH_SCORE_FACTOR) - Final score discount. A synthesis entity’s
final_scoreis multiplied by0.9after fusion — leaf-first tiebreak when scores are close. (SYNTHESIS_FINAL_SCORE_FACTOR) - Budget upgrade order. When packing the response into
max_tokens, leaves are upgraded from PREVIEW to STANDARD/DEEP first; synthesis entities are upgraded only with the leftover budget. This guarantees that any synthesis included inpacked_textis accompanied by enough leaf evidence for the agent to ground its citations.
Channel
The channel surface is a pattern-aware multi-agent message bus on top of the same Primary Key store. Subscriptions live in__internal_context.context_channel_subscriptions (PK subscription_id) and survive leader failover.
POST /api/context/subscribe/POST /api/context/unsubscribe— body{"subscriber": "...", "pattern": "<glob>"}. Patterns are case-sensitive globs —*and?match single segments,**crosses segments. A subscriber can hold many patterns; duplicates are coalesced.POST /api/channel/send— body{"channel": "<cb.col>", "key": "...", "payload": "..."}. Wakes any leader-local pullers blocked on a matching pattern.POST /api/channel/pull— body{"channel": "...", "subscriber": "...", "since_id": <opt>, "wait_timeout_ms": <opt>}. The optionalsubscriberroutes delivery through the stored subscriptions; omitting it preserves raw collection polling.wait_timeout_msenables leader-local long polling so a sender wakes waiting pullers without a separate WebSocket/SSE service.
Worked example: search + pack
as-of time travel
Every commit is stamped with a monotonicsnapshot_version.
- Point reads (
/api/context/get) treatas_of_timeas an entity-history selector and resolve the latest version whoseupdated_time <= as_of_time. - Collection/contextbase/search/graph/vector/text reads still pin a single snapshot fence so cross-entity reads stay mutually consistent.
as_of_time accepts YYYY-MM-DD, YYYY-MM-DD HH:mm:ss, or a raw snapshot number on snapshot-based surfaces.
Error responses
Every REST endpoint that fails inside the module returns a structured envelope so SDK clients can build retry/backoff without scraping free-form text:
The TVF surface raises the same errors as
SemanticException / ContextException and surfaces them through the SQL layer.
Observability
- Metrics (all registered in
MetricRepo, Prometheus-scraped):context_upsert_total,context_delete_total,context_get_totalcontext_search_total,context_graph_expand_total,context_pack_total,context_text_search_total,context_vector_search_totalcontext_channel_send_total,context_channel_pull_total,context_workspace_upsert_total
- Audit log: every
CONTEXT UPSERT/DELETEandCONTEXT_SEARCHemits aninternal.baseaudit line with request-id, scope, and key parameters.
Prerequisites
The internal-context fragments table carries an inline GIN inverted index onfragment_text and a vector index on embedding. Vector indexes are always available, while the GIN index requires the experimental FE config enable_experimental_gin, which defaults to false. If this flag is disabled, the bootstrap daemon creates the __internal_context database but skips all fragment/index tables — CONTEXT UPSERT then silently drops fragments and every search returns zero hits. To recover, set enable_experimental_gin to true (ADMIN SET FRONTEND CONFIG is picked up within one 60s daemon tick, no FE restart needed) and add it to fe.conf so the setting survives a restart.
Embedding provider configuration
Embedding provider settings (endpoint, model, dimensions, timeout, api_key) are SQL-managed objects, persisted on the FE metadata journal / image — they are not FE configs. Manage them viaCREATE / ALTER / DROP / SHOW / DESC / SET DEFAULT EMBEDDING PROVIDER. Every CONTEXT write path resolves the current DEFAULT EMBEDDING PROVIDER at request time; if none is set, CONTEXT UPSERT and vector_search over query_text fail with VECTOR_NOT_READY.
Example bootstrap (admin only — SYSTEM-level OPERATE privilege):
fe.conf (or are mutable via ADMIN SET FRONTEND CONFIG):
Limitations and roadmap
- Execution ownership: supported SQL TVFs are now materialized in FE through the same semantic-context services the REST surface uses. The BE
ContextGetoperator remains a schema-compatible fallback stub for introspection and future native operators; it is not the user-facing execution path. - Vector search: standalone
/api/context/vector-searchand fusedCONTEXT_SEARCHboth execute the real vector path. Whenquery_embeddingis supplied, the query runs even without a configured embedding provider; when onlyquery_textis supplied, a configured provider is still required. - Inverted-index pushdown: text search pushes down to the GIN index for single-token
MATCHqueries; multi-token / wildcard patterns still fall back toLIKEscans to preserve semantics. - Real embedding provider: register one via
CREATE EMBEDDING PROVIDER ...andSET <name> AS DEFAULT EMBEDDING PROVIDER(see “Embedding provider configuration” above). Without a default provider,CONTEXT UPSERTfails per-row because the writer requires a real embedding for the fragments INSERT, andvector_searchoverquery_textcannot produce fresh query embeddings. Point the endpoint at any OpenAI-compatible/v1/embeddingsservice;dimensionsin the provider must matchcontext_vector_index_dim.
Embedding compute on BE
Per-row embedding compute runs on the BE side via the scalar functionembedding(text VARCHAR, config JSON) -> ARRAY<FLOAT>. Bulk inserts and SQL-driven query embeddings parallelize across all BE nodes; the FE leader is no longer a serial bottleneck. The function takes the same OpenAI-compatible /v1/embeddings shape as the FE provider:
config argument is optional. When it is omitted, the FE resolves the current DEFAULT EMBEDDING PROVIDER and injects its config automatically, so a single-argument call is enough once a default provider exists:
DEFAULT EMBEDDING PROVIDER is set, the single-argument form fails analysis with a message pointing at CREATE EMBEDDING PROVIDER / SET <name> AS DEFAULT EMBEDDING PROVIDER. Pass an explicit config to embed against a non-default provider.
Internal callers (ContextWriteExecutor, VectorSearchExecutor) materialize the same shape from the current DEFAULT EMBEDDING PROVIDER — api_key is omitted entirely when the provider has none (local / self-hosted endpoints that don’t require an Authorization header).
API key handling
The API key value lives in FE metadata (journal + image) and is inlined into the BEembedding(text, config_json) call site:
- Manage provider credentials via
CREATE / ALTER EMBEDDING PROVIDER— theapi_keyproperty travels with the provider object and is persisted on the FE meta journal and image so cluster restarts and upgrades retain the credential. SHOW EMBEDDING PROVIDERSandDESC EMBEDDING PROVIDERmask the key as******. The plaintext is only read internally byEmbeddingConfigJson/FeEmbeddingClientwhen building the config JSON for the BE-sideembedding(...)call.- The audit-log redactor (
SqlCredentialRedactor) masks any literal"api_key":"<value>"it sees in SQL strings. - All
EMBEDDING PROVIDERDDL (includingSHOW/DESC) requires SYSTEM-levelOPERATEprivilege. - Anyone with read access to the FE meta image / BDB journal directory can read provider
api_keyvalues. Protect those files with filesystem permissions.
DEFAULT EMBEDDING PROVIDER is set, every write path that needs an embedding fails fast with VECTOR_NOT_READY.
The config JSON is parsed by the same ModelConfig helper that backs the generic ai_query(text VARCHAR, config JSON) -> VARCHAR LLM scalar (opcode 200000, registered alongside embedding at 200001). That means temperature, max_tokens, and top_p are accepted in the JSON but ignored on the embedding path — paste-as-is from an ai_query config will work, but those fields don’t influence /v1/embeddings requests.