Knotrel External Source-of-Truth Integration Contract
Document Status: Implemented contract. Written as the v0.2.0 design (Feature 0.2.1), approved and implemented in v0.2.x, extended through v0.9.x; normative for v1.0 together with openapi.yaml, which is the wire contract
Milestone: v0.2.0 — Integration & Graph Loading (Feature 0.2.1); maintained since
License: Elastic License 2.0
Target Platform: Rust 1.100.0, Edition 2024 (core MSRV: Rust 1.98.1)
Implementation Notice: Every route, schema, header and protocol message in sections 2–10 is implemented. Sections 11–14 keep the original design record (test traces, decisions D1–D6, handoff and approval checklist) for traceability; where their wording differs, sections 2–10, openapi.yaml and the code prevail.
1. Purpose and Non-Goals
1.1 Purpose
Knotrel is an in-memory dynamic connectivity accelerator for undirected graphs. An external system (such as an authoritative transactional database, an event stream, or an application cluster) remains the sole authoritative source of graph truth.
The purpose of this contract is to specify:
- The boundary and responsibilities between Knotrel and the external system (the Feeder).
- Two formal operating modes: default Standalone Volatile Mode and opt-in Source-Managed Mode.
- The synchronization protocol: coherent initial graph image at source position $S$, incremental ordered update streaming, deduplicated progress events, and verification-only synchronization barriers $B$.
- The identity, versioning, generation, instance scoping, and feeder lease/fencing model.
- The acknowledgment, visibility, retry, exact bounded duplicate-detection, and failure semantics.
- The synchronization-aware lifecycle, readiness states, lease tracking, and freshness visibility.
- The deterministic acceptance-test specification matrix and Feature 0.2.2 implementation handoff.
1.2 Non-Goals
The following capabilities are explicitly out of scope for v0.2.0:
- Local Durability: Knotrel does not provide local Write-Ahead Logging (WAL), Append-Only Files (AOF), disk snapshots, or local crash recovery in v0.2.0. Applying an update in memory never implies durability in the authoritative store.
- Provider-Specific Connectors: Knotrel does not embed database-specific drivers, Kafka/Postgres/MySQL connectors, or CDC parsers. An external feeder is responsible for reading the source and calling Knotrel’s transport API.
- Multi-Graph Routing: Knotrel continues to own exactly one graph per server instance. Logical graph identifiers are used for validation and fencing, not dynamic multi-tenancy.
- Transaction Rollback: Knotrel executes operations in memory without transactional undo or two-phase commit rollback.
- Distributed Consensus: Knotrel is a single-process accelerator; distributed consensus, active-active multi-leader replication, and partition merging remain feeder responsibilities.
2. Operating Modes and Selection
Knotrel defines two mutually exclusive operating modes configured at startup:
+-----------------------------------------------------------------------------------------+
| KNOTREL MODES |
+-----------------------------------------------------------------------------------------+
| Standalone Volatile Mode (Default) | Source-Managed Mode (Opt-In) |
| - KNOTREL_MODE=standalone | - KNOTREL_MODE=source_managed |
| - Self-contained, in-memory graph | - Graph derived from external source |
| - Mutating /v1/operations & /v1/batch OK | - Direct mutating REST operations BLOCKED |
| - state_version increments on changes | - Graph advanced solely by Feeder protocol|
| - Restart starts empty or from supplied | - Restart requires full external rebuild |
| - Ready immediately after startup | - Ready ONLY after verified barrier B |
+-----------------------------------------------------------------------------------------+
2.1 Standalone Volatile Mode (Default)
- Selection: Selected when
KNOTREL_MODEis unset or set tostandalone. - Compatibility: 100% backward compatible with Knotrel v0.1.0 preview.
- Graph Initialization: Starts empty (for the standalone binary) or from the user-supplied
Graph(for library embedders callingrouter(graph)). - Mutations: Direct client mutations via
POST /v1/operations(add_node,link,cut) andPOST /v1/batchare fully supported. - Readiness:
/readytransitions fromstartingtoreadyas soon as the listener begins serving, and reports 503 only during shutdown (draining) or worker panic (unavailable). - State Version: Tracks local mutations using the arbitrary-precision decimal counter (
"0","1","2", …) established in v0.1.0.
2.2 Source-Managed Mode (Opt-In)
- Selection: Explicitly selected at startup via
KNOTREL_MODE=source_managed(orServerConfig::with_mode(ServerMode::SourceManaged)for embedded callers). - Graph Authority: Knotrel is a derived read accelerator. The external data store is the authoritative source of truth.
- Direct Mutation Prohibition: Direct client mutations via
POST /v1/operations(add_node,link,cut, and with lifecycle supportset_node_active,set_edge_enabled,remove_node) and mutating operations inPOST /v1/batchare rejected with HTTP 409 Conflict (code:direct_mutation_disabled). Clients must not bypass source ordering. - Queries: Connectivity queries (
POST /v1/operationswithop: "connected", and with lifecycle supportnode_stateandedge_state) and batch queries remain supported, subject to the readiness and freshness policy. - Readiness:
/readyreports 503 during bootstrap (uninitialized,loading,catching_up) and transitions to 200readyonly after an initial coherent graph image is published and verified through a synchronization barrier $B$. - Restart Semantics: Process restart completely discards in-memory volatile graph state. Upon restart, the server re-enters
uninitializedwith a newinstance_idand requires the external feeder to perform a full bootstrap.
2.3 Mode Admission & Route Enforcement Matrix
| Route | Method | Standalone Volatile Mode | Source-Managed Mode |
|---|---|---|---|
/health |
GET | 200 {"status":"ok"} |
200 {"status":"ok"} |
/ready |
GET | 200 ready (503 if starting/draining/unavailable) |
200 ready ONLY when synchronized; 503 during bootstrap, lag, gap, or failure |
/v1/info |
GET | 200 (settings snapshot, mode: "standalone") |
200 (settings snapshot, mode: "source_managed", instance_id, feeder_reserved_jobs) |
/v1/stats |
GET | 200 (live node/edge counts, state_version) |
200 (counts, instance_id, state_version, generation, source_position, sync_status) |
/metrics |
GET | 200 when KNOTREL_METRICS_ENABLED=true, otherwise 404 |
Same; source-managed families included |
/v1/operations (connected; with lifecycle support node_state, edge_state) |
POST | 200 (query outcome) | 200 while a generation is usable (also while catching_up or stale); 503 uninitialized, loading or desynchronized otherwise |
/v1/operations (add_node/link/cut; with lifecycle support set_node_active/set_edge_enabled/remove_node) |
POST | 200/404/422 (applied under graph lock) | 409 Conflict (code: "direct_mutation_disabled") |
/v1/batch (all queries) |
POST | 200 (query outcomes) | 200 with query outcomes while a generation is usable; otherwise 200 with one uninitialized, loading or desynchronized error result per operation |
/v1/batch (contains $\ge 1$ mutation) |
POST | 200 (runs with continue-on-error) | 409 Conflict (code: "direct_mutation_disabled") |
Lifecycle operations without KNOTREL_TOPOLOGY_LIFECYCLE=true |
POST | 409 topology_lifecycle_disabled |
409 topology_lifecycle_disabled (checked before the mode) |
/v1/nodes, /v1/nodes/{node}, /v1/nodes/{node}/edges, /v1/edges (experimental) |
GET | 200 with KNOTREL_INSPECTION=true, otherwise 409 inspection_disabled |
Same, no readiness gate |
/v1/feeder/session |
POST | 409 mode_conflict |
Admitted: acquires or fences feeder session lease |
/v1/feeder/heartbeat |
POST | 409 mode_conflict |
Admitted: extends feeder lease deadline |
/v1/feeder/import |
POST | 409 mode_conflict |
Admitted: candidate built, published, generation bumped |
/v1/feeder/events |
POST | 409 mode_conflict |
Admitted: ordered updates applied under graph lock |
/v1/feeder/barrier |
POST | 409 mode_conflict |
Admitted: barrier verified, transitions to ready |
/v1/feeder/gap |
POST | 409 mode_conflict |
Admitted: declares source history loss $\to$ Desynchronized |
3. Identity, Generations, Versions, and Fencing
To ensure deterministic synchronization and prevent split-brain anomalies or cross-restart collisions, Knotrel establishes an explicit identity and version hierarchy.
+-----------------------------------------------------------------------------------------------+
| IDENTITY HIERARCHY |
+-----------------------------------------------------------------------------------------------+
| Service Instance Identity: instance_id (opaque, ephemeral, changes every process restart) |
| | |
| +--> Feeder Lease: feeder_session_id & feeder_epoch (fencing token, renewed by heartbeat) |
| | |
| +--> Logical Graph Identity: graph_id (string, e.g. "default", defines projection) |
| | |
| +--> Published Generation: generation (u64, 1, 2, ..., scoped to instance_id) |
| | |
| +--> Source Lineage: source_id & source_epoch (source branch/failover era) |
| | |
| +--> Source Position: applied_source_position (opaque string, advances on op) |
| | |
| +--> Local Revision: state_version (decimal string, advances on topology chg) |
+-----------------------------------------------------------------------------------------------+
3.1 Token Definitions
- Service Instance Identity (
instance_id):- Type: Ephemeral opaque string generated at process startup (for example
"srv-1a2b-0187f3c2d4e5f607-0001"). Its format is not part of the contract: feeders must compare it for equality only and must not parse it or validate its shape. - Invariant: Changes on every process launch/restart.
- Discovery: Exposed as
instance_idinGET /v1/infoandGET /v1/stats(source-managed mode).GET /readydoes not expose it. - Enforcement Rule: Every feeder request (
import,session,heartbeat,events,barrier,gap) must supplyinstance_idin the HTTP headerX-Knotrel-Instance-Id(and in the JSON payload). If the requestinstance_iddoes not match the active serverinstance_id, Knotrel rejects it with409 Conflict(code: "stale_instance_id") before reading the graph. The header is checked first, before the body is read and before any admission or import permit is acquired. The bodyinstance_idis checked once the body is parsed, because it is inside the body: onsession,heartbeat,events,barrierandgapthat is still before an admission permit is acquired, but onimportit is after the import permit is acquired and the body is received and parsed (the permit is taken before any body byte is read). A stale import that carries the current instance in its header and an old one in its body therefore holds the import permit while its body is received, and is then refused withstale_instance_idwithout reading or changing the graph. This prevents stale in-flight requests from a previous incarnation from colliding with a new incarnation that happens to be at generation 1.
- Type: Ephemeral opaque string generated at process startup (for example
- Logical Graph Identity (
graph_id):- Type: UTF-8 string (1–64 characters,
[a-zA-Z0-9_-]+). - Scope: Identifies the logical graph dataset or projection. Default:
"default". - Invariant: A Knotrel instance validates
graph_idin every feeder payload. Mismatched IDs are rejected with HTTP 400 (invalid_graph_id).
- Type: UTF-8 string (1–64 characters,
- Published Graph Generation (
generation):- Type: Unsigned 64-bit integer (
u64), represented as a JSON integer (for example"generation": 3). A JSON string such as"3"is rejected with 422invalid_request. - Lifecycle: Starts at
0before any import. Set to1on the initial baseline import, and increments monotonically ($g \to g + 1$) on every subsequent atomic graph replacement. - Scoping: Generational lineage is strictly scoped to
instance_id. - Invariant: Every incremental event, progress event, and barrier declaration must specify the exact current
generation. Any request bearing an older or newer generation is rejected immediately with HTTP 409 (stale_generation).
- Type: Unsigned 64-bit integer (
- Local State Revision (
state_version):- Type: Arbitrary-precision decimal string (
"0","1","2", …), encoded as little-endian digits internally without fixed-width integer wraparound. - Semantics: Preserves v0.1.0 behavior. Starts at
"0"upon service creation or upon publication of a new generation image. Increments by 1 if and only if an applied operation results in a topological change (changed: true). - Invariant: An accepted source event that is an effective graph no-op (e.g. linking an edge that already exists) or an explicit
progressevent does not incrementstate_version, but does advanceapplied_source_position.
- Type: Arbitrary-precision decimal string (
- Source Identity (
source_id):- Type: UTF-8 string identifying the external authoritative store or database cluster (e.g.,
"pg-cluster-prod-01"or"kafka-graph-events"). - Invariant: Bound at import. Updates from another
source_idare rejected with HTTP 409 (source_mismatch).
- Type: UTF-8 string identifying the external authoritative store or database cluster (e.g.,
- Source Epoch (
source_epoch):- Type: JSON string (UTF-8) identifying the timeline, failover epoch, or schema version of the source stream. A JSON number is rejected with 422
invalid_request; a feeder whose epoch is numeric sends its decimal string form (for example"3"). - Invariant: If the external database undergoes failover, timeline reset, or schema change, it increments its epoch. An event carrying a different
source_epochis rejected with HTTP 409 (source_epoch_mismatch) and forces a full graph rebuild.
- Type: JSON string (UTF-8) identifying the timeline, failover epoch, or schema version of the source stream. A JSON number is rejected with 422
- Applied Source Position (
applied_source_position):- Type: Opaque UTF-8 string (1 to 256 bytes, not characters; enforced on every source position the server accepts, otherwise 422
invalid_request) representing the external cursor (e.g. Postgres LSN"0/16B3740", Kafka offset"104928", or hybrid token"epoch=3,pos=9912"). - Invariant: Knotrel never interprets this string as an integer, never parses its structure, and never compares cursors lexicographically. It treats the cursor as an opaque token received from the feeder.
- Type: Opaque UTF-8 string (1 to 256 bytes, not characters; enforced on every source position the server accepts, otherwise 422
- Feeder Session Identity & Lease Fencing (
feeder_session_id,feeder_epoch):feeder_session_id: Unique string identifying the active feeder process instance.feeder_epoch: Monotonically increasing 64-bit integer fencing token.- Invariant: Only requests bearing the currently registered
feeder_session_idand matchingfeeder_epochare admitted to apply updates. A request bearing an olderfeeder_epochis rejected with HTTP 409 (fenced_feeder_session).
4. Feeder Session and Lease Protocol
Ownership and readiness in source-managed mode are governed by an explicit Lease Protocol, decoupled from underlying HTTP TCP connections.
4.1 Session Acquisition and Transitions
To become the active writer, a feeder registers a session:
- Endpoint:
POST /v1/feeder/session - Payload:
instance_id,feeder_session_id,feeder_epoch,lease_duration_ms(required, no default; 1,000 ms to 60,000 ms, otherwise 400invalid_lease_duration). - Clock: Lease duration is evaluated exclusively against the host’s monotonic clock (
std::time::Instant), never wall-clock time.
Complete Feeder Session Transition Matrix
| Current Server Lease State | Incoming Session Request | Action & Response | Resulting Lease State |
|---|---|---|---|
| No active session (Startup) | Any (session_A, epoch_1) |
Accept: set active session, initialize monotonic deadline. Return 200 session_acquired. |
Active (session_A, epoch_1) |
Active (session_A, epoch_1) |
Exact retry: (session_A, epoch_1) |
Idempotent: extend monotonic deadline. Return 200 session_acquired. |
Active (session_A, epoch_1) |
Active (session_A, epoch_1) |
Same session, lower epoch: (session_A, epoch_0) |
Reject: 409 Conflict (fenced_feeder_session). |
Active (session_A, epoch_1) |
Active (session_A, epoch_1) |
Same session, higher epoch: (session_A, epoch_2) |
Accept: update epoch to 2, extend monotonic deadline. Return 200 session_acquired. |
Active (session_A, epoch_2) |
Active (session_A, epoch_1) |
Another session, higher epoch: (session_B, epoch_2) |
Takeover Accepted: preempt session A, set active session to B, reset monotonic deadline. Return 200 session_acquired. |
Active (session_B, epoch_2) |
Active (session_A, epoch_1) |
Another session, lower/equal epoch: (session_B, epoch_1) |
Reject: 409 Conflict (fenced_feeder_session). |
Active (session_A, epoch_1) |
Active (session_A, epoch_1) |
Monotonic deadline elapses without heartbeat | Lease Expired: ownership remains assigned to session A, but lease is expired. State transitions to Disconnected/Stale, recording last_expired_epoch = 1. |
Expired (session_A, epoch_1) |
Expired (session_A, epoch_1) |
Heartbeat from (session_A, epoch_1) |
Lease Renewed: extends deadline. Readiness remains Stale until synchronization recovery proof under a newly registered epoch (§4.3). Return 200 heartbeat_acknowledged. |
Active (session_A, epoch_1) |
| Any active lease | Requests queued in worker pool across takeover | Under mutex, queued request observes live.feeder_epoch > req.feeder_epoch. Fenced: rejected with 409 fenced_feeder_session. |
Unchanged |
4.2 Independent Observation of Lease Expiry
Lease expiration is checked independently of slow graph worker jobs:
- The server maintains a lock-free atomic word (
PublishedReadiness, the runtime’sReadinessWord) encoding status, publication sequence, and monotonic deadline millis. - Probes (
GET /ready), stats (GET /v1/stats), and request admission gates read this atomic word without acquiring the graph lock. - If the current monotonic clock exceeds the published deadline:
- If server phase was
Ready, it is immediately observed as 503status: "stale", and/readyattempts a lock-free CAS to update the published status word toStalewithout overwriting newer publications. - A long-running graph worker traversal cannot block or delay detection of feeder abandonment.
- If server phase was
4.3 Lease Renewal vs. Synchronization Proof & Recovery Fencing
[!IMPORTANT] A heartbeat proves feeder liveness, NOT graph catch-up.
- When a lease expires, Knotrel transitions to
Disconnected/Staleand records the expired epoch (last_expired_epoch).- A subsequent valid heartbeat (
POST /v1/feeder/heartbeat) successfully renews the lease deadline, but DOES NOT restore readiness toReady.- Explicit Recovery-Fencing Across Expiry: To prevent delayed, obsolete in-flight barriers created before expiry from executing after a heartbeat and resurrecting
Readywithout fresh proof, Knotrel explicitly fences synchronization recovery:
- Any barrier submitted under
feeder_epoch <= last_expired_epochis rejected with409 Conflict(code: "fenced_feeder_session"), whatever its delivery sequence and source position: the fence is evaluated before B8, B9 and B7 (see the guaranteed precedence in §5.3).- To restore
Readyafter lease expiry, the feeder must register a strictly newer epoch (POST /v1/feeder/sessionwithfeeder_epoch > last_expired_epoch).- Under the new epoch, the feeder supplies fresh verification proof that Knotrel is synchronized with the source:
- If source updates were produced during the disconnect, the feeder streams them followed by barrier $B$.
- If zero source updates were produced, the feeder issues an exact verification barrier (
POST /v1/feeder/barrier) matching current $D_{applied}$ and $P_{applied}$, affirming no changes occurred.- Heartbeats must never clear
Failed,Desynchronized,Uninitialized,Loading, orCatchingUpstates.
5. Source-to-Knotrel Synchronization Protocol
The synchronization protocol coordinates the external feeder and Knotrel through an explicit state machine.
+-------------------+
| UNINITIALIZED |
+-------------------+
|
| [Feeder: POST /v1/feeder/import (Image S)]
v
+-------------------+
| LOADING |
+-------------------+
|
| [Import Validated & Published as Gen g]
v
+-------------------+
+--------> | CATCHING_UP | <--------+
| +-------------------+ |
| | |
| [More Updates/ | [Feeder: POST /v1/feeder/barrier (Pos B)]
| Progress Events] v |
| +-------------------+ |
+--------- | READY/SYNCHRONIZED| ---------+
+-------------------+
| |
[Lease Expiration / | | [Declared Unrepairable Gap /
Heartbeat Timeout] | | Source Epoch Mismatch]
v v
+--------------+ +-----------------+
| STALE/DISCONN| | DESYNCHRONIZED |
+--------------+ +-----------------+
| |
| [Feeder Proves | [Full Rebuild Required]
| Sync at B] |
+-----------------+
5.1 Verifiable Continuity: Delivery Sequences and Predecessor Tokens
Because opaque external cursors cannot be verified as contiguous by Knotrel, the feeder must supply a transport-level continuity envelope for every event:
delivery_sequence($D$): A strictly increasing 64-bit integer, starting at1for the first update following import $S$, incrementing by exactly1for each subsequent update ($1, 2, 3, \dots$).prev_delivery_sequence($D_{prev}$): The delivery sequence of the immediate predecessor ($0$ for the first event).source_position($P$): The opaque source cursor for this event (1 to 256 bytes of UTF-8).prev_source_position($P_{prev}$): The opaque source cursor of the predecessor (for $D=1$, matches snapshot position $S$; 1 to 256 bytes of UTF-8).event_id: A unique string identifier (up to 64 bytes of UTF-8) for idempotent retry tracking. All these limits count bytes, not characters; a value outside them refuses the whole request with 422invalid_request.
5.2 Ordered Progress Events (Sole Mechanism for Non-Mutating Progress)
To advance applied_source_position through source transactions that affect tables unrelated to the graph (or produce zero graph mutations), the feeder must emit explicit progress events:
{
"event_id": "prog-1001",
"delivery_sequence": 15,
"prev_delivery_sequence": 14,
"source_position": "0/16B4000",
"prev_source_position": "0/16B3800",
"op": "progress"
}
- A
progressevent is ordered, validated, and deduplicated identically tolinkandcut. - Under the graph lock: advances
applied_source_position = event.source_positionand $D_{applied} \leftarrow D$. state_versionis not incremented because no topological mutation occurred.- Retries of
progressevents are deduplicated identically to other events.
5.3 Verification-Only Synchronization Barriers
A barrier declaration (POST /v1/feeder/barrier) is strictly verification-only:
- It never mutates graph topology.
- It never advances
applied_source_positionordelivery_sequence. - It asserts that Knotrel has applied all events and progress up to barrier position $B$ ($D_{barrier}$, $P_{barrier}$).
Mutually Exclusive Barrier Evaluation Decision Table (Under Graph Lock)
Preconditions checked before table evaluation:
req.instance_id == live.instance_id(mismatch $\to$409 stale_instance_id, state preserved).req.feeder_session_id == live.feeder_session_idandreq.feeder_epoch == live.feeder_epoch(mismatch $\to$409 fenced_feeder_session, state preserved).- Monotonic lease is unexpired (
monotonic_now() <= live.lease_deadline; expired $\to$409 lease_expired, state preserved). req.generation == live.generation(mismatch $\to$409 stale_generation, state preserved).- Recovery fence (§4.3): if a lease expired,
req.feeder_epoch > last_expired_epoch(otherwise $\to$409 fenced_feeder_session, state preserved). This is evaluated after B3/B4 and B5 and before B8, B9 and B7 (see the precedence below).
Guaranteed precedence. When a barrier meets several rejection conditions, the first in this order decides the answer; every rejection preserves the state (graph, $D_{applied}$, $P_{applied}$, synchronization status, /ready):
- Failed worker (B6) $\to$
503 unavailable. - Session and lease: no registered session $\to$
409 session_required; session or epoch mismatch $\to$409 fenced_feeder_session; expired lease $\to$409 lease_expired. - Generation $\to$
409 stale_generation. - Uninitialized or initial loading (B3, B4) $\to$
409 graph_uninitialized. - Desynchronized (B5) $\to$
409 graph_desynchronized. - Recovery fence,
feeder_epoch <= last_expired_epoch$\to$409 fenced_feeder_session, whatever the sequence and position. barrier_source_positionoutside 1 to 256 bytes of UTF-8 $\to$422 invalid_request.- Premature sequence (B8) $\to$
409 barrier_not_reached. - Older sequence (B9) $\to$
409 superseded_barrier. - Position mismatch at equal sequence (B7) $\to$
409 barrier_position_mismatch. - Exact match: B1 or B2 (
200).
Checks made before the graph worker come first: operating mode (409 mode_conflict), the X-Knotrel-Instance-Id header and the body instance_id (409 stale_instance_id), graph_id (400 invalid_graph_id), service availability and the feeder data lane (503 busy). Before v1.0.0 the recovery fence was evaluated after B8, B9 and B7, so a fenced barrier with a wrong sequence or position got their code instead of fenced_feeder_session (compatibility.md, approved exception).
Under the mutex, $(D_{barrier}, P_{barrier})$ is matched against $(D_{applied}, P_{applied})$:
| Case | Sequence Condition | Position Condition | Current Sync State | Outcome & HTTP Response | Resulting Sync State |
|---|---|---|---|---|---|
| B1: Exact Match (Restores Ready) | $D_B == D_{applied}$ | $P_B == P_{applied}$ | CatchingUp or Stale (published $g > 0$) |
200 OK (result: "synchronized") |
Transitions to Ready |
| B2: Exact Match (Affirms Ready) | $D_B == D_{applied}$ | $P_B == P_{applied}$ | Ready (published $g > 0$) |
200 OK (result: "already_synchronized") |
Remains Ready |
| B3: Exact Match While Uninitialized | $D_B == D_{applied}$ | $P_B == P_{applied}$ | Uninitialized ($g == 0$) |
409 Conflict (code: "graph_uninitialized") |
Remains Uninitialized (no barrier may make an unpublished initial graph Ready) |
| B4: Exact Match While Initial Loading | $D_B == D_{applied}$ | $P_B == P_{applied}$ | Loading (initial baseline, $g == 0$) |
409 Conflict (code: "graph_uninitialized") |
Remains Loading (initial candidate unpublished) |
| B5: Exact Match While Desynchronized | $D_B == D_{applied}$ | $P_B == P_{applied}$ | Desynchronized |
409 Conflict (code: "graph_desynchronized") |
Remains Desynchronized (barrier cannot clear gap) |
| B6: Exact Match While Failed | $D_B == D_{applied}$ | $P_B == P_{applied}$ | Failed |
503 Service Unavailable (code: "unavailable") |
Remains Failed (worker failed permanently) |
| B7: Position Mismatch at Equal Sequence | $D_B == D_{applied}$ | $P_B$ supplied and $P_B \ne P_{applied}$ (an omitted or null $P_B$ matches any position) | Any | 409 Conflict (code: "barrier_position_mismatch") |
Unchanged (preserves existing state) |
| B8: Premature Sequence | $D_B > D_{applied}$ | Any | Any | 409 Conflict (code: "barrier_not_reached") |
Unchanged (preserves existing state) |
| B9: Older Sequence (Conservative Rejection) | $D_B < D_{applied}$ | Any | Any | 409 Conflict (code: "superseded_barrier") |
Unchanged (preserves existing state) |
Prohibition of Barriers Making Unpublished Graphs Ready
Under no circumstances may a barrier request make an unpublished graph Ready:
- In
Uninitialized($g == 0$), no baseline graph has been imported. Any barrier request—even if specifying $D_B = 0$ and matching $P_{applied} = \text{null}$—is rejected with409 Conflict(code: "graph_uninitialized"), preservingUninitialized. - During initial baseline
Loading($g == 0$), an import candidate is being parsed and constructed off-lock. The graph has not been published to readers. Any barrier arriving during this phase is rejected with409 Conflict(code: "graph_uninitialized"), preservingLoading.
Relationship Between Replacement Loading and the Currently Published Graph
When a replacement graph is imported (mode: "replace"):
- The candidate graph is parsed and constructed in memory off-lock by a dedicated import worker thread.
- During this background build, the currently published live graph remains active at
generation g. It continues serving queries and processing incremental feeder updates under the mutex according to its active synchronization status (Ready,CatchingUp, orStale). - If a barrier arrives specifying
generation == g, it is evaluated strictly against generation $g$’s live stream frontier $(D_{applied}, P_{applied})$ using the decision table above (e.g. Case B1 restoresReady, Case B2 affirmsReady). It has zero relationship with the uncommitted replacement candidate. - If a barrier arrives specifying candidate
generation == g + 1before publication, it is rejected by Precondition 4 with409 Conflict(code: "stale_generation"), because generation $g + 1$ has not yet been published. The live state of generation $g$ is strictly preserved. - Only upon successful candidate construction, precondition verification under the mutex, and atomic pointer swap is generation $g + 1$ published. At that instant,
live.generationbecomes $g + 1$, $D_{applied}$ resets to 0,applied_source_positionbecomes snapshot $S$, and the server transitions toCatchingUp. From that moment onward, barriers for generation $g + 1$ are evaluated against the newly published baseline.
Conservative Rejection of Older Barriers (Case B9)
Proving whether an older barrier ($D_B < D_{applied}$) was historically valid would require retaining an unbounded historical ledger recording past $(D, P)$ checkpoints. Knotrel stores only the single current stream frontier $(D_{applied}, P_{applied})$ and recent operation descriptors in its ring buffer deduplication window, without a historical position ledger. Knotrel therefore avoids unsupported matching claims and conservatively rejects all older barriers with 409 Conflict (code: "superseded_barrier"). This rejection strictly preserves the existing synchronization state and prevents delayed or reordered barrier requests from altering state.
Conditions for Restoring Ready
A barrier request transitions the server from CatchingUp or Stale to Ready strictly under Case B1, which requires all of the following:
- Valid feeder session ownership (
req.feeder_session_id == live.feeder_session_idandreq.feeder_epoch == live.feeder_epoch). - An active, unexpired monotonic lease (
monotonic_now() <= live.lease_deadline). - Matching instance identity (
req.instance_id == live.instance_id) and generation (req.generation == live.generation). - Exact delivery sequence equality ($D_B == D_{applied}$) AND, when $P_B$ (
barrier_source_position) is supplied, position equality ($P_B == P_{applied}$); an omitted or null $P_B$ is not compared.
Case B2 affirms that an already Ready server remains Ready (200 OK, result: "already_synchronized"). If the server is in Desynchronized (Case B5) or Failed (Case B6), matching sequence and position cannot bypass the failure, and the barrier is rejected while preserving the failure state.
[!IMPORTANT] State Preservation Invariant: Every rejected barrier (B3 through B9) strictly preserves the existing synchronization state without alteration. Because barriers never modify
applied_source_position, delayed or reordered barriers can never regress or corrupt the source cursor.
6. Execution Boundary, Predecessor Validation, and Sequence Classification
To eliminate race conditions between deduplication, predecessor checks, and sequence validation, all checks are evaluated together under the exclusive graph lock.
6.1 Request Validation and Execution Pipeline
[Phase 1: Pre-Lock Validation]
1. Route & Method Validation (404/405)
2. Content-Type is JSON (415 invalid_request)
3. Body size within bound (413 invalid_request)
3a. Body read to its end: no client abort, malformed chunked encoding or receive error (400 invalid_request)
4. JSON syntax valid (400 invalid_request)
5. Schema shape, field constraints, node ID strings (422 invalid_request)
6. Lifecycle check: not draining (503 shutting_down)
7. Instance identity check: req.instance_id == live.instance_id (409 stale_instance_id)
8. Feeder fencing check: req.feeder_epoch == live.feeder_epoch & session match (409 fenced_feeder_session)
9. Generation precondition: req.generation == live.generation (409 stale_generation)
10. Source lineage: req.source_id == live.source_id & req.source_epoch == live.source_epoch (409 source_mismatch / source_epoch_mismatch)
11. Acquire worker permit from semaphore (503 busy)
[Phase 2: Under Exclusive Graph Lock]
12. Re-verify instance, feeder lease, and generation tokens under lock.
13. Sequence Classification of delivery_sequence D against applied sequence D_applied:
+---------------------------------------------------------------------------------+
| Case A: D <= D_applied (Previous / Retried Sequence) |
| - If D < D_window_min (evicted from N-entry window): |
| return 409 Conflict (code: "unverifiable_duplicate"). State unchanged. |
| - If D in [D_window_min, D_applied]: look up D in sequence ring buffer: |
| * If req.event_id != retained.event_id: |
| return 409 (conflicting_duplicate) -> state Desynchronized. |
| * If req.event_id == retained.event_id: perform Tier 2 canonical check: |
| - If canonical content matches: return 200 OK (already_applied). |
| - If canonical content differs: return 409 (conflicting_duplicate) |
| -> state Desynchronized (protocol violation). |
+---------------------------------------------------------------------------------+
| Case B: D == D_applied + 1 (Expected Next Sequence) |
| - Verify D_prev == D_applied. |
| - Source Predecessor Check: verify event.prev_source_position == |
| live.applied_source_position. |
| * If mismatch: reject with 409 (source_predecessor_mismatch), transition |
| state to Desynchronized, STOP progress. |
| - Retained Event ID Uniqueness Check: |
| * Check if req.event_id exists in retained event_id hash index: |
| - If found: return 409 (conflicting_duplicate) -> state Desynchronized. |
| (retained event ID reused at new sequence). |
| - Note: an event ID evicted from window (> N events ago) cannot be |
| detected and is evaluated as fresh at D_applied + 1. |
| - Execute graph mutation(s) or progress event: |
| * If domain error (self_loop / limit_exceeded / unknown_node / |
| unknown_edge): reject with 422 (feeder events have no 404 outcome), |
| STOP progress. (Uncommitted rejected attempts NOT recorded in window). |
| * If success: |
| - If changed: true (and not progress), increment state_version. |
| - Advance applied_source_position = event.source_position. |
| - Advance D_applied = D. |
| - Record in sequence ring buffer and event_id index (evicting oldest |
| if window exceeds capacity N). |
| - Return 200 OK (applied). |
+---------------------------------------------------------------------------------+
| Case C: D > D_applied + 1 (Future Sequence / Transport Gap) |
| - Reject request immediately: 409 Conflict (out_of_order_sequence). |
| - Live graph state remains untouched at D_applied. |
| - Feeder must resend from expected sequence D_applied + 1. |
+---------------------------------------------------------------------------------+
Implementation note (verified for M3.2, 2026-11-12). The diagram above is the
logical order. In the 0.2.x/0.3.0 implementation, only the instance header/body
check, graph_id, JSON shape and service availability run before admission
(api.rs feeder_events). Steps 8–10 (session, epoch, lease, generation, source
lineage), the 1..=1024 count check and per-event shape/bounds prevalidation all run
once under the graph lock, before the first event is applied
(service.rs GraphState::apply_events). The observable result is the same: they
reject the whole request with no graph or frontier change, except that a
source_epoch mismatch and an expired lease also change synchronization status
(see §9.3). When the feeder’s admission lane is exhausted (since 0.9.0 feeder
requests have reserved permits that queries never use; see docs/http-api.md,
“Admission and cancellation”), /v1/feeder/events returns
503 busy: no event of that request was admitted. (Before v1.0.0 it returned
503 import_in_progress; that code now means only that another import is
running. See §9.3.)
6.2 Source Predecessor Validation and Feeder Obligations
- Validation: For every new event ($D == D_{applied} + 1$), Knotrel verifies under the mutex that
event.prev_source_position == live.applied_source_position. - Mismatch Result: If
prev_source_positiondoes not match, Knotrel responds with409 Conflict(code: "source_predecessor_mismatch") and transitions state toDesynchronized. - Feeder Obligation: Sequence continuity proves transport order, but cannot prove that the feeder extracted all authoritative source transactions. Faithful snapshot extraction, transaction filtering, and projection remain feeder responsibilities.
6.3 Normative Sequence Jump and Gap Resolution Table
| Condition | Error Code | HTTP Status | Next Server State | Query Serving Behavior | Feeder Recovery Action | Condition to Return to Ready |
|---|---|---|---|---|---|---|
| Transient Transport Out-of-Order ($D > D_{applied} + 1$) | out_of_order_sequence |
409 |
Unchanged (CatchingUp or Ready) |
Continues serving queries if was Ready |
Resend missing event starting at $D_{applied} + 1$ | When sequence reaches barrier $B$ |
| Source Predecessor Mismatch ($P_{prev} \ne P_{applied}$) | source_predecessor_mismatch |
409 |
Desynchronized |
All queries return 503 desynchronized |
Inspect source timeline; rebuild from fresh snapshot $S’$ | Full atomic replacement import at $S’$ followed by catch-up to $B’$ |
Declared Unrepairable Source Gap (POST /v1/feeder/gap) |
gap_acknowledged |
200 |
Desynchronized |
All queries return 503 desynchronized |
Abort incremental catch-up; obtain fresh snapshot $S’$ | Full atomic replacement import at $S’$ followed by catch-up to $B’$ |
Source Epoch Reset / Failover (source_epoch mismatch) |
source_epoch_mismatch |
409 |
Desynchronized |
All queries return 503 desynchronized |
Feeder must rebuild from authoritative source | Full atomic replacement import at new epoch |
| Evicted Duplicate ($D \le D_{applied}$, evicted from ring buffer) | unverifiable_duplicate |
409 |
Unchanged | Continues serving queries if was Ready |
Re-verify feeder tracking or initiate full rebuild if continuity lost | N/A (already ready if stream is active) |
| Conflicting Duplicate ($D \le D_{applied}$, content differs) | conflicting_duplicate |
409 |
Desynchronized |
All queries return 503 desynchronized |
Fatal feeder logic bug; inspect feeder event store | Full atomic replacement import |
| Retained Sequence with Different Event ID ($D \in [D_{win}, D_{app}]$, $ID \ne ID_{ret}$) | conflicting_duplicate |
409 |
Desynchronized |
All queries return 503 desynchronized |
Protocol violation: sequence reassigned; inspect feeder | Full atomic replacement import |
| Retained Event ID Reused at New Sequence ($D == D_{app}+1$, $ID \in \text{window}$) | conflicting_duplicate |
409 |
Desynchronized |
All queries return 503 desynchronized |
Protocol violation: event ID duplicate; inspect feeder | Full atomic replacement import |
| Premature Barrier ($B$ declared but $D_{applied} < D_{barrier}$) | barrier_not_reached |
409 |
Remains CatchingUp |
Queries return 503 catching_up |
Feeder streams remaining events up to $D_{barrier}$, then re-declares barrier | Barrier declaration succeeds |
| Barrier Position Mismatch ($D_B == D_{applied}$, $P_B \ne P_{applied}$) | barrier_position_mismatch |
409 |
Unchanged (preserves state) | Queries return status based on current state | Reconcile feeder position tracking; stream missing events or re-declare matching barrier | Barrier declaration succeeds |
| Older / Superseded Barrier ($D_B < D_{applied}$) | superseded_barrier |
409 |
Unchanged (preserves state) | Queries return status based on current state | Advance feeder barrier target to current frontier $D_{applied}$ and declare matching barrier | Barrier declaration succeeds |
| Barrier While Uninitialized / Initial Loading ($g == 0$) | graph_uninitialized |
409 |
Unchanged (Uninitialized or Loading) |
Queries return 503 uninitialized or 503 loading |
Feeder must complete atomic import before declaring barrier | Initial import publishes baseline $S$ $\to$ CatchingUp |
7. Exact Bounded Deduplication and Resource Layout
Knotrel guarantees deterministic deduplication within a bounded window without relying on 64-bit hash equality as the sole proof of content match.
7.1 Deduplication Model, Dual-Index Structure, and Identity Semantics
- Generation Scoping: Deduplication records belong strictly to the active
generation. When an import publishes generation $g+1$, previous records are flushed. - Retained Window Horizon: The window stores up to $N$ entries (default $N = 10{,}000$,
KNOTREL_DEDUP_WINDOW_SIZE, at most 1,000,000), spanning sequence numbers: \([D_{window\_min}, D_{applied}] \quad \text{where} \quad D_{window\_min} = \max(1, D_{applied} - N + 1)\) - Dual-Index Data Structure:
- Sequence Ring Buffer: Direct modulo indexing by
delivery_sequence % Nstoring entries for the active contiguous sequence range $[D_{window_min}, D_{applied}]$. - Event ID Hash Index: Fast hash index mapping
event_id$\to$delivery_sequencefor all active entries in the window.
- Sequence Ring Buffer: Direct modulo indexing by
- Two-Tier Equality Verification:
- Tier 1 (Indexing): Fast sequence lookup in ring buffer and hash lookup in
event_idindex. - Tier 2 (Canonical Equality): Exact byte-for-byte comparison of:
event_idstring (up to 64 bytes).source_positionstring (1 to 256 bytes).- Canonical operation descriptor: operation type (
link,cut,add_node,progress, and with lifecycle supportset_node_active,set_edge_enabled,remove_node), normalized endpoints (min(u,v),max(u,v)for undirected edges) or node, and for lifecycle events the flag value (activeorenabled). A retry at a retained sequence with the sameevent_idbut a different operation type or flag is a conflicting duplicate (case 4 below).
- Tier 1 (Indexing): Fast sequence lookup in ring buffer and hash lookup in
- Mutually Exclusive Bounded Identity Decisions:
- Retained Committed Sequence with Different Event ID ($D \in [D_{window_min}, D_{applied}]$, incoming
event_id != retained.event_id): Sequence $D$ was already committed with a differentevent_id. $\implies$ Rejected with409 Conflict(code: "conflicting_duplicate"), transitions state toDesynchronized. - Retained Event ID Reused at New Sequence ($D == D_{applied} + 1$,
event_idfound in retained hash index): The feeder is attempting to reuse an already-committedevent_idunder a new sequence number. $\implies$ Rejected with409 Conflict(code: "conflicting_duplicate"), transitions state toDesynchronized. - Exact Retry ($D \in [D_{window_min}, D_{applied}]$, incoming
event_id == retained.event_id, Tier 2 matches): Both identity and canonical payload match the committed event. $\implies$ Idempotent200 OK(status: "already_applied",result: "duplicate"). Live graph topology andstate_versionremain unmodified; $D_{applied}$ does not advance. - Conflicting Content ($D \in [D_{window_min}, D_{applied}]$, incoming
event_id == retained.event_id, Tier 2 differs): Canonical operation, endpoints, flag, orsource_positiondiffer from the committed record. $\implies$ Rejected with409 Conflict(code: "conflicting_duplicate"), transitions state toDesynchronized. - Evicted History ($D < D_{window_min}$ or Evicted
event_idReuse):- Evicted Sequence: If an incoming request specifies $D \le D_{applied}$ with $D < D_{window_min}$, the record has been evicted. Knotrel cannot verify canonical content and returns
409 Conflict(code: "unverifiable_duplicate"), leaving state unchanged. - Evicted Event ID at New Sequence: If an incoming request at $D == D_{applied} + 1$ reuses an
event_idthat was committed more than $N$ events ago ($< D_{window_min}$), that historical event was evicted from both the ring buffer and the hash index. Knotrel cannot detect this historical reuse and evaluates the request as fresh at $D_{applied} + 1$. Knotrel guarantees deduplication and conflict detection strictly within the retained bounded window of $N$ entries, and explicitly disclaims detection outside this horizon.
- Evicted Sequence: If an incoming request specifies $D \le D_{applied}$ with $D < D_{window_min}$, the record has been evicted. Knotrel cannot verify canonical content and returns
- Retained Committed Sequence with Different Event ID ($D \in [D_{window_min}, D_{applied}]$, incoming
7.2 Memory Accounting Requirements
- Window Size ($N$): Default $N = 10{,}000$ entries (configurable at startup via
KNOTREL_DEDUP_WINDOW_SIZE, at most 1,000,000). - Entry Bounds:
- Max
event_id: 64 bytes UTF-8. - Max
source_position: 256 bytes UTF-8. - Fixed metadata: sequence integer, hash tokens, outcome flags.
- Max
- Implementation Memory Accounting Requirements:
The total memory consumed by the deduplication window depends on the data structure chosen by the implementation. An implementation must account for:- The primary ring buffer / index collection storage.
- Hash indexing structures and bucket capacities.
- Retained string heap allocations for variable-length
event_idandsource_positionvalues. - Normalized canonical operation payload descriptors.
- Global allocator per-allocation bookkeeping overhead and fragmentation.
Implementations must strictly enforce the entry ceiling $N$ and field bounds without leaking memory across generations.
- Complete Import Resource Accounting:
- Body buffering is gated: connection limits and single-permit semaphore (
KNOTREL_MAX_CONCURRENT_IMPORTS = 1) check occurs before streaming request body bytes. - Total import peak memory must be accounted for across all phases: \(\text{Peak Memory} = \text{Old Live Graph (retained for reads)} + \text{Buffered Raw JSON Body (max 64 MiB)} + \text{Decoded AST Collections} + \text{Candidate Graph Structure} + \text{Queued Work}\)
- Body buffering is gated: connection limits and single-permit semaphore (
8. Atomic Graph Import and Replacement Preconditions
Knotrel supports both initial baseline creation and conditional atomic replacement of the live graph:
8.1 Create-Only Mode vs. Replace Mode
In POST /v1/feeder/import, the payload explicitly declares mode:
mode: "create_only":- Precondition: Valid only when Knotrel is in state
Uninitialized(generation == 0). - If Knotrel already owns an active graph (
generation > 0), rejected with409 Conflict(code: "graph_already_initialized").
- Precondition: Valid only when Knotrel is in state
mode: "replace":- Precondition: Mandatory composite precondition.
- Header format (RFC 3986 percent-encoded cursor):
If-Match: "<expected_generation>.<expected_state_version>.<percent_encoded_source_position>" - The
If-Matchheader is the only carrier of the precondition. The import body has no precondition fields: it rejects unknown fields, so a body that carriesexpected_generation,expected_state_versionorexpected_source_positionis rejected with422 invalid_request. In the checks below,expected_generation,expected_state_versionandexpected_source_positiondenote the three components parsed fromIf-Match. - Post-Build Mutex Recheck: After candidate graph is built off-lock, worker acquires graph mutex and rechecks:
- Feeder lease and session epoch remain active and valid (failure $\to$
409 fenced_feeder_sessionor409 lease_expired). live.generation == expected_generation.live.state_version == expected_state_version.live.applied_source_position == expected_source_position.
- Feeder lease and session epoch remain active and valid (failure $\to$
- If any precondition field mismatches (2, 3, or 4), candidate is discarded, lock released, and request rejected with
412 Precondition Failed(code: "precondition_failed").
8.2 Atomic Publication Package
Under a single graph mutex acquisition, the following fields are atomically updated:
live.graph = candidate.graphlive.generation = live.generation + 1live.state_version = "0"live.source_id = import.source_idlive.source_epoch = import.source_epochlive.applied_source_position = import.source_positionlive.delivery_sequence = 0live.dedup_window.clear()live.sync_status = CatchingUplive.feeder_session_id = import.feeder_session_id,live.feeder_epoch = import.feeder_epoch
8.3 Publication from a Snapshot at Startup (v1.3.0, experimental)
With KNOTREL_SNAPSHOT_DIR (ADR 0016,
http-api.md), a new process instance may start
from the newest valid snapshot instead of an empty graph. A snapshot
guarantees only one thing: the graph equals the source state at the
snapshot’s applied position. It carries no feeder session, no delivery
sequence to continue and no deduplication history.
State machine edge. The graph starts in Loading (generation 0, /ready
503 loading). The restore runs in the background while probes and
/v1/info answer; it holds the import permit, so an import meanwhile gets
503 import_in_progress and is retried. It then ends in one of two ways:
- Restored:
Loading → CatchingUp. Under one graph lock acquisition, the package of §8.2 is published with the snapshot as the import:generation = 1(of thisinstance_id),state_version = "0",source_id,source_epochandapplied_source_positionfrom the snapshot,delivery_sequence = 0, an empty deduplication window. No feeder session is installed. Until a feeder lease covers the generation it reads asstale, and registering the first session records that missing lease, so the graph staysstaleuntil the barrier. The graph is neverreadyby itself: only a barrier (B1) makes it ready. - Fallback:
Loading → Uninitialized. No snapshot, a corrupt or unsupported one, an incompatible one (another graph or tenant, authority other thanexternal, no source position, flags withoutKNOTREL_TOPOLOGY_LIFECYCLE, counts over the configured limits) or a read error. The bootstrap of §8.1 proceeds as without snapshots. Corrupt newer snapshots are skipped in favor of the newest valid one; a failed restore deletes no file. The engine may differ from the one that took the snapshot.
Feeder resumption. After registering its session, the feeder reads
GET /v1/stats. A restored generation has restored_snapshot set (not
null), and source_id, source_epoch and source_position are the
snapshot’s. The feeder then decides:
| Feeder’s source state | Action | Result |
|---|---|---|
Same source_id and source_epoch, history after source_position available, no changes since |
Barrier barrier_delivery_sequence = 0, barrier_source_position = source_position |
ready (B1) |
Same source_id and source_epoch, history after source_position available |
Events from delivery_sequence = 1, prev_delivery_sequence = 0, the first with prev_source_position = source_position; then a barrier |
ready at the barrier |
Different source_epoch, history after source_position expired, or a gap |
replace import with If-Match: "1.0.<percent-encoded source_position>" |
New generation 2 in catching_up, restored_snapshot = null |
| Any | create_only import |
409 graph_already_initialized, as for any published generation |
The snapshot’s own generation, revision and delivery sequence (reported in
restored_snapshot and in the snapshot response) belong to the process that
took it and are information only: there is exactly one resumption rule, the
one that follows an import.
9. Partial Batch Failures, Rejected Events, and Remediation
9.1 Partial Batch Failure Semantics (Non-Trivial Global Sequence Example)
Feeder event batches use strict stop-on-first-error semantics.
Consider a batch starting at global sequence $D = 101$ with 3 events:
- Index 0: $D = 101$ (succeeds)
- Index 1: $D = 102$ (succeeds)
- Index 2: $D = 103$ (fails: self-loop error)
Execution Outcome:
- Events at $D = 101$ and $D = 102$ are applied and recorded in the deduplication window.
- Event at $D = 103$ is rejected; $D_{applied}$ advances to $102$.
- Knotrel responds with HTTP 422:
{ "result": "partial_failure", "code": "event_failed", "message": "batch stopped at batch index 2 (global sequence 103) due to domain error", "instance_id": "srv-550e8400-e29b-41d4-a716-446655440000", "generation": 1, "applied_delivery_sequence": 102, "applied_source_position": "0/16B3800", "state_version": "45", "failed_batch_index": 2, "failed_delivery_sequence": 103, "failed_event_id": "evt-8803", "error": { "code": "self_loop", "message": "self-loops are not permitted: node 5" } }
9.2 Rejected Events vs. Committed Events and Progress Invariants
1. Rejected Attempts are Not in Deduplication Window
- The deduplication window records only successfully committed events ($D \le D_{applied}$).
- A rejected event (e.g. failing at sequence $D_{applied} + 1$ due to
self_looporedge_limit_exceeded) is never applied to the graph and is not recorded in the deduplication window. - Retrying an uncommitted sequence:
- If retried with the exact same payload at $D_{applied} + 1$, it is evaluated fresh under the mutex and fails with the same domain error.
- If retried with corrected payload at $D_{applied} + 1$ (e.g. self-loop fixed to valid edge), it is evaluated as a new candidate for sequence $D_{applied} + 1$ and succeeds.
- In contrast, once an event is committed ($D \le D_{applied}$):
- Retained sequence with different event ID: If a request reuses a committed sequence $D \in [D_{window_min}, D_{applied}]$ with a different
event_id, it is rejected as409 Conflict(conflicting_duplicate) and transitions state toDesynchronized. - Retained event ID at new sequence: If a request at sequence $D_{applied} + 1$ reuses an
event_idalready present in the retained window, it is rejected as409 Conflict(conflicting_duplicate) and transitions state toDesynchronized. - Altered canonical content: If a request at sequence $D \in [D_{window_min}, D_{applied}]$ matches the committed
event_idbut alters operation, endpoints, lifecycle flag, orsource_position, it is rejected as409 Conflict(conflicting_duplicate) and transitions state toDesynchronized. - Exact retry: If a request at sequence $D \in [D_{window_min}, D_{applied}]$ matches
event_idand canonical payload, it returns200 OK(status: "already_applied"). - Evicted history boundary: Sequences older than the retained window ($D < D_{window_min}$) return
409 Conflict(code: "unverifiable_duplicate") with server state unchanged. Reusing anevent_idfrom an evicted sequence ($< D_{window_min}$) at a new sequence cannot be detected by the bounded window and is evaluated as fresh at $D_{applied} + 1$. Knotrel explicitly guarantees deduplication strictly within the retained $N$-entry window.
- Retained sequence with different event ID: If a request reuses a committed sequence $D \in [D_{window_min}, D_{applied}]$ with a different
2. Progress Events Cannot Bypass Required Graph Mutations
- A
progressevent is permitted only when the corrected authoritative source projection genuinely produces zero topological changes under the graph projection filter (e.g. a non-graph database row update, or an extraneous record emitted due to a projection filter bug). - Prohibition: Feeder is strictly forbidden from using a
progressevent to skip or bypass a required graph mutation that failed (e.g. because ofnode_limit_exceededoredge_limit_exceeded). Bypassing a required mutation would cause silent, unrecoverable topological divergence between Knotrel and the authoritative source. - Remediation for Required Mutation Failure (e.g. Capacity Ceilings):
- Stream progress is halted at the failing sequence.
- The operator must either reconfigure Knotrel with increased capacity (
KNOTREL_MAX_NODES,KNOTREL_MAX_EDGES) and initiate an external full rebuild, or - The feeder must declare an unrepairable source gap via
POST /v1/feeder/gap, transitioning state toDesynchronized.
9.3 Feeder Batch Failure Matrix (v0.3.0 M3.2)
This section records the verified failure model of POST /v1/feeder/events. It
is distinct from the continue-on-error POST /v1/batch contract (ADR 0013).
Every request runs in one worker under one exclusive graph-lock acquisition, so
queries and other requests observe the state either before or after the whole
request, never between events. “Applied” means applied to the volatile in-memory
graph; Knotrel has no WAL and nothing here implies local durability or
exactly-once delivery.
Frontier. For every applied event, including no-op mutations and progress
events, applied_delivery_sequence becomes the event’s sequence and
applied_source_position its source_position. state_version advances by
exactly 1 only for a mutation that changed the graph. The source position
therefore never runs ahead of the applied events.
Response shapes.
- Plain error (
{"result":"error","code","message"}, no version headers): whole-request rejection, or an in-loop failure of a single-event request. - Partial failure (
{"result":"partial_failure", ...}, §9.1, with version headers): an in-loop failure of a multi-event request, even at index 0.applied_delivery_sequence,applied_source_positionandstate_versiondescribe the committed prefix;failed_batch_index,failed_delivery_sequenceandfailed_event_ididentify the failed event; the outercodeisevent_failedfor a graph domain error (innererror.codeis the domain code), and otherwise equals the inner code.
| Case | HTTP / body | State change | Progress metadata | What the caller can safely infer | Tests |
|---|---|---|---|---|---|
Rejected before execution: standalone, instance, graph_id, JSON shape/size, unavailable |
409/400/413/415/422/503 plain error | None | None | Nothing was applied; fix the request | events.rs test_15, test_16, test_18 |
Feeder data lane exhausted (all KNOTREL_FEEDER_RESERVED_JOBS permits in use by events, barrier and gap calls) |
503 busy plain error |
None | None | This request was not admitted and applied nothing; it may be resubmitted unchanged | events.rs test_26; feeder_admission.rs |
Whole-request check under lock: empty or > 1024 events, any event with an invalid op, field or bound (even the last one), including active or enabled on add_node, link, cut or progress |
422 invalid_request plain error |
None | None | No event of the request was applied | events.rs test_18, test_21; topology.rs |
Lifecycle support off and any event is set_node_active, set_edge_enabled or remove_node (same per-event prevalidation slot; the first failing event in order decides between this and invalid_request) |
409 topology_lifecycle_disabled plain error |
None | None | No event of the request was applied; enable lifecycle support or stop sending lifecycle events | topology.rs |
Session/epoch fencing, stale generation, source_id mismatch, uninitialized graph |
409 plain error | None | None | No event applied; re-register, re-read generation, or rebuild | events.rs test_13, test_24; e2e_rebuild.rs |
| Lease expired (checked once at request start) | 409 lease_expired |
No graph change; status becomes stale |
None | No event applied; renew/re-register the session | events.rs test_13; bootstrap.rs (status stale) |
source_epoch mismatch |
409 source_epoch_mismatch |
No graph change; status becomes desynchronized |
None | No event applied; replacement import required | events.rs test_8 |
| Already desynchronized | 409 graph_desynchronized |
None | None | Replacement import required | events.rs test_17, test_19, test_23 |
Domain error at first event (index 0), including unknown_node and unknown_edge of lifecycle events |
Single event: 422 domain code. Batch: 422 partial_failure/event_failed, index 0 |
None | Prefix = previous frontier | Nothing applied; resubmit corrected event at applied_delivery_sequence + 1 |
events.rs test_9, test_20; topology.rs |
| Domain error at middle or last event | 422 partial_failure/event_failed |
Prefix applied; failed and later events not applied, not recorded in the window | Prefix frontier and version | Events ≤ applied_delivery_sequence are applied in memory; resume from failed_delivery_sequence |
events.rs test_10, test_20 |
| Sequence gap after a prefix | 409 partial_failure/out_of_order_sequence |
Prefix applied; status unchanged | Prefix frontier | Resend from applied_delivery_sequence + 1 |
events.rs test_7, test_23 |
| Predecessor mismatch or conflicting duplicate after a prefix | 409 partial_failure (source_predecessor_mismatch / conflicting_duplicate) |
Prefix applied; status becomes desynchronized |
Prefix frontier | Stream is inconsistent; replacement import required | events.rs test_4, test_8, test_23 |
| Evicted duplicate | 409 unverifiable_duplicate (partial_failure if multi-event) |
None beyond any prefix | Current frontier | Outcome of that old event cannot be verified | events.rs test_5 |
| Exact retained duplicate, single event | 200 duplicate/already_applied with historical_outcome |
None | Current frontier | An identical event was applied earlier in this generation; this does not identify which request applied it | events.rs test_2, test_11 |
| Exact retained duplicates in a multi-event request, optionally followed by new events | 200 applied; duplicates skipped and not counted in events_applied |
Only new events applied | New frontier | events_applied counts newly applied events only |
events.rs test_10, test_22, test_25 |
No-op mutation or progress event |
200 applied, counted in events_applied |
Frontier advances; version unchanged | New frontier | Event is applied and recorded in the window | events.rs test_1, test_22 |
| Request timeout or client disconnect after admission | 503 request_timeout, or no response |
The admitted worker may still execute later; when it does, it applies the request like any other (whole-request rejection, full application, or a prefix up to the first failure) | None for this request | Outcome unknown, including whether the worker has run yet. See Uncertain outcomes below | events.rs test_11, test_25 |
| Restart | New instance_id; old requests get 409 stale_instance_id |
Volatile state is lost | — | Re-register and import a new baseline | events.rs test_15 |
| Replacement import (any generation change) | Old-generation events get 409 stale_generation |
New generation resets frontier, version and window | Frontier = imported source_position, sequence 0 |
Continue from the new baseline at sequence 1 | events.rs test_12 (import race), test_19, test_24 (stale_generation) |
Uncertain outcomes (timeout, disconnect, lost response). Once admitted, a worker is not cancelled with its caller; the request is executed whenever the worker acquires the graph lock. Worker completion means the request was processed, not that every event was applied: processing still stops at the first failing event, and whole-request checks (fencing, lease, generation, source lineage) are evaluated at execution time, not at submission time. Consequently:
- A
GET /v1/statsresult or version headers are a point-in-time snapshot, not a completion barrier for an earlier request. - An unchanged frontier does not prove that the timed-out worker cannot still
apply events afterwards (
events.rstest_25observes exactly this). - A matching or advanced
source_position/applied_delivery_sequencedoes not prove that this request applied those events; another request (a retry, or the same stream from another submission) may have done so. - Resubmitting the identical events is safe and resolves the outcome only while
the same
instance_id,generation,source_id/source_epochand feeder session/epoch remain valid, the lease is held, and the earlier events are still in the retained deduplication window. Retained events then return as exact duplicates and only missing events are applied (test_11,test_22,test_25). - If instead the retry is rejected with fencing (
fenced_feeder_session,lease_expired),stale_generation,stale_instance_id(restart),graph_desynchronized/source_epoch_mismatch, orunverifiable_duplicate, identical replay cannot resolve the outcome. The caller must use the existing recovery paths: re-establish the session, or re-import a baseline (replacement import, or create-only after restart) and continue from its position.
Retry and reconciliation decisions are specified in §9.4.
Admission codes (v1.0.0). An exhausted feeder admission lane answers
503 busy on every route of that lane (data lane: events, barrier, gap;
control lane: session, heartbeat), as /v1/operations and /v1/batch do for
the shared lane. 503 import_in_progress is returned only by
/v1/feeder/import while another import holds the import permit. Until
v0.9.x the two feeder lanes also answered import_in_progress; the change is
an approved exception (compatibility).
Tests: feeder_admission.rs.
9.4 Retry and Reconciliation Decision Table (v0.3.0 M3.3)
M3.3 uses the existing protocol only: no new endpoint, response field, persisted cursor or exactly-once guarantee. Two different actions must not be confused:
- Exact retry resends the identical events (same
event_id, delivery sequence and predecessor, source position and predecessor, op and operands) under the sameinstance_id,generation,source_idandsource_epoch, and a currently valid feeder session/epoch. The retained window makes it idempotent: applied events return as exact duplicates and only missing events are applied. Any change to event identity or payload is not a retry. - Correction replaces an event the server explicitly reported as failed and
unapplied (
failed_delivery_sequenceor a single-event rejection) with a different event at the same sequence. Rejected events are not retained (§9.2), so this is accepted. It is never safe after a timeout or lost response: if the original was applied, the corrected event is aconflicting_duplicateand desynchronizes the graph.
The server never decides that an event can be skipped. A caller must not skip
events because applied_delivery_sequence, source_position, counts or
generation appear to cover them; it resends them exactly and lets
deduplication decide. The frontier in a response body or its version headers is
captured under the graph lock for that request. A separate GET /v1/stats
read is only a point-in-time snapshot (§9.3, Uncertain outcomes).
| Case | Caller knows | Still uncertain | Exact retry? | Must stay unchanged | Next step |
|---|---|---|---|---|---|
Rejection before admission (validation, instance, mode, 503 busy lane capacity, 503 unavailable) |
Nothing from this request was applied | Nothing about this request | Yes, after fixing the request if it was malformed | Everything, unless correcting the rejected request itself | Resubmit |
200 applied |
Every event of the request is applied in memory, frontier = response frontier | External durability (none locally) | Not needed; harmless while retained | — | Continue at applied_delivery_sequence + 1 |
Partial failure, domain error (422 event_failed) or sequence gap (409 out_of_order_sequence) |
Prefix ≤ applied_delivery_sequence applied; failed and later events not applied |
Nothing for this request | Yes for the whole request: the prefix deduplicates. A domain error recurs unless the state or event changes | Prefix events; instance, generation, source, session | Correct or resend from failed_delivery_sequence |
Timeout (503 request_timeout) or lost response after admission |
Request was admitted | Whether and when the worker runs, and how far it gets; whether it applied anything | Yes, only if identities, ownership and window retention still hold | All events and identities | Exact retry; a newer-state retry and the late worker both deduplicate. Never correct or skip |
Exact retained duplicate (200 duplicate, or skipped inside a 200 applied) |
An identical event was applied earlier in this generation | Which request applied it | Already resolved | — | Continue after the current frontier |
Duplicate outside the window (409 unverifiable_duplicate) |
An event at that sequence was applied earlier | Whether it was this event | No: identical replay cannot resolve it | — | Rebuild by replacement import |
Conflicting duplicate, predecessor mismatch, source_epoch mismatch, or already desynchronized |
The stream diverged from what the graph applied; graph is desynchronized |
— | No | — | Rebuild by replacement import |
Session takeover (409 fenced_feeder_session for the old owner) |
Old owner’s requests not yet executed will be rejected | Whether the old owner’s earlier requests ran before takeover | Old owner: no. New owner: yes, same generation, source and window | Events, instance, generation, source | New owner resumes with exact retries |
Lease expired (409 lease_expired, status stale) |
This request applied nothing | Earlier timed-out requests | Only after registering a higher epoch | Events, instance, generation, source | Re-register; exact retry; barrier proof to return to ready |
Generation change (409 stale_generation) |
Graph was replaced; old-generation events cannot apply | Whether the old event reached the replaced generation | No | — | Read the new generation and its import position; reconcile against the new baseline |
Process restart (409 stale_instance_id) |
All volatile state is gone | Nothing survives to verify | No | — | Rediscover, register, create_only import |
Production guarantees vs. reference-client policy. The guarantees above are
server behavior. The reference client in
tests/common/feeder.rs adds
policy, which other feeders may choose differently:
apply_events_with_recoveryretries only transport errors, at mostmax_retriestimes with bounded backoff (15–200 ms), always with the identical payload and identities, and checks heartbeat ownership before every attempt.- It returns every HTTP rejection, including 503
request_timeoutandpartial_failure, to the caller instead of retrying. It maps restart toStaleInstance, takeover toFenced, lease expiry toLeaseExpired, and replacement, eviction or stream divergence toRecoveryRequired. parse_partial_failurereads the committed prefix from both 422 and 409partial_failureresponses.import_with_reconciliationnever synthesizes a successful import fromGET /v1/statscounts, cursor or generation. It returnsUncertainOutcome,FencedorRecoveryRequired, and the caller rebuilds conditionally (e2e_rebuild.rstest_09,test_16–test_19,test_21).
Coverage.
| Scenario | Tests |
|---|---|
| Committed event with lost acknowledgment | e2e_rebuild.rs test_03 |
| Timed-out worker completing later | events.rs test_11, test_25, and test_27 (the exact retry and a newer cut apply first; the late worker replays nothing) |
| Partial prefix then retry or correction | events.rs test_9, test_10, test_20; e2e_rebuild.rs test_08, and test_22 (409 prefix diagnostics) |
| Exact duplicate after newer events | events.rs test_3, test_27; e2e_rebuild.rs test_04 |
| Deduplication eviction | events.rs test_5; e2e_rebuild.rs test_11 |
| Replacement, restart or takeover before retry | e2e_rebuild.rs test_13, test_14, test_15 (the new owner’s exact retry is deduplicated) |
| Stream divergence requires rebuild | events.rs test_4, test_8, test_23; e2e_rebuild.rs test_23 |
| No-op and progress events | events.rs test_1, test_22; e2e_rebuild.rs test_02 |
| Conservative import reconciliation | e2e_rebuild.rs test_09, test_16–test_19, test_21 |
9.5 Shared Mutation Execution (v0.3.0 M3.4)
M3.4 found that the graph mutation semantics are already shared, and made no
production change. Every mutation path calls the same ConnectivityGraph
methods in knotrel-core (since v0.5.0 through the server’s ServiceGraph,
which dispatches to LifecycleGraph instead when lifecycle support is
enabled; that facade keeps the same limit, self-loop and no-op rules) (add_node, link, cut in
configuration.rs). Those methods
own the node/edge limit checks and their precedence, self-loop rejection,
no-mutation-on-error, and effective-change detection (the returned bool).
Revision arithmetic is the single GraphState::increment_version. What differs
per endpoint is policy, and stays separate on purpose.
| Stage | POST /v1/operations |
POST /v1/batch |
POST /v1/feeder/events |
|---|---|---|---|
| Parsing and mode | api.rs single: Operation; mutations rejected 409 direct_mutation_disabled in source-managed mode |
api.rs batch: mode check, then 1..=MAX_BATCH_OPERATIONS size check |
api.rs feeder_events: instance header and body, graph_id, availability; source-managed only |
| Admission and worker | Service::execute → Service::run: permit, track_job, spawn_blocking, panic guard |
Same as single | Service::execute_feeder_worker: same permit, tracking and panic guard, plus readiness publication under the lock |
| Lock scope | One graph-lock acquisition per request | One acquisition for the whole batch | One acquisition for the whole request |
| Pre-execution state checks | Source-managed: uninitialized, loading or desynchronized → per-item error | Same as single | Session, epoch, lease, generation, desynchronization, source lineage, whole-request validation (§9.3) |
| Mutation dispatch | Operation::apply (api.rs) → core |
Same as single, per item | Inline CanonicalOp match in GraphState::apply_events → core |
| Graph limits, self-loop, change detection | Core | Core | Core (plus a redundant feeder self-loop pre-check that keeps its message text) |
| Revision | GraphState::apply: increment_version iff changed |
Same, per effective item | increment_version iff changed, after the event is accepted |
| Domain error policy | 422 (404 unknown_node for queries and lifecycle setters, 404 unknown_edge for set_edge_enabled) |
Per-item error; execution continues; no rollback (ADR 0013) | Stop at the first failure; 422 domain code, or partial_failure with the applied prefix (§9.3) |
| Frontier and deduplication | — | — | Sequence and position advance for every applied event, including no-ops and progress; window records applied events only |
| Response metadata | response_metadata captured under the lock |
Same | Same function, captured under the lock for success, duplicate and partial failure |
| Error mapping | Outcome::from(GraphError), service_error |
Same | Feeder (code, message) mapping and feeder_error |
Verified equivalence. events.rs test_28 runs one script through all three
endpoints under identical limits and checks every outcome and the final revision
and topology against an independently written expected table. The script covers
effective and no-op add_node/link/cut, self-loop link/cut, node and edge
limits on link, the node limit on add_node, and cut of an absent edge. Single
operations and the batch report identical results; each feeder event reports the
same code or revision change, and also advances the frontier on no-ops.
Recorded maintenance risk (no current defect). The feeder dispatcher duplicates
the server-level GraphError → code mapping with endpoint-specific message text
and catch-all fallbacks (invalid_node, invalid_edge). Today those fallbacks
are unreachable for every error core can return. The cut self-loop case
reaches them only if the feeder’s pre-check is removed. A future core error would
silently take a different code on each path. test_28 detects this for every
scripted case. A small shared GraphError → code function, keeping the feeder’s
message text, would remove the risk without an observable change; it is left for
a separate decision. The same catch-all pattern exists in candidate import
validation, which is outside M3.4. The two worker wrappers (run,
execute_feeder_worker) are also similar but differ in readiness publication and
failure marking; merging them would change worker ownership and is not proposed.
9.6 Node and Edge Lifecycle Events and Imports (v0.5.0 M10)
With KNOTREL_TOPOLOGY_LIFECYCLE=true (supported only with
KNOTREL_ENGINE=compact-bfs in v0.5.0) the source can describe registered
topology with flags (contract: topology-lifecycle.md;
wire shapes: HTTP API). The
protocol above is unchanged; this section records what lifecycle support adds.
Events. set_node_active (node, active), set_edge_enabled
(source, target, enabled) and remove_node (node) are ordinary
ordered events: same envelope, sequence and predecessor checks, frontier
advance on every applied event (including no-ops), one state_version
increment per changed event whatever the number of incident edges, and
fail-fast failure matrix (§9.3). Domain errors are 422 with unknown_node,
unknown_edge or self_loop (single event) or partial_failure /
event_failed (multi-event). remove_node of an absent node is an applied
no-op.
Duplicate fingerprint. The canonical descriptor (§7.1) includes the
operation type and the flag value, so an exact retry deduplicates and a retry
that changes either is conflicting_duplicate.
Stale events cannot resurrect removed topology. An event is applied only
at D_applied + 1 after the predecessor checks. Any older event is either
answered from the retained window without being applied (exact duplicate),
rejected as conflicting_duplicate, or rejected as unverifiable_duplicate
once evicted; a later sequence is out_of_order_sequence. A delayed retry of
an event preceding a remove_node therefore never re-registers the removed
node or its edges. Only a new in-order add_node or link registers the ID
again, as a fresh active node with no edges.
Imports carry complete registered topology. A rebuild import must contain
every registered node and edge with its flags, including isolated nodes,
inactive nodes and disabled edges; anything omitted is simply absent from the
new generation. nodes entries are a node ID string (active) or
{"node", "active"}; edges entries take an optional enabled (default
true). Repeated entries must agree, otherwise 422 invalid_node or
invalid_edge. Legacy payloads (strings only, no enabled) are unchanged and
mean all active, all enabled, so a source that tracks flags must send them on
every rebuild.
Lifecycle support off.
- Events: any
set_node_active,set_edge_enabledorremove_nodeevent rejects the whole request with 409topology_lifecycle_disabled. The check occupies the existing per-event prevalidation slot under the graph lock (after session, generation and source checks, before any event is applied), in event order together withinvalid_request. It is counted inknotrel_feeder_rejections_total{code="topology_lifecycle_disabled"}. - Imports: any node object or any
enabledmember, even with the default value, rejects the import with 409topology_lifecycle_disabledin the payload phase (after JSON parsing and theinstance_id/graph_idchecks, before candidate construction and the graph-lock request). It is classified aspayload_rejectedinknotrel_imports_total. activeorenabledonadd_node,link,cutorprogressis 422invalid_requestwhatever the setting.
10. HTTP Interface Specification
[!NOTE] Every endpoint in this section is implemented (since v0.2.x). The request and response schemas, statuses and error codes of record are in openapi.yaml; this section explains them with examples.
10.1 Feeder Session Registration
- Endpoint:
POST /v1/feeder/session - Headers:
X-Knotrel-Instance-Id: <instance_id>
Request Example:
{
"instance_id": "srv-550e8400-e29b-41d4-a716-446655440000",
"feeder_session_id": "feeder-node-a-uuid",
"feeder_epoch": 1,
"lease_duration_ms": 10000
}
Success Response (200 OK):
{
"result": "session_acquired",
"instance_id": "srv-550e8400-e29b-41d4-a716-446655440000",
"feeder_session_id": "feeder-node-a-uuid",
"feeder_epoch": 1,
"lease_duration_ms": 10000,
"generation": 0,
"applied_delivery_sequence": 0,
"applied_source_position": null,
"status": "uninitialized"
}
10.2 Feeder Heartbeat
- Endpoint:
POST /v1/feeder/heartbeat - Headers:
X-Knotrel-Instance-Id: <instance_id>
Request Example:
{
"instance_id": "srv-550e8400-e29b-41d4-a716-446655440000",
"feeder_session_id": "feeder-node-a-uuid",
"feeder_epoch": 1
}
Success Response (200 OK):
{
"result": "heartbeat_acknowledged",
"instance_id": "srv-550e8400-e29b-41d4-a716-446655440000",
"feeder_session_id": "feeder-node-a-uuid",
"feeder_epoch": 1,
"lease_expires_in_ms": 10000,
"status": "ready"
}
10.3 Atomic Graph Import
- Endpoint:
POST /v1/feeder/import - Headers:
X-Knotrel-Instance-Id: <instance_id>
If-Match: "1.45.0%2F16B3800"(mandatory whenmode: "replace")
Request Example:
{
"mode": "create_only",
"instance_id": "srv-550e8400-e29b-41d4-a716-446655440000",
"graph_id": "default",
"source_id": "postgres-cluster-01",
"source_epoch": "epoch-2026-10-19",
"source_position": "0/16B3740",
"feeder_session_id": "feeder-node-a-uuid",
"feeder_epoch": 1,
"nodes": [
"1", "2", "3", "4", "5", "100"
],
"edges": [
{"source": "1", "target": "2"},
{"source": "2", "target": "3"},
{"source": "4", "target": "5"}
]
}
Success Response (201 Created):
{
"result": "published",
"instance_id": "srv-550e8400-e29b-41d4-a716-446655440000",
"graph_id": "default",
"generation": 1,
"state_version": "0",
"node_count": 6,
"edge_count": 3,
"source_position": "0/16B3740",
"status": "catching_up"
}
10.4 Ordered Incremental Events (Including Progress Events)
- Endpoint:
POST /v1/feeder/events - Headers:
X-Knotrel-Instance-Id: <instance_id>
Request Example (Batch Starting at Sequence 101):
{
"instance_id": "srv-550e8400-e29b-41d4-a716-446655440000",
"graph_id": "default",
"generation": 1,
"feeder_session_id": "feeder-node-a-uuid",
"feeder_epoch": 1,
"source_id": "postgres-cluster-01",
"source_epoch": "epoch-2026-10-19",
"events": [
{
"event_id": "evt-8801",
"delivery_sequence": 101,
"prev_delivery_sequence": 100,
"source_position": "0/16B3758",
"prev_source_position": "0/16B3740",
"op": "link",
"source": "3",
"target": "4"
},
{
"event_id": "prog-8802",
"delivery_sequence": 102,
"prev_delivery_sequence": 101,
"source_position": "0/16B3800",
"prev_source_position": "0/16B3758",
"op": "progress"
}
]
}
Success Response (200 OK):
{
"result": "applied",
"instance_id": "srv-550e8400-e29b-41d4-a716-446655440000",
"generation": 1,
"applied_delivery_sequence": 102,
"applied_source_position": "0/16B3800",
"state_version": "1",
"events_applied": 2
}
Duplicate Event Response (200 OK):
{
"result": "duplicate",
"status": "already_applied",
"instance_id": "srv-550e8400-e29b-41d4-a716-446655440000",
"generation": 1,
"event_id": "evt-8801",
"delivery_sequence": 101,
"historical_outcome": {
"changed": true
},
"current_applied_delivery_sequence": 102,
"current_applied_source_position": "0/16B3800",
"current_state_version": "1"
}
10.5 Synchronization Barrier Declaration (Verification-Only)
- Endpoint:
POST /v1/feeder/barrier - Headers:
X-Knotrel-Instance-Id: <instance_id>
Request Example:
{
"instance_id": "srv-550e8400-e29b-41d4-a716-446655440000",
"graph_id": "default",
"generation": 1,
"feeder_session_id": "feeder-node-a-uuid",
"feeder_epoch": 1,
"barrier_delivery_sequence": 102,
"barrier_source_position": "0/16B3800"
}
Success Response (200 OK):
{
"result": "synchronized",
"instance_id": "srv-550e8400-e29b-41d4-a716-446655440000",
"graph_id": "default",
"generation": 1,
"state_version": "1",
"applied_source_position": "0/16B3800",
"status": "ready"
}
10.6 Declaring Irreparable Source Gap
- Endpoint:
POST /v1/feeder/gap - Headers:
X-Knotrel-Instance-Id: <instance_id>
Request Example:
{
"instance_id": "srv-550e8400-e29b-41d4-a716-446655440000",
"graph_id": "default",
"generation": 1,
"feeder_session_id": "feeder-node-a-uuid",
"feeder_epoch": 1,
"failed_delivery_sequence": 103,
"reason": "source CDC history expired before catch-up completed"
}
Success Response (200 OK):
{
"result": "gap_acknowledged",
"instance_id": "srv-550e8400-e29b-41d4-a716-446655440000",
"generation": 1,
"status": "desynchronized",
"action_required": "full_rebuild_required"
}
11. Deterministic Acceptance-Test Specification
This test matrix defines reproducible, deterministic test traces for the future v0.2.0 implementation. Every test specifies input sequence, controlled synchronization points, version tuples, and failure oracles.
11.1 Deterministic Test Traces
| Test ID | Scenario Description | Initial State | Inputs & Controlled Interleaving Protocol | Expected Final State & Output Oracle |
|---|---|---|---|---|
| TR-01 | Happy Path: Image $S \to$ Catch-up $\to$ Barrier $B$ | Uninitialized (gen=0) |
1. POST /v1/feeder/session (epoch=1)2. POST /v1/feeder/import (mode: "create_only", $S=\text{“pos-10”}$, 3 nodes, 2 edges)3. POST /v1/feeder/events ($D=1, P=\text{“pos-11”}$, link 3-4)4. POST /v1/feeder/barrier ($B=\text{“pos-11”}$, $D=1$) |
State: Uninitialized $\to$ Loading $\to$ CatchingUp $\to$ Ready.Final tuple: (gen=1, state_version="1", applied_pos="pos-11").GET /ready returns 200 ready. |
| TR-02 | Stale Instance ID Rejection | Ready on inst_B |
1. Feeder sends request with X-Knotrel-Instance-Id: inst_A |
Request rejected: 409 Conflict (code: "stale_instance_id").State remains intact on inst_B. |
| TR-03 | Exact Duplicate Event Retry | CatchingUp ($D_{applied}=1$, event evt-1) |
1. POST /v1/feeder/events (resend evt-1, $D=1$, link 3-4) |
Response: 200 OK (status: "already_applied").state_version does not increment.D_{applied} remains 1. |
| TR-04 | Conflicting Duplicate Event | CatchingUp ($D_{applied}=1$, event evt-1, link 3-4) |
1. POST /v1/feeder/events (same evt-1, $D=1$, but payload cut 1-2) |
Request rejected: 409 Conflict (code: "conflicting_duplicate").State transitions to Desynchronized; stream halted. |
| TR-05 | Transient Out-of-Order Sequence ($D > D_{applied}+1$) | CatchingUp ($D_{applied}=1$) |
1. Feeder sends event with $D=3$. 2. Server responds with 409. 3. Feeder sends event $D=2$. 4. Feeder resends event $D=3$. |
Step 1 yields 409 out_of_order_sequence (expected_sequence: 2). State stays CatchingUp.Step 3 yields 200 applied ($D_{applied}=2$).Step 4 yields 200 applied ($D_{applied}=3$). |
| TR-06 | No-Op Event Advances Source Position | Ready ($D_{applied}=1, P=\text{“pos-11”}$, edge 1-2 exists) |
1. POST /v1/feeder/events ($D=2, P=\text{“pos-12”}$, link 1-2) |
Response: 200 OK (result: "applied").applied_source_position advances to "pos-12".state_version remains unchanged. |
| TR-07 | Worker Timeout with Controlled Interleaving | CatchingUp ($D_{applied}=1$) |
1. Install WorkerPauseHandle on worker 1.2. Client sends event $D=2$, admitted to worker. 3. Advance virtual clock past KNOTREL_REQUEST_TIMEOUT_MS $\to$ client observes 503.4. Release worker 1 to complete under mutex. 5. Client retries event $D=2$ with same event_id. |
Step 3 yields 503 request_timeout.Step 4 worker completes under mutex: $D_{applied}=2$. Step 5 retry hits deduplication window $\to$ returns 200 already_applied. |
| TR-08 | Replacement During Catch-up with Controlled Lock Boundary | CatchingUp (gen 1, $D_{applied}=1$) |
1. Worker 1 parses candidate replacement graph (gen 2) off-lock. 2. Worker 2 enqueues event for gen 1 ($D=2$). 3. Worker 1 acquires lock, swaps pointer, sets gen 2, releases lock. 4. Worker 2 acquires lock, checks generation. |
Worker 1 publishes gen 2. Worker 2 fails under mutex: 409 Conflict (code: "stale_generation").Live state belongs cleanly to gen 2. |
| TR-09 | Fenced Stale Feeder Under Mutex Check | Ready (gen 1, feeder_epoch=2) |
1. Stale feeder sends POST /v1/feeder/events (feeder_epoch=1).2. Request reaches service validation under mutex. |
Request rejected: 409 Conflict (code: "fenced_feeder_session").Validated under service boundary before graph execution; live state intact. |
| TR-10 | Source Epoch Reset / Failover | Ready (epoch "ep-1") |
1. Feeder sends POST /v1/feeder/events (epoch "ep-2", $D=2$) |
Request rejected: 409 Conflict (code: "source_epoch_mismatch").State transitions to Desynchronized. Requires full rebuild. |
| TR-11 | Feeder Lease Expiration and Stale Readiness | Ready (lease 10s) |
1. Stop feeder heartbeats. 2. Advance virtual clock by 10,001 ms. 3. Probe GET /ready.4. Send heartbeat. 5. Probe GET /ready. |
Step 3 returns 503 Service Unavailable (status: "stale").Step 4 heartbeat returns 200 heartbeat_acknowledged.Step 5 probe remains 503 status: "stale" until synchronization barrier is verified (§4.3). |
| TR-12 | Process Restart and Full Rebuild | Ready (gen 1, 1000 nodes) |
1. Send SIGTERM; server exits clean. 2. Start new Knotrel process. 3. Old feeder sends gen 1 event with old instance_id. |
Step 2 new process starts with new instance_id, gen=0, state Uninitialized.Step 3 rejected: 409 Conflict (stale_instance_id).Feeder discovers new instance_id and performs full import. |
| TR-13 | Direct Mutation Rejection in Source-Managed Mode | Mode: source_managed, Ready |
1. POST /v1/operations (link 1-2)2. POST /v1/batch (contains 1 link, 1 query) |
1. Rejected: 409 Conflict (direct_mutation_disabled).2. Rejected: 409 Conflict (direct_mutation_disabled).Graph topology unmodified. |
| TR-14 | Standalone Mode Backward Compatibility | Mode: standalone (default) |
1. POST /v1/operations (link 1-2)2. POST /v1/batch (mixed ops with domain error) |
1. Succeeds: 200 OK, changed: true.2. Succeeds: 200 OK, continue-on-error behavior verified.state_version increments identically to v0.1.0. |
| TR-15 | Equal Barrier Sequence with Mismatching Position | CatchingUp ($D_{applied}=10, P_{applied}=\text{“0/16B3800”}$) |
1. Feeder sends POST /v1/feeder/barrier ($D=10, P=\text{“0/16B9999”}$). |
Rejected under decision table case B7: 409 Conflict (code: "barrier_position_mismatch").State remains CatchingUp; cursor untouched. |
| TR-16 | Progress Event Retry and Conflicting Retry | CatchingUp ($D_{applied}=5, P=\text{“pos-10”}$) |
1. Send progress event ($D=6, P=\text{“pos-11”}$).2. Resend exact progress event.3. Send same ID with conflicting position. |
Step 1 applies: $D_{applied}=6, P=\text{“pos-11”}$, version unchanged. Step 2 returns 200 already_applied.Step 3 returns 409 conflicting_duplicate $\to$ Desynchronized. |
| TR-17 | Heartbeat After Lease Expiry While Updates Remain Unapplied | Disconnected/Stale (lease expired, source has new events) |
1. Send heartbeat POST /v1/feeder/heartbeat.2. Probe GET /ready.3. Send events up to $B$ and call barrier. |
Step 1 returns 200 heartbeat_acknowledged.Step 2 returns 503 stale (proves heartbeat does not bypass catch-up).Step 3 verifies barrier $\to$ /ready returns 200 ready. |
| TR-18 | Heartbeat During Desynchronized and CatchingUp | Desynchronized (epoch mismatch) |
1. Send heartbeat POST /v1/feeder/heartbeat.2. Probe GET /ready. |
Step 1 returns 200 (lease extended). Step 2 probe remains 503 status: "desynchronized" (heartbeat never clears failure). |
| TR-19 | Session Takeover Pausing Candidate Import Before Publication | CatchingUp (Feeder A, epoch=1) |
1. Feeder A begins building candidate import off-lock. 2. Feeder B takes over: POST /v1/feeder/session (epoch=2).3. Feeder A candidate build completes and acquires lock for publication. |
Step 2 updates live.feeder_epoch = 2.Step 3 under lock rechecks epoch: Feeder A ( epoch=1) rejected with 409 fenced_feeder_session. Candidate discarded. |
| TR-20 | Sequence Continuity with Incorrect Source Predecessor | CatchingUp ($D_{applied}=1, P_{applied}=\text{“pos-10”}$) |
1. Feeder sends event with $D=2, D_{prev}=1$, but prev_source_position: "pos-WRONG". |
Rejected under mutex: 409 Conflict (source_predecessor_mismatch).State transitions to Desynchronized. Graph unchanged. |
| TR-21 | Hash Collision Handling with 256-Byte Cursor | CatchingUp |
1. Fabricate two events with same SipHash but different 256-byte source_position strings. |
Tier 2 full string comparison detects mismatch; entry treated as cache miss, preventing false deduplication. |
| TR-22 | Partial Batch Beginning at Non-Trivial Global Sequence | CatchingUp ($D_{applied}=100$) |
1. Send batch with 3 events: $D=101$ (valid), $D=102$ (valid), $D=103$ (self-loop). | Events 101 and 102 applied ($D_{applied}=102$). Response returns 422 partial_failure (failed_batch_index: 2, failed_delivery_sequence: 103). |
| TR-23 | Declared Source History Loss via /v1/feeder/gap |
CatchingUp ($D_{applied}=5$) |
1. Feeder calls POST /v1/feeder/gap (failed_delivery_sequence: 6). |
Server acknowledges gap (200 gap_acknowledged).State transitions to Desynchronized. Queries fail with 503. |
| TR-24 | Older Barrier with Different Position (Superseded Case B9) | Ready ($D_{applied}=20, P_{applied}=\text{“0/16B5000”}$) |
1. Feeder sends delayed barrier ($D=10, P=\text{“0/16B3000”}$). | Rejected under decision table case B9: 409 Conflict (code: "superseded_barrier").State remains Ready; cursor remains at 20. |
| TR-25 | Rejected Barriers Preserving Ready, Stale, and Desynchronized | Test across 3 distinct server states | 1. State Ready: send premature barrier ($D=50$).2. State Stale: send mismatched position barrier ($P=\text{“bad”}$).3. State Desynchronized: send exact matching barrier. |
1. Returns 409 barrier_not_reached; state stays Ready.2. Returns 409 barrier_position_mismatch; state stays Stale.3. Returns 409 graph_desynchronized; state stays Desynchronized. |
| TR-26 | Rejected Event Retry vs. Committed-Event Conflict | Initial: $D_{applied}=100$ | 1. Event $D=101$ (evt-1, self-loop) fails with 422.2. Resend sequence 101 with corrected link. 3. Event 101 commits ($D_{applied}=101$). 4. Resend committed evt-1 with altered cut. |
Step 1 uncommitted $\to$ not in dedup window. Step 2 succeeds: 200 applied ($D_{applied}=101$).Step 4 resends committed ID with altered content $\to$ 409 conflicting_duplicate $\to$ Desynchronized. |
| TR-27 | Required Mutation Failure Cannot Be Bypassed with Progress | Graph at edge capacity ceiling (remaining_edges: 0) |
1. Event $D=50$ (link 1-2) fails with 422 edge_limit_exceeded.2. Feeder attempts to bypass by emitting event $D=50$ as op: "progress". |
Stream progress is halted at 49. Feeder is strictly forbidden from substituting progress for failed required mutations. Feeder must either halt and declare gap via /v1/feeder/gap or operator increases limits. |
| TR-28 | Import Precondition Failure (412) vs. Ownership Fencing (409) | Mode: source_managed, Ready (gen 1, epoch 1) |
1. Call import with stale feeder epoch 0. 2. Call import with valid epoch 1 but mismatched If-Match: "1.99.pos". |
Step 1 fails fencing: 409 Conflict (fenced_feeder_session).Step 2 passes fencing but fails precondition: 412 Precondition Failed (precondition_failed). Live graph untouched. |
| TR-29 | Exact Barrier Match While Uninitialized | Uninitialized ($g=0, D_{app}=0, P_{app}=\text{null}$) |
1. Feeder sends POST /v1/feeder/barrier ($D=0, P=\text{null}$). |
Rejected under Case B3: 409 Conflict (code: "graph_uninitialized").State remains Uninitialized. No barrier may make an unpublished initial graph Ready. |
| TR-30 | Barrier During Initial Baseline Loading | Loading ($g=0$, candidate parsing off-lock) |
1. Feeder sends POST /v1/feeder/barrier ($D=0$ or matching candidate snapshot $S$). |
Rejected under Case B4: 409 Conflict (code: "graph_uninitialized").State remains Loading; candidate remains unpublished. |
| TR-31 | Barrier During Replacement Loading | Ready (live $g=1, D_{app}=10$), candidate $g=2$ parsing off-lock |
1. Feeder sends barrier for candidate gen=2 ($D=0$).2. Feeder sends barrier for live gen=1 ($D=10, P=P_{live}$). |
Step 1 rejected: 409 Conflict (stale_generation); live $g=1$ untouched.Step 2 accepted under Case B2: 200 already_synchronized; live $g=1$ remains Ready. |
| TR-32 | Retained Committed Sequence with Different Event ID | CatchingUp ($D_{applied}=5$, seq 5 committed with evt-05) |
1. Feeder sends POST /v1/feeder/events ($D=5, \text{event_id: “evt-99”}$). |
Ring buffer sequence check fails: evt-99 != evt-05.Rejected: 409 Conflict (code: "conflicting_duplicate"). State transitions to Desynchronized. |
| TR-33 | Retained Event ID Reused at New Sequence | CatchingUp ($D_{applied}=5$, evt-03 committed at seq 3) |
1. Feeder sends POST /v1/feeder/events ($D=6, D_{prev}=5, \text{event_id: “evt-03”}$). |
Event ID hash index check detects reuse of evt-03.Rejected: 409 Conflict (code: "conflicting_duplicate"). State transitions to Desynchronized. |
| TR-34 | Evicted History Boundaries | Window $N=10$, $D_{applied}=15$ ($D_{win}=6$). evt-04 at seq 4 is evicted. |
1. Feeder resends sequence $D=4$ (evt-04).2. Feeder sends new sequence $D=16$ reusing evt-04. |
Step 1: $D=4 < D_{win} \to$ rejected: 409 Conflict (unverifiable_duplicate), state unchanged.Step 2: evt-04 evicted $> N$ events ago; cannot be detected by bounded window $\to$ evaluated fresh at $D=16$ and succeeds (200 applied, $D_{applied}=16$). |
12. Resolution of Roadmap Decisions D1–D6
This section documents the formal architectural decisions resolving items D1–D6 from historical planning record.
Decision D1: Identity and Ownership
| Category | Details |
|---|---|
| Context | Knotrel needs stable identity and fencing tokens to prevent split-brain updates, cross-graph contamination, and resurrection of stale versions after restart. |
| Alternatives Considered | 1. Dynamic Multi-Graph Routing: Add per-request graph URI routing (/graphs/{id}/...). Rejected: unmeasured complexity, contradicts single-graph accelerator scope.2. Opaque Timestamps as Versions: Use wall-clock timestamps for generation/revision. Rejected: non-monotonic clock skew, breaks deterministic testing. 3. Strict Token Hierarchy with Instance Scoping (Recommended): Explicit tuple (instance_id, graph_id, generation, state_version, source_id, source_epoch, applied_source_position, feeder_session_id, feeder_epoch). Mandatory instance_id in headers. |
| Recommended Design | Adopt Alternative 3. Single implicit graph (graph_id: "default"). Monotonic generation ($1, 2, \dots$) increments on each atomic import. Existing arbitrary-precision decimal state_version increments on topological changes. Monotonic feeder_epoch fences stale feeders. |
| Compatibility | 100% compatible with v0.1.0 standalone mode (where generation is 0 and existing decimal revision rules apply). |
| Correctness & Security | Eliminates stale feeder races and cross-generation update application across restarts. |
| Residual Questions for Maintainer | Confirm default graph_id string ("default"). |
Decision D2: Modes and Acknowledgment
| Category | Details |
|---|---|
| Context | Direct uncoordinated writes in source-managed mode would desynchronize the in-memory graph from the authoritative database, invalidating the applied cursor. |
| Alternatives Considered | 1. Permissive Dual-Mode: Allow direct writes and attempt to advance an artificial cursor. Rejected: guarantees silent divergence from external source. 2. Synchronous Source Write-Through: Knotrel calls the external DB to write changes before applying. Rejected: turns Knotrel into a distributed transaction coordinator, violating acceleration goals. 3. Strict Mode Segregation (Recommended): Explicit startup flag KNOTREL_MODE. Standalone mode accepts legacy writes. Source-managed mode strictly rejects mutating /v1/operations and /v1/batch with HTTP 409 direct_mutation_disabled. Acknowledgment certifies in-memory application only; durability disclaimer is explicit. |
| Recommended Design | Adopt Alternative 3. Maintain complete separation of concerns. In source-managed mode, direct mutations fail fast. |
| Compatibility | Standalone mode remains the default with unchanged v0.1.0 semantics. |
| Correctness & Security | Guarantees that in source-managed mode, Knotrel is a faithful projection of the verified source prefix. |
| Residual Questions for Maintainer | Confirm HTTP 409 Conflict vs HTTP 403 Forbidden for direct mutation rejection. |
Decision D3: Ordering and Retry
| Category | Details |
|---|---|
| Context | External source cursors (e.g. Postgres LSNs, Kafka partition offsets, alphanumeric composite tokens) cannot be assumed to be contiguous integers. Knotrel needs a source-independent continuity protocol. |
| Alternatives Considered | 1. Contiguous Integer Cursor Assumption: Force external systems to provide 1, 2, 3… cursors. Rejected: incompatible with standard enterprise databases and Kafka. 2. Lexicographical Cursor Comparison: Compare arbitrary string cursors. Rejected: incorrect for non-fixed-width numbers or complex structures. 3. Transport Delivery Sequence + Bounded Deduplication Evaluated Under Mutex (Recommended): Feeder supplies strictly contiguous delivery_sequence ($1, 2, 3, \dots$) and prev_delivery_sequence alongside opaque source cursor strings. Under the graph mutex, requests are classified as: previous sequence (checked in bounded deduplication window with exact canonical equality), expected next sequence (executed), or future sequence (rejected as out_of_order_sequence). Feeder events use stop-on-first-error semantics. |
| Recommended Design | Adopt Alternative 3. Feeder owns cursor interpretation and ordering; Knotrel enforces transport sequence continuity, predecessor match, and bounded duplicate rejection under the lock via a dual-index window (sequence ring buffer and event ID hash index). Knotrel strictly differentiates exact retries (200 OK) from conflicting duplicates (409 Conflict -> Desynchronized) across both sequence reuse and event ID reuse within the active N-entry horizon, while conservatively returning 409 unverifiable_duplicate for evicted sequences. |
| Compatibility | Legacy /v1/batch error continuation is preserved for standalone mode. Feeder endpoints use their own strict fail-fast ordering contract. |
| Correctness & Security | Completely prevents gaps, reordering anomalies, cross-sequence event ID duplication, and false deduplication claims. |
| Residual Questions for Maintainer | Approve proposed default bounded duplicate window size (10,000 entries) with exact dual-index memory accounting requirements. |
Decision D4: Capacity and Freshness
| Category | Details |
|---|---|
| Context | Graph memory must be bounded, and operators must know whether queries reflect current source state without inventing unsupported numerical freshness SLOs. |
| Alternatives Considered | 1. Arbitrary Real-Time SLO: Declare that lag $< 100\text{ ms}$ is ready. Rejected: arbitrary, unverifiable without synchronized distributed clocks. 2. Silent Serving During Disconnect: Continue reporting 200 Ready indefinitely when the feeder drops. Rejected: violates rule that divergent graphs must not be reported synchronized. 3. Explicit Lease-Driven State Machine with Degradation Headers (Recommended): Feeder renews lease via heartbeats against a monotonic clock. Heartbeat renews lease but does not restore Ready without synchronization proof. Discrete states: CatchingUp, Ready, Stale, Desynchronized. Bounded import body (proposed default: 64 MiB). On lease expiry, readiness drops to 503 by default; if KNOTREL_SERVE_STALE=true, queries succeed but carry X-Knotrel-Sync-Status: stale. Declared gaps always force Desynchronized. |
| Recommended Design | Adopt Alternative 3. Enforce deterministic state transitions without inventing unsupported millisecond promises. |
| Compatibility | Standalone mode retains existing cardinality limits (KNOTREL_MAX_NODES, KNOTREL_MAX_EDGES) and fixed 1 MiB body limit. |
| Correctness & Security | Ensures operators and downstream clients are never misled about data currency. |
| Residual Questions for Maintainer | Confirm proposed default import payload bound (64 MiB) and default KNOTREL_SERVE_STALE setting (default false). |
Decision D5: Import and Publication
| Category | Details |
|---|---|
| Context | How should initial baseline images be loaded, and how should replacement images be applied without corrupting live query state? |
| Alternatives Considered | 1. Streaming Chunked Import: Stream nodes/edges over chunked HTTP. Deferred: high protocol complexity for initial v0.2.0. 2. In-Place Mutation: Mutate the live graph directly during import. Rejected: queries observe half-loaded graphs; failure leaves corrupt state. 3. Offline Candidate Build + Atomic Swap with Mandatory Composite Precondition (Recommended): Parse and build candidate ConnectivityGraph entirely outside the live lock. Concurrency bounded to 1. Acquire graph lock. For create_only, verify generation == 0. For replace, verify mandatory If-Match: "<generation>.<state_version>.<percent_encoded_source_position>". Atomically swap graph pointer, increment generation ($g \to g + 1$), reset state_version to "0", update applied_source_position to $S$, and enter CatchingUp. Failed build leaves live graph untouched. |
| Recommended Design | Adopt Alternative 3. Support both create-only (initial load) and conditional replace via mandatory composite If-Match. Readers never observe partial state. Strictly separate error categories: composite precondition mismatches on If-Match return 412 Precondition Failed (precondition_failed); ownership, fencing, and state errors (create_only when already initialized, stale session epoch, expired lease) return 409 Conflict (graph_already_initialized, fenced_feeder_session, lease_expired). |
| Compatibility | Preserves existing try_from_edges validation rules (duplicate edges are no-ops, self-loops rejected, limits checked). |
| Correctness & Security | Guarantees atomic publication, prevents concurrent update clobbering, and ensures clients unambiguously differentiate HTTP condition evaluation from fencing conflicts. |
| Residual Questions for Maintainer | Confirm composite header syntax If-Match: "<generation>.<state_version>.<percent_encoded_source_position>". |
Decision D6: Trust Boundary
| Category | Details |
|---|---|
| Context | Who is authorized to feed events, replace the graph, or declare barriers? |
| Alternatives Considered | 1. Zero Authentication (v0.1.0 Baseline): Assume trusted private network only. Problematic: rogue or crashed feeder can disrupt production graph. 2. Full Integrated TLS + OAuth2/OIDC RBAC: Build enterprise auth into Knotrel server. Rejected: premature, belongs to v1.0.0 Milestone M8. 3. Partitioned Surfaces + Shared Secret Token (Recommended): Keep loopback default. Partition routes into Query vs Feeder/Admin. Introduce optional KNOTREL_FEEDER_TOKEN (HTTP header X-Knotrel-Feeder-Token) for feeder routes. Require reverse proxy/gateway for non-local or multi-tenant deployment. If untrusted network exposure is required immediately, bring Milestone M8 forward. |
| Recommended Design | Adopt Alternative 3. Provide immediate lightweight protection against rogue feeder writes while preserving minimal dependency footprint. |
| Compatibility | Standalone local testing remains frictionless when token is unset. |
| Correctness & Security | Prevents accidental cross-talk between development tools and production feeder sessions. |
| Residual Questions for Maintainer | Confirm whether KNOTREL_FEEDER_TOKEN should be mandatory when non-loopback binding is enabled in source-managed mode. |
13. Handoff Specification for Feature 0.2.2 (Bounded Atomic HTTP Import)
To enable immediate, unambiguous implementation of Feature 0.2.2 without premature freezing of subsequent features, this section defines the minimal candidate handoff contract pending maintainer approval:
13.1 Implementation Prerequisites
- Startup Mode Support: Implement configuration flag
KNOTREL_MODE(standalonedefault,source-managedopt-in). - Identity Model: Implement
instance_id(opaque string),generation(u64),source_id(String),source_epoch(String),applied_source_position(String), andfeeder_session_id(String). - Endpoint: Implement
POST /v1/feeder/import(enforcingX-Knotrel-Instance-Id). - Import Mode Preconditions & Error Segregation:
- If
mode: "create_only": Server must beUninitialized(generation == 0). Otherwise return409 Conflict(graph_already_initialized). - If
mode: "replace": Mandatory composite preconditionIf-Match: "<gen>.<state_version>.<percent_encoded_source_position>". Server verifies match under mutex. If precondition fields mismatch, return412 Precondition Failed(precondition_failed). If feeder lease/fencing fails, return409 Conflict(fenced_feeder_session/lease_expired).
- If
- Offline Candidate Build & Concurrency Ceiling:
- Single active import permit (
KNOTREL_MAX_CONCURRENT_IMPORTS = 1); excess gets 503import_in_progressbefore reading request body bytes. - Deserialization bounded by
KNOTREL_MAX_IMPORT_BYTES(proposed default: 64 MiB). - Candidate
ConnectivityGraphconstructed in memory on a worker thread. - Enforce existing
try_from_edgesinvariants: deduplicate edges, reject self-loops, enforce cardinality limits (KNOTREL_MAX_NODES,KNOTREL_MAX_EDGES).
- Single active import permit (
- Atomic Publication:
- Acquire exclusive graph lock.
- Recheck feeder lease and preconditions under lock.
- Swap graph pointer, set
generation = generation + 1, resetstate_version = "0", recordapplied_source_position = S. - Transition lifecycle state to
CatchingUp.
- Query Isolation During Rebuild:
- If an existing generation was already serving queries, active queries continue executing against the old graph until the lock acquisition.
- The swap is instantaneous. Readers subsequent to the swap observe the new generation and
CatchingUpstatus.
13.2 Implementation Status: Feature 0.2.3 (Identity, Generation, Revision & Source Position)
Feature 0.2.3 is implemented in knotrel-server:
- Coherent Response Metadata: Query responses (
POST /v1/operations), batch responses (POST /v1/batch), live snapshots (GET /v1/stats), and import publications (POST /v1/feeder/import) capture results and identity/version headers (ETag,X-Knotrel-Instance-Id,X-Knotrel-Graph-Id,X-Knotrel-Generation,X-Knotrel-State-Version,X-Knotrel-Source-Position,X-Knotrel-Sync-Status) under the same graph mutex serialization boundary. - Replacement Preconditions: The composite token
ETag: "<generation>.<state_version>.<percent_encoded_source_position>"is directly reusable as the mandatoryIf-Matchheader on replacement imports. Preconditions become stale upon replacement ($g \to g + 1$) or restart even when numeric revisions and graph topology coincide. - Cursor Representation & Safety: Opaque source cursors are safely RFC 3986 percent-encoded in HTTP headers, preventing header injection and delimiter collisions. Cursors are never interpreted as numbers or compared lexicographically.
- Generation Exhaustion: If generation counter reaches
u64::MAX, subsequent replacements are rejected with HTTP 409generation_exhaustedwithout arithmetic overflow or wrapping, preserving live state, topology, revision, and source lineage. Verified via dedicated service-level test on the real import publication path. - Arbitrary-Precision Decimal Revisions: Multi-digit carries beyond
u64::MAXare preserved without numeric overflow. Verified across real mutation execution (599 -> 600), with duplicate no-ops and domain error rejections preserving the revision. - Response Delivery Coherence: Verified via deterministic test-support synchronization (
pause_next_worker_after_lock) that a query capturing outcome and metadata under the graph lock retains its exact original topology result, generation, revision, cursor, and ETag even when response delivery is paused across a completed replacement publication on the live graph. - Batch Scope: Batch response headers reflect the final coherent state after all operations in the batch complete under continue-on-error.
- Feature Boundaries: Non-mutating source progress (
progressevents) and ordered update streaming belong to Feature 0.2.4; synchronization barrier verification and automated readiness gating belong to Feature 0.2.5.
13.3 Implementation Status: Feature 0.2.4 (Ordered Incremental Updates, Deduplication & Gap Declaration)
Feature 0.2.4 is implemented in knotrel-server:
- Endpoints: Implemented
POST /v1/feeder/events(ordered update streaming & progress events with bounded deduplication and fail-fast batch execution) andPOST /v1/feeder/gap(declared unrepairable gap transitioning toDesynchronized). - Deterministic Dual-Index Deduplication: Implemented
DedupWindowring buffer indexed modulo $N$ with anevent_idshash index.- Retained sequence matching
event_idand canonical payload returns HTTP 200already_applied(result: "duplicate"). - Retained sequence with altered content or differing
event_idreturns HTTP 409conflicting_duplicateand transitions toDesynchronized. - Retained
event_idreused at a new sequence returns HTTP 409conflicting_duplicateand transitions toDesynchronized. - Evicted sequence ($D \le D_{applied} - W$) returns HTTP 409
unverifiable_duplicatepreservingCatchingUp. - Evicted
event_idreused at new sequence is admitted fresh at $D_{applied} + 1$ (TR-34). - Configured via
KNOTREL_DEDUP_WINDOW_SIZE(default: 10,000, bounds: 1 to 1,000,000).
- Retained sequence matching
- Regression Invariant: Applying
link(A, B), followed bycut(A, B), then retrying the oldlink(A, B)event at $D=1$ yields HTTP 200already_appliedwithout modifying graph topology; edge $(A, B)$ strictly remains absent. - Sequence Continuity and Gaps: Contiguous delivery sequence verified ($D_i = D_{prev} + 1$) with initial $D_{prev} == D_{applied}$. Gaps or out-of-order delivery return HTTP 409
gap_detected. - Fail-Fast Batch Semantics: Events are processed sequentially under a single graph mutex acquisition. On first domain error (e.g. self-loop or capacity limit; every feeder domain error is HTTP 422 and there is no 404 feeder outcome, see §9.3), execution stops immediately; already committed prefix remains applied in memory; partial failure reports
failed_batch_index,failed_delivery_sequence,failed_event_id, and current applied frontier. Uncommitted events are not recorded in the deduplication window and can be retried at $D_{applied} + 1$ with corrected payload. - No-Op & Progress Events: No-op mutations and
progressevents advanceapplied_source_positionand delivery sequence without incrementingstate_version. - Sequence Boundary Semantics and Checked Arithmetic: Delivery sequence is bounded to
u64. When $D_{applied} = \text{u64::MAX}$, checked arithmetic (checked_add(1)) prevents integer overflow panics. Because nou64wire payload can represent a value beyondu64::MAX, any incoming wire sequence satisfies $\text{seq} \le D_{applied}$. Retained duplicate retries atu64::MAXreturn HTTP 200already_applied; wrapped sequence zero or evicted sequences return HTTP 409unverifiable_duplicatewithout mutating topology, revision, sequence, or position. The internalSequenceExhaustederror variant serves as a defensive guard for checked arithmetic and is unreachable through theu64wire interface. - Declared Gap & Desynchronized State Event Rejection:
POST /v1/feeder/gaptransitions sync status toDesynchronized. Once desynchronized (via declared gap, conflicting duplicate, predecessor mismatch, or source epoch mismatch), subsequent event submissions are rejected under lock with HTTP 409graph_desynchronizedwithout mutating topology, revision, delivery sequence, source position, or deduplication state. Subsequent queries return HTTP 503desynchronized. Feeder heartbeats renew session lease but probe reportsdesynchronized. Live graph remains intact for diagnostics; recovery requires atomic graph replacement viaPOST /v1/feeder/import. - Feature Boundaries: Synchronization barrier verification (
POST /v1/feeder/barrier), barrier timeout, and automated readiness promotion belong to Feature 0.2.5.
13.4 Implementation Status: Feature 0.2.5 (Synchronization-Aware Bootstrap and Readiness)
Feature 0.2.5 is implemented in knotrel-server:
- Verification-Only Barrier Endpoint: Implemented
POST /v1/feeder/barriervalidating mode, headers (X-Knotrel-Instance-Id), JSON body schema, graph identity ("default"), generation, feeder lease, and worker health under the graph mutex. It strictly executes Decision Table B1 through B9:- Case B1: Exact match ($D_B == D_{applied} \land P_B == P_{applied}$) in
CatchingUporStaletransitions toReady(200 synchronized). - Case B2: Exact match in
ReadyaffirmsReady(200 already_synchronized). - Case B3/B4: Barrier while
Uninitializedor initial baselineLoading($g == 0$) is rejected with HTTP 409graph_uninitialized(no barrier can make an unpublished graphReady). - Case B5: Barrier while
Desynchronizedis rejected with HTTP 409graph_desynchronized(barriers cannot bypass unrepairable gaps or desynchronization). - Case B6: Barrier while
Failedis rejected with HTTP 503unavailable. - Case B7: Position mismatch at equal sequence ($D_B == D_{applied} \land P_B \ne P_{applied}$) is rejected with HTTP 409
barrier_position_mismatch. - Case B8: Premature sequence ($D_B > D_{applied}$) is rejected with HTTP 409
barrier_not_reached. - Case B9: Older sequence ($D_B < D_{applied}$) is conservatively rejected with HTTP 409
superseded_barrier.
- Case B1: Exact match ($D_B == D_{applied} \land P_B == P_{applied}$) in
- Strict Readiness Precedence: Implemented 7-level strict evaluation precedence in
readiness():Permanent Worker Failure(unavailable) >Draining(draining) >Starting(starting) >Uninitialized / Loading(uninitialized/loading) >Desynchronized(desynchronized) >Expired Lease / Stale(stale) >CatchingUp(catching_up) >Ready(ready). - Lock-Free Monotonic Lease Expiry & Coherent Atomic Publication:
GET /readyevaluates lease expiry against host monotonic time without acquiring the graph mutex, reading a single atomic 64-bit word (PublishedReadiness) encoding status (4 bits), publication sequence (16 bits), and lease deadline (44 bits). On observing lease expiry inReady,/readyattempts a lock-free CAS to transition the word toStale. If a concurrent publication (such as a fresh barrier or new epoch) modified the publication sequence or deadline, the CAS safely fails without overwriting newer state. - Heartbeat Non-Regression: Heartbeats (
POST /v1/feeder/heartbeat) extend lease deadline and renew ownership, but if the graph was stale,GET /readyremains HTTP 503staleuntil a barrier verification proves synchronization. Heartbeats never cleardesynchronized,uninitialized,loading,catching_up, or worker panic. - Explicit Recovery-Fencing Across Lease Expiry: To prevent delayed pre-expiry barriers from executing after a heartbeat renewal on the same session/epoch and restoring readiness without fresh proof, Knotrel implements explicit recovery fencing: when lease expiry occurs,
last_expired_epochrecords the expired epoch. Any barrier request submitted underfeeder_epoch <= last_expired_epochis rejected with HTTP 409fenced_feeder_session. Restoration ofReadyfromStalestrictly requires the feeder to register a newly incrementedfeeder_epoch > last_expired_epochand supply fresh barrier proof. - Drain Gate and Shutdown Integration: The existing shutdown gate in
serve()admits requests once and answers with 503shutting_down(/readyreportsdraining). In-flight barrier and event workers complete cleanly within the drain timeout. - Verification Evidence: 21 deterministic integration tests in
crates/knotrel-server/tests/bootstrap.rs(includingtest_20_delayed_barrier_fenced_across_lease_expiryandtest_21_probe_paused_at_expiry_does_not_overwrite_newer_publication) and unit tests incrates/knotrel-server/src/service.rsverify all contract scenarios TR-01 through TR-31 and concurrency interleavings with zero failures.
13.5 Implementation Status: Feature 0.2.6 (External Feeder Example, Restart/Rebuild Tests, and Reproducible Measurements)
Feature 0.2.6 is implemented, providing executable integration tools, comprehensive recovery tests, and reproducible benchmarks:
- Runnable External Feeder Reference Example: Implemented in
crates/knotrel-server/examples/external_feeder.rsseparate from server internals and graph core. Driven by a deterministic source fixture (crates/knotrel-server/tests/common/feeder.rs), it executes the full lifecycle over the wire:- Server discovery (
GET /v1/info) and operating mode verification (source_managed). - Session registration (
POST /v1/feeder/session) with observable background heartbeat loop (POST /v1/feeder/heartbeat), validating responses with bounded timeouts and stopping stale ownership on fencing. - Atomic baseline snapshot import ($S$) with isolated vertices (
[99, 100]), verifying published generation 1 and HTTP 201 Created. - Ordered catch-up stream ($D=1..7$) exercising vertex creation, links, cuts, no-op duplicate mutations, and non-mutating
progresscheckpoints. - Synchronization barrier $B$ (
POST /v1/feeder/barrier) at high-water mark, restoringReady(HTTP 200). - Independent Oracle comparison: Queries against
/v1/operationsverified against pure standard library BFS/adjacency oracle (ExternalSourceOracle) with reported agreement percentage. - Controlled fault injection: Deterministic response loss simulated via loopback TCP proxy (
ControlledFaultProxy); feeder automatically reconciles via/v1/statsand recovers without data loss or false progress. - Volatile state demonstration: Simulates abrupt crash (
SIGKILL), verifies newly spawned instance begins uninitialized (HTTP 503) with a fresh instance ID, and rebuilds authoritatively toReady. - Clean shutdown: Heartbeat background task termination is cleanly awaited during shutdown.
- Build command:
cargo build --bin knotrel-server --example external_feederbuilds both server and example.
- Server discovery (
- Automated End-to-End Restart, Rebuild, and Recovery Tests: Implemented in
crates/knotrel-server/tests/e2e_rebuild.rsexecuting 21 automated scenarios against realknotrel-serverchild processes:test_01_initial_bootstrap_oracle_verification: Initial build toReadyverified against independent oracle; uninitialized server rejects queries (503uninitialized); stale instance header rejection (409stale_instance_id).test_02_noop_and_progress_records_preserve_revision: No-op links and progress records advance source frontier without incrementingstate_version.test_03_committed_event_with_lost_acknowledgment_and_feeder_recovery: Committed event with response dropped byControlledFaultProxyis retried using exact immutable identity, letting server deduplication logic idempotently return HTTP 200already_appliedwithout synthesizing success from sequence frontiers.test_04_old_link_retry_after_newer_cut_preserves_cut: Critical regression test: retrying an oldlink(A, B)event after a newercut(A, B)returnsalready_appliedand preserves the cut (edge strictly remains absent).test_05_graceful_restart_and_abrupt_termination_require_rebuild: Graceful restart (SIGTERM) and abrupt process crash (SIGKILL) cause newly started server to start uninitialized (HTTP 503), reject old instance identity (HTTP 409stale_instance_id), and require rediscovery and authoritative rebuild.test_06_declared_gap_followed_by_authoritative_rebuild: Feeder gap declaration (POST /v1/feeder/gap) rejects subsequent updates with 409graph_desynchronized; authoritative rebuild via replacement import (mode: "replace"with compositeIf-Match) and fresh barrier restoresReadyserving.test_07_lease_expiry_cannot_be_repaired_by_heartbeat_alone: Expired lease causes 503stale; subsequent heartbeat renews deadline but returnsstatus: "stale"; barrier with expired epoch returns 409fenced_feeder_session; recovery requires registering a bumped feeder epoch (feeder_epoch > last_expired_epoch) and submitting barrier proof.test_08_failed_domain_mutation_stops_batch_without_false_progress: Domain failure (self-loop 422) stops batch execution cleanly; committed prefix advances applied frontier while uncommitted items are not recorded; structured partial failure diagnostics inspected; corrected retry succeeds.test_09_import_with_lost_acknowledgment_and_reconciliation: Snapshot import with lost HTTP response returns explicitUncertainOutcomewithout synthesizing publication from counts/cursor; feeder safely executes documented conditional rebuild (conditional_rebuild_snapshotwith mandatory compositeIf-Matchprecondition) before declaring barrier and serving.test_10_authoritative_changes_during_snapshot_loading_catch_up_to_barrier_b: Controlled test where external authoritative mutations occur strictly after snapshot S and before import completion via upload proxy synchronization; server remains incatching_upuntil stream catches up to high-water mark B and reachesReady, verified against independent oracle.test_11_unverifiable_duplicate_requiring_safe_recovery: Events evicted from bounded deduplication window return HTTP 409unverifiable_duplicate; server remains healthy and feeder safely initiates authoritative rebuild (mode: "replace").test_12_heartbeat_observability_fencing_and_clean_shutdown: Competing session fences primary feeder; background heartbeat detects 409 fencing, stops stale ownership, updates observable status toHeartbeatStatus::Fenced, and awaits clean shutdown.test_13_lost_ack_combined_with_replacement_before_retry: Lost event ACK followed by replacement before retry returns explicitRecoveryRequired/Fencedwithout fabricating success.test_14_lost_ack_combined_with_restart: Lost event ACK followed by server crash and restart returns explicitStaleInstancewithout fabricating deduplication.test_15_lost_ack_combined_with_competing_ownership_takeover: Lost event ACK followed by competing feeder takeover returns explicitFencedwithout fabricating deduplication.test_16_import_reconciliation_existing_graph_same_cursor_different_topology: Import reconciliation on existing graph with matching cursor but different topology safely rejects false publication success.test_17_import_reconciliation_import_never_committed: Import dropped before server commit returns explicitUncertainOutcome(“publication not observed on server”) without synthesizing publication.test_18_import_reconciliation_replaced_by_another_feeder_before_reconciliation: Replacement by competing feeder before import reconciliation returns explicitUncertainOutcome/Fencedwithout unconditional replacement.test_19_import_reconciliation_restart_during_uncertain_outcome: Restart during uncertain import outcome returns explicitRecoveryRequired/StaleInstance.test_20_heartbeat_failure_halts_feeder_control_flow: Background heartbeat fencing halts all feeder operations (import,apply_events,apply_events_with_recovery,declare_barrier) immediately, ensuring retries and recovery do not continue under lost ownership.test_21_import_reconciliation_same_count_same_cursor_different_topology: Deterministic regression reproducing same-count, same-cursor, different-topology competing publication; verifies that when original import was not forwarded and heartbeat detection cannot mask the reconciliation defect, the feeder returns explicitUncertainOutcomerather than synthesizing false publication success.
- Reproducible Measurement Tooling: Implemented in
crates/knotrel-server/examples/measure_e2e.rsandscripts/measure-e2e.sh:- Supports deterministic synthetic workloads across tiers (
small,medium,large). - Pure query latency and throughput timing strictly separated from out-of-band BFS oracle verification.
- Non-zero process exit on unexpected HTTP response, malformed payload, or oracle disagreement.
- Continuous 25ms sampling reports sampled maximum process RSS (documenting that brief transient allocations between sampling intervals may not be captured) alongside final sampled process RSS.
- Supports repeated runs (
--runs <N>) with statistical aggregation (mean, p50, p95). - Explicitly documents build profile (debug smoke vs release benchmark), connection reuse model (
Connection: closesequential loopback), warmup phase (50 queries), and timer boundaries. - Retains timestamped Markdown evidence in
target/measurements/without overwriting prior evidence files.
- Supports deterministic synthetic workloads across tiers (
14. Maintainer Decision Checklist
Before declaring Feature 0.2.1 complete and proceeding to implementation in Feature 0.2.2, the maintainer must review and formally approve:
- Approval of Operating Mode Segregation: Confirm that direct mutations in source-managed mode return HTTP 409 Conflict (
direct_mutation_disabled). - Approval of Instance ID Header Enforcement: Confirm mandatory
X-Knotrel-Instance-Idheader across all feeder endpoints. - Approval of Progress Events & Verification-Only Barrier: Confirm that
progressevents are the sole non-mutating progress mechanism, barriers are verification-only, and mutually exclusive evaluation table (§5.3) is adopted. - Approval of Sequence Classification & Predecessor Validation: Confirm sequence classification ($D \le D_{applied}$, $D == D_{applied}+1$, $D > D_{applied}+1$) and predecessor check under the graph lock prior to mutation execution.
- Approval of Feeder Lease Protocol: Confirm
POST /v1/feeder/sessionandPOST /v1/feeder/heartbeatwith monotonic lease timeout (proposed default: 10s), where heartbeat renews lease but does not restoreReadywithout synchronization proof. - Approval of Mandatory Replace Precondition: Confirm
If-Match: "<gen>.<state_version>.<percent_encoded_source_position>"for graph replacements. - Approval of Exact Bounded Duplicate Window: Confirm proposed default 10,000 entry window with dual-index (sequence ring buffer + event ID hash index), Tier 2 canonical equality check, and memory accounting requirements.
- Approval of Import Bounds: Confirm proposed default 64 MiB body limit and
KNOTREL_MAX_CONCURRENT_IMPORTS = 1.