{"version":3,"sources":["../src/interchange/types.ts","../src/interchange/ingestion-import-target.ts","../src/interchange/stream-source.ts","../src/interchange/import.ts","../src/interchange/export.ts","../src/interchange/trusted-import.ts"],"names":["z","isCanonicalIsoDate","storeBackend","ConfigurationError","acquireSerializedStreamLease","storeRuntime","batchPointReadVerdict","uniqueSidecarBatchVerdict","statementExecutionVerdict","graphOwesClaims","constraintFenceRefusal","assertEdgeMatchIdentityBackendSupport","runWritePlan","createClaimsVerdictThunk","storeCaptureEnabled","mixedWritePlan","snapshotExportContention","ValidationError","NodeNotFoundError","IdentityContradictionError","IDENTITY_IMPORT_FAILED_ASSERTION","IDENTITY_IMPORT_PROGRESS","getNodeKinds","getEdgeKinds","createNodeBatchValidationSeams","primeBatchValidationCaches","isLiveNodeRow","rowPropsToObject","checkUniquenessConstraints","checkDisjointnessConstraint","planNodeCreateClaims","UniquenessError","DisjointError","CardinalityError","EdgeMatchIdentityConflictError","runRecordedTransactionSavepoint","DatabaseOperationError","edgeMatchIdentityUpdateRefusal","INVERTED_VALIDITY_WINDOW_CODE","IMMUTABLE_VALIDITY_LOWER_BOUND_CODE","validateOptionalCanonicalIsoDate","assertOrderedValidityWindow","assertWritableValidityWindow","resolveEdgeMatchIdentityStorage","encodeTupleKey","requireDefined","createEdgeBatchValidationBackend","validateEdgeEndpoints","bindExtraIfReachable","BATCH_POINT_READ","params","checkCardinalityConstraint","classifyDurableEdgeBatchOutcomes","edgeCardinalityClaim","createDataKeyedBag","hasOwnKey","result","ExportStreamIdleTimeoutError","ExportStreamCancelledError","nowIso","take","push","TrustedImportError","getSearchableFields","resolveGraphVectorSlots","isInvertedValidityWindow"],"mappings":";;;;;;;;;;;;;;;;;AA4BO,IAAM,cAAA,GAAiB;AAQ9B,IAAM,8BAA8BA,KAAA,CAAE,IAAA,CAAK,CAAC,KAAA,EAAO,KAAK,CAAC,CAAA;AAWzD,IAAM,uBAAA,GAA0BA,KAAA,CAAE,GAAA,CAC/B,QAAA,EAAS,CACT,OAA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ACA,IAAA,EAC8B;AAC9B,EAAA,OAAO,wBAAA,CAAyB,KAAA,EAAO,eAAA,CAAgB,IAAI,CAAC,CAAA;AAC9D","file":"chunk-6GUBF5TF.cjs","sourcesContent":["/**\n * Graph interchange format types.\n *\n * Defines Zod schemas for importing and exporting graph data.\n * The format is designed to be:\n * - JSON-serializable for API transport\n * - Validated via Zod at runtime\n * - Exportable as JSON Schema for LLM/API documentation\n */\nimport { z } from \"zod\";\n\nimport { isCanonicalIsoDate } from \"../utils/date\";\n\n// ============================================================\n// Format Version\n// ============================================================\n\n/**\n * Current interchange format version — the value every export writes.\n *\n * Read-side compatibility policy: the format is versioned separately from what\n * it *accepts*. A 1.0 document is a structurally valid 2.0 document — the only\n * 2.0 addition is the optional `identity` section — so import and\n * {@link GraphDataSchema} accept both `\"1.0\"` and `\"2.0\"` (see\n * {@link AcceptedFormatVersionSchema}), while exports keep writing this\n * constant. Bump this only when exports must emit a new version; add the old\n * value to the accepted set rather than dropping read compatibility.\n */\nexport const FORMAT_VERSION = \"2.0\" as const;\n\n/**\n * Format versions accepted on the read side (import + `GraphDataSchema.parse`).\n * A pre-existing 1.0 export is a valid 2.0 document (the 2.0 change is the\n * additive optional `identity` section), so both validate; exports always write\n * {@link FORMAT_VERSION}.\n */\nconst AcceptedFormatVersionSchema = z.enum([\"1.0\", \"2.0\"]);\n\n/**\n * A stored validity-window timestamp (`validFrom` / `validTo`). Must be a\n * canonical fixed-width UTC ISO-8601 string (`YYYY-MM-DDTHH:mm:ss.sssZ`) — the\n * same contract `create` / `update` enforce — because temporal filters compare\n * it as text against the `asOf` read coordinate, and a variable-width value\n * (date-only, offset, missing/variable milliseconds) would mis-sort and\n * silently include or exclude the wrong rows. Convert non-canonical inputs with\n * `new Date(value).toISOString()`.\n */\nconst ValidityTimestampSchema = z.iso\n  .datetime()\n  .refine((value) => isCanonicalIsoDate(value), {\n    message:\n      \"Expected canonical UTC ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ); convert with new Date(value).toISOString().\",\n  });\n\n// ============================================================\n// Node Interchange\n// ============================================================\n\n/**\n * Interchange format for a node.\n *\n * Properties are stored as a record to allow schema-agnostic transport.\n * Validation against the actual schema happens during import.\n */\nexport const InterchangeNodeSchema = z.object({\n  kind: z.string().min(1),\n  id: z.string().min(1),\n  properties: z.record(z.string(), z.unknown()),\n  /**\n   * `undefined` (key absent): not requested (`includeTemporal: false`) —\n   * import defaults it to the import's own creation timestamp, UNLESS the\n   * record states a `validTo` at or before that instant, in which case the row\n   * is imported with no lower bound (\"ended at T, start unknown\") rather than\n   * one after its own end (issue #407). `null`: requested and confirmed the row\n   * has no lower bound (e.g. a legacy row predating the \"omitted validFrom\n   * defaults to creation time\" fix) — import preserves that open-left validity\n   * instead of re-stamping it.\n   */\n  validFrom: ValidityTimestampSchema.nullable().optional(),\n  validTo: ValidityTimestampSchema.optional(),\n  meta: z\n    .object({\n      version: z.number().int().positive().optional(),\n      createdAt: z.iso.datetime().optional(),\n      updatedAt: z.iso.datetime().optional(),\n    })\n    .optional(),\n});\n\nexport type InterchangeNode = z.infer<typeof InterchangeNodeSchema>;\n\n// ============================================================\n// Edge Interchange\n// ============================================================\n\n/**\n * Interchange format for an edge.\n *\n * Endpoint references are objects with kind and id, rather than\n * composite strings, for clarity and type safety.\n */\nexport const InterchangeEdgeSchema = z.object({\n  kind: z.string().min(1),\n  id: z.string().min(1),\n  from: z.object({\n    kind: z.string().min(1),\n    id: z.string().min(1),\n  }),\n  to: z.object({\n    kind: z.string().min(1),\n    id: z.string().min(1),\n  }),\n  properties: z.record(z.string(), z.unknown()).default({}),\n  /** See {@link InterchangeNodeSchema}'s `validFrom` for the null/undefined contract. */\n  validFrom: ValidityTimestampSchema.nullable().optional(),\n  validTo: ValidityTimestampSchema.optional(),\n  meta: z\n    .object({\n      createdAt: z.iso.datetime().optional(),\n      updatedAt: z.iso.datetime().optional(),\n    })\n    .optional(),\n});\n\nexport type InterchangeEdge = z.infer<typeof InterchangeEdgeSchema>;\n\n// ============================================================\n// Operational Identity Interchange\n// ============================================================\n\nexport const IdentityInterchangeModeSchema = z.enum([\"state\", \"archival\"]);\nexport type IdentityInterchangeMode = z.infer<\n  typeof IdentityInterchangeModeSchema\n>;\n\nexport const InterchangeIdentityAssertionSchema = z.object({\n  id: z.string().min(1),\n  relation: z.enum([\"same\", \"different\"]),\n  a: z.object({ kind: z.string().min(1), id: z.string().min(1) }),\n  b: z.object({ kind: z.string().min(1), id: z.string().min(1) }),\n  validFrom: ValidityTimestampSchema,\n  validTo: ValidityTimestampSchema.optional(),\n  /**\n   * The node whose soft-delete cascade ended this assertion — the ledger's\n   * stored cause, carried so an `archival` round-trip preserves WHY each\n   * ending happened and not merely that it did. Absent on open rows and on\n   * explicit retractions; when present it names one of `a` / `b` and requires\n   * `validTo`. Import rejects both violations with an attributed error.\n   */\n  endedBy: z\n    .object({ kind: z.string().min(1), id: z.string().min(1) })\n    .optional(),\n});\nexport type InterchangeIdentityAssertion = z.infer<\n  typeof InterchangeIdentityAssertionSchema\n>;\n\nexport const InterchangeIdentitySchema = z.object({\n  profile: z.literal(\"typegraph-identity-v1\"),\n  mode: IdentityInterchangeModeSchema,\n  assertions: z.array(InterchangeIdentityAssertionSchema),\n});\nexport type InterchangeIdentity = z.infer<typeof InterchangeIdentitySchema>;\n\nconst InterchangeIdentityHeaderSchema = InterchangeIdentitySchema.omit({\n  assertions: true,\n});\n\n// ============================================================\n// Import Configuration\n// ============================================================\n\n/**\n * Strategy for handling conflicts when a node/edge ID already exists.\n *\n * - `skip`: Keep existing, ignore incoming\n * - `update`: Merge incoming properties into existing\n * - `error`: Throw an error on conflict\n */\nexport const ConflictStrategySchema = z.enum([\"skip\", \"update\", \"error\"]);\nexport type ConflictStrategy = z.infer<typeof ConflictStrategySchema>;\n\n/**\n * Strategy for handling properties not defined in the schema.\n *\n * - `error`: Throw a validation error\n * - `strip`: Remove unknown properties silently\n * - `allow`: Pass through to storage (relies on backend behavior)\n */\nexport const UnknownPropertyStrategySchema = z.enum([\n  \"error\",\n  \"strip\",\n  \"allow\",\n]);\nexport type UnknownPropertyStrategy = z.infer<\n  typeof UnknownPropertyStrategySchema\n>;\n\n/**\n * Options for importing graph data.\n */\nexport const ImportOptionsSchema = z.object({\n  /** How to handle existing nodes/edges with the same ID */\n  onConflict: ConflictStrategySchema,\n  /** How to handle properties not in the schema */\n  onUnknownProperty: UnknownPropertyStrategySchema.default(\"error\"),\n  /** Whether to validate that edge endpoints exist */\n  validateReferences: z.boolean().default(true),\n  /**\n   * Number of items to process in each batch. Each batch pays fixed\n   * per-round-trip costs (existence probe, unique check, one multi-row\n   * insert), so undersized batches dominate import time on client/server\n   * engines: measured on PostgreSQL, 20k nodes + 5k edges import in\n   * 1,515ms at 100 vs 781ms at 1,000. Above ~1,000 the multi-row insert\n   * itself dominates and larger batches stop paying; SQLite is\n   * insensitive to the value (in-process, no round trips). The backend\n   * further splits inserts by its bind-parameter budget, so a large\n   * batch never overruns driver limits.\n   */\n  batchSize: z.number().int().positive().default(1000),\n  /**\n   * Refresh planner statistics (ANALYZE) after an import that created or\n   * updated rows. Bulk loads otherwise run against stale statistics until\n   * the engine catches up on its own. Default: true.\n   */\n  refreshStatistics: z.boolean().optional(),\n  /**\n   * How a streamed import reacts when one chunk reports entity-level errors.\n   * `abort` is the safe default: earlier chunks are already committed, so\n   * callers must not mistake a partial stream for a successful retryable load.\n   * `continue` is reserved for explicit best-effort ingestion.\n   */\n  onStreamChunkError: z.enum([\"abort\", \"continue\"]).default(\"abort\"),\n});\n\n/**\n * Caller-facing options: fields with schema defaults are optional.\n * `importGraph` parses these once at its boundary; internal stages\n * consume {@link ResolvedImportOptions} with every default applied.\n */\nexport type ImportOptions = z.input<typeof ImportOptionsSchema>;\n\n/** {@link ImportOptions} after schema parsing — all defaults resolved. */\nexport type ResolvedImportOptions = z.infer<typeof ImportOptionsSchema>;\n\n// ============================================================\n// Graph Data Source\n// ============================================================\n\n/**\n * Source metadata for graph data.\n *\n * Uses discriminated union to capture different origin types:\n * - `typegraph-export`: Exported from a TypeGraph store\n * - `external`: From a third-party system\n */\nexport const GraphDataSourceSchema = z.discriminatedUnion(\"type\", [\n  z.object({\n    type: z.literal(\"typegraph-export\"),\n    graphId: z.string(),\n    schemaVersion: z.number().int().positive(),\n  }),\n  z.object({\n    type: z.literal(\"external\"),\n    description: z.string().optional(),\n  }),\n]);\n\nexport type GraphDataSource = z.infer<typeof GraphDataSourceSchema>;\n\n// ============================================================\n// Graph Data Envelope\n// ============================================================\n\n/**\n * Complete graph data interchange format.\n *\n * The envelope contains metadata about the data source and format version,\n * plus arrays of nodes and edges to import.\n */\nexport const GraphDataSchema = z.object({\n  formatVersion: AcceptedFormatVersionSchema,\n  exportedAt: z.iso.datetime(),\n  source: GraphDataSourceSchema,\n  nodes: z.array(InterchangeNodeSchema),\n  edges: z.array(InterchangeEdgeSchema),\n  identity: InterchangeIdentitySchema.optional(),\n});\n\nexport type GraphData = z.infer<typeof GraphDataSchema>;\n\n/** The metadata envelope emitted before streamed graph entities. */\nexport const GraphDataHeaderSchema = GraphDataSchema.omit({\n  nodes: true,\n  edges: true,\n  identity: true,\n}).extend({\n  identity: InterchangeIdentityHeaderSchema.optional(),\n});\n\nexport type GraphDataHeader = z.infer<typeof GraphDataHeaderSchema>;\n\n/**\n * One bounded unit in the streamed interchange protocol. Nodes always precede\n * edges, so an importer can validate endpoints from rows already written to its\n * target without retaining all prior nodes in memory.\n */\nexport const GraphInterchangeChunkSchema = z.discriminatedUnion(\"type\", [\n  z.object({ type: z.literal(\"header\"), header: GraphDataHeaderSchema }),\n  z.object({ type: z.literal(\"nodes\"), nodes: z.array(InterchangeNodeSchema) }),\n  z.object({ type: z.literal(\"edges\"), edges: z.array(InterchangeEdgeSchema) }),\n  z.object({\n    type: z.literal(\"identity\"),\n    assertions: z.array(InterchangeIdentityAssertionSchema),\n  }),\n]);\n\nexport type GraphInterchangeChunk = z.infer<typeof GraphInterchangeChunkSchema>;\n\n// ============================================================\n// Import Result\n// ============================================================\n\n/**\n * An error that occurred during import.\n */\nexport const ImportErrorSchema = z.object({\n  entityType: z.enum([\"node\", \"edge\", \"identity\"]),\n  kind: z.string(),\n  id: z.string(),\n  error: z.string(),\n});\n\nexport type ImportError = z.infer<typeof ImportErrorSchema>;\n\n/**\n * Result of an import operation.\n *\n * Contains counts of created/updated/skipped entities and any errors.\n */\nexport const ImportResultSchema = z.object({\n  success: z.boolean(),\n  nodes: z.object({\n    created: z.number().int().nonnegative(),\n    updated: z.number().int().nonnegative(),\n    skipped: z.number().int().nonnegative(),\n  }),\n  edges: z.object({\n    created: z.number().int().nonnegative(),\n    updated: z.number().int().nonnegative(),\n    skipped: z.number().int().nonnegative(),\n  }),\n  identity: z.object({\n    created: z.number().int().nonnegative(),\n    skipped: z.number().int().nonnegative(),\n  }),\n  errors: z.array(ImportErrorSchema),\n});\n\nexport type ImportResult = z.infer<typeof ImportResultSchema>;\n\n// ============================================================\n// Export Options\n// ============================================================\n\n/** Largest delay JavaScript timers represent without truncation or overflow. */\nconst MAX_TIMER_DELAY_MS = 2_147_483_647;\n\n/**\n * Options for exporting graph data.\n */\nexport const ExportOptionsSchema = z.object({\n  /** Filter to specific node kinds (undefined = all) */\n  nodeKinds: z.array(z.string()).optional(),\n  /** Filter to specific edge kinds (undefined = all) */\n  edgeKinds: z.array(z.string()).optional(),\n  /** Include temporal fields (validFrom, validTo) */\n  includeTemporal: z.boolean().default(false),\n  /** Include metadata (version, timestamps) */\n  includeMeta: z.boolean().default(false),\n  /** Include soft-deleted records */\n  includeDeleted: z.boolean().default(false),\n  /** Operational Identity export mode. Defaults to current state only. */\n  identityMode: IdentityInterchangeModeSchema.default(\"state\"),\n  /**\n   * Cancels the export: whatever it had opened is settled — on a backend with\n   * `capabilities.execution.interactiveTransactions` that means its repeatable-read snapshot is\n   * rolled back and the serialized connection's stream lease released; on one\n   * without, there is no transaction and no lease, and the remaining reads are\n   * simply abandoned. Either way the consumer is rejected with an\n   * `ExportStreamCancelledError` (`code:\n   * \"INTERCHANGE_EXPORT_STREAM_ABORTED\"`), whose message states which of the\n   * two happened, carrying the signal's own `reason` as `cause`. Aborting\n   * before the first read refuses the export outright: nothing is opened and\n   * nothing claimed.\n   *\n   * On `exportGraph` this is a convenience — the call rejects instead of\n   * running to completion. On {@link exportGraphStream} it is the ONLY\n   * contract-grade way to stop a stream a consumer will not finish pulling:\n   * an async generator's `finally` does not run on garbage collection, so a\n   * consumer that pulls `next()` and then drops the iterator — the\n   * `Promise.race([iterator.next(), timeout])` pattern — otherwise holds the\n   * snapshot transaction, and with it the connection's exclusive stream lease,\n   * until the process exits. `break` / `throw` out of a `for await` and an\n   * explicit `iterator.return()` settle the stream cooperatively and need no\n   * signal; a race that abandons the iterator needs one.\n   */\n  signal: z.instanceof(AbortSignal).optional(),\n});\n\n/** Export options with defaults applied (output type) */\nexport type ExportOptions = z.infer<typeof ExportOptionsSchema>;\n\n/** Export options as accepted by exportGraph (input type with optional defaults) */\nexport type ExportOptionsInput = z.input<typeof ExportOptionsSchema>;\n\n/**\n * Export options for {@link exportGraphStream}. `batchSize` bounds the number\n * of node or edge entities retained for one yielded chunk.\n */\nexport const ExportStreamOptionsSchema = ExportOptionsSchema.extend({\n  /**\n   * Maximum time the consumer may leave a delivered chunk unacknowledged\n   * before the export settles itself. The clock starts when a chunk is yielded\n   * and is cleared when the consumer asks for the next chunk, so time spent\n   * waiting for the backend to produce a chunk does not count as consumer\n   * idleness. On expiry, the consumer is rejected with\n   * `ExportStreamIdleTimeoutError` and any snapshot transaction and serialized\n   * connection lease are released.\n   *\n   * Omit this only when the caller guarantees a cooperative exit (`break`,\n   * `throw`, or `iterator.return()`) or supplies a signal it will abort. An\n   * abandoned async iterator is not closed by garbage collection.\n   */\n  idleTimeoutMs: z.number().int().positive().max(MAX_TIMER_DELAY_MS).optional(),\n  batchSize: z.number().int().positive().default(1000),\n});\n\nexport type ExportStreamOptions = z.infer<typeof ExportStreamOptionsSchema>;\nexport type ExportStreamOptionsInput = z.input<\n  typeof ExportStreamOptionsSchema\n>;\n","/**\n * Private capability bridge from an opaque ingestion branch to interchange.\n *\n * The branch handle must not expose its relaxed-schema Store, but interchange\n * still needs the real Store so it can reuse the one import implementation that\n * owns validation, temporal windows, edge endpoints, and stream leases.\n */\n\nimport type { GraphDef } from \"../core/define-graph\";\nimport { ConfigurationError } from \"../errors\";\nimport { storeBackend } from \"../store/runtime-port\";\nimport type { Store } from \"../store/store\";\n\ndeclare const INGESTION_IMPORT_TARGET_BRAND: unique symbol;\n\n/** Opaque capability implemented by ingestion branches accepted by import. */\nexport type IngestionImportTarget<G extends GraphDef> = Readonly<{\n  [INGESTION_IMPORT_TARGET_BRAND]: G;\n}>;\n\nconst INGESTION_IMPORT_TARGETS = new WeakMap<object, unknown>();\n\n/** Registers the private Store represented by an opaque ingestion handle. */\nexport function registerIngestionImportTarget<G extends GraphDef>(\n  handle: object,\n  store: Store<G>,\n): void {\n  INGESTION_IMPORT_TARGETS.set(handle, store);\n}\n\n/** Resolves an import target without making the hidden Store public. */\nexport function resolveIngestionImportTarget<G extends GraphDef>(\n  target: Store<G> | object,\n): Store<G> {\n  const registeredStore = INGESTION_IMPORT_TARGETS.get(target);\n  if (registeredStore !== undefined) return registeredStore as Store<G>;\n  try {\n    storeBackend(target);\n    return target as Store<G>;\n  } catch (error) {\n    throw new ConfigurationError(\n      \"Interchange import received an unrecognized ingestion target\",\n      { target: \"unregistered-ingestion-target\" },\n      {\n        cause: error,\n        suggestion:\n          \"Pass a Store or the exact handle returned by ingestionBranch() from this TypeGraph installation.\",\n      },\n    );\n  }\n}\n","import { type GraphBackend } from \"../backend/types\";\nimport { type GraphInterchangeChunk } from \"./types\";\n\nconst EXPORT_STREAM_BACKENDS = new WeakMap<\n  AsyncIterable<GraphInterchangeChunk>,\n  GraphBackend\n>();\n\nexport function markExportStreamBackend(\n  stream: AsyncIterable<GraphInterchangeChunk>,\n  backend: GraphBackend,\n): AsyncIterable<GraphInterchangeChunk> {\n  EXPORT_STREAM_BACKENDS.set(stream, backend);\n  return stream;\n}\n\nexport function exportStreamBackend(\n  stream: AsyncIterable<GraphInterchangeChunk>,\n): GraphBackend | undefined {\n  return EXPORT_STREAM_BACKENDS.get(stream);\n}\n","/**\n * Graph data import functionality.\n *\n * Imports nodes and edges from the interchange format into a store,\n * with configurable conflict resolution and validation.\n *\n * ## A write asserts EVERY component its verdict read\n *\n * `onConflict: \"update\"` is a read-then-write pair: this module PROBES the\n * stored row, decides from what it finds, and then writes. Under PostgreSQL\n * READ COMMITTED a concurrent `hardDelete` + recreate re-resolves the probed key\n * between those two statements, so any part of the verdict that is not restated\n * in the UPDATE's own `WHERE` is a decision that can land on a row it was never\n * computed for — and the import reports success, because the write did affect a\n * row. The failure is invisible and only appears under a race, which is why it\n * has taken three rounds to enumerate:\n *\n *  - the edge's KIND — the probe is keyed on `(graph_id, id)` alone, so the row\n *    under an id may be a different edge entirely;\n *  - the edge's ENDPOINTS — kind is not an identity, and an upsert that resolved\n *    an edge BY its endpoints must say so;\n *  - the effective `valid_from` of BOTH entities — {@link\n *    validateUpdateValidityWindow} decides from the stored lower bound, so a\n *    recreate carrying a different one turns that verdict into a write that\n *    ignores the document's `validFrom` or persists `valid_to < valid_from`.\n *\n * The rest of what these legs read, and where each is asserted:\n *\n *  - the row EXISTS (the `getNode` / `getEdge` probe): restated as the\n *    `(graph_id, kind, id)` / `(graph_id, id)` predicate every UPDATE carries.\n *  - the row is LIVE (`isLiveNodeRow` / `deleted_at === undefined`, which is what\n *    routes a tombstone to `skipped` instead of to the update): restated as the\n *    `deleted_at IS NULL` conjunction on the non-resurrecting UPDATE leg. Import\n *    never resurrects, so it never builds the `IS NOT NULL` leg.\n *  - `onConflict: \"skip\"` / `\"error\"`: verdict-independent by construction —\n *    they write nothing.\n *  - the row's PROPS, read as the `oldProps` side of the uniqueness diff: the\n *    ONE input with no portable SQL predicate behind it (a props blob is TEXT on\n *    SQLite and `jsonb` on PostgreSQL, and neither comparison is stable under\n *    key reordering). It is bounded rather than asserted: the sidecar writes now\n *    run AFTER the primary update returns a row (see `applyNodeUpdate`), so a\n *    verdict-invalidating recreate that changes the lower bound takes the\n *    sidecars with it. The residual window is a recreate that reproduces the\n *    probed `valid_from` exactly while changing props — noted here so the next\n *    round starts from the list rather than from the symptom.\n */\nimport type { z } from \"zod\";\n\nimport { bindExtraIfReachable } from \"../backend/capabilities/bind\";\nimport type {\n  STATEMENT_EXECUTION,\n  UNIQUE_SIDECAR_BATCH,\n} from \"../backend/capabilities/bundle-registry\";\nimport { BATCH_POINT_READ } from \"../backend/capabilities/bundle-registry\";\nimport {\n  batchPointReadVerdict,\n  type BundleVerdictOf,\n  createClaimsVerdictThunk,\n  statementExecutionVerdict,\n  uniqueSidecarBatchVerdict,\n} from \"../backend/capabilities/resolve\";\nimport { assertEdgeMatchIdentityBackendSupport } from \"../backend/edge-match-identity\";\nimport {\n  acquireSerializedStreamLease,\n  type SerializedStreamKind,\n  type SnapshotExportContention,\n  snapshotExportContention,\n} from \"../backend/transaction-resource\";\nimport {\n  type EdgeRow,\n  type GraphBackend,\n  type InsertEdgeParams,\n  isLiveNodeRow,\n  type LiveNodeRow,\n  rowPropsToObject,\n} from \"../backend/types\";\nimport { validateEdgeEndpoints } from \"../constraints\";\nimport {\n  getEdgeKinds,\n  getNodeKinds,\n  type GraphDef,\n} from \"../core/define-graph\";\nimport {\n  type Cardinality,\n  type EdgeRegistration,\n  type NodeRegistration,\n  type UniqueConstraint,\n} from \"../core/types\";\nimport {\n  CardinalityError,\n  ConfigurationError,\n  DatabaseOperationError,\n  DisjointError,\n  EdgeMatchIdentityConflictError,\n  IdentityContradictionError,\n  IMMUTABLE_VALIDITY_LOWER_BOUND_CODE,\n  INVERTED_VALIDITY_WINDOW_CODE,\n  NodeNotFoundError,\n  UniquenessError,\n  ValidationError,\n} from \"../errors\";\nimport {\n  IDENTITY_IMPORT_FAILED_ASSERTION,\n  IDENTITY_IMPORT_PROGRESS,\n} from \"../identity/service\";\nimport { type IdentityTarget } from \"../identity/sql-target\";\nimport { type KindRegistry } from \"../registry/kind-registry\";\nimport { edgeCardinalityClaim } from \"../store/claims/edge-claims\";\nimport {\n  checkUniquenessConstraints,\n  type NodeClaimItem,\n  planNodeCreateClaims,\n} from \"../store/claims/node-claims\";\nimport {\n  checkCardinalityConstraint,\n  checkDisjointnessConstraint,\n  graphOwesClaims,\n} from \"../store/constraints\";\nimport { classifyDurableEdgeBatchOutcomes } from \"../store/durable-edge-batch\";\nimport {\n  edgeMatchIdentityUpdateRefusal,\n  resolveEdgeMatchIdentityStorage,\n} from \"../store/edge-match-key\";\nimport { createEdgeBatchValidationBackend } from \"../store/operations/edge-batch-validation\";\nimport {\n  createNodeBatchValidationSeams,\n  type NodeCreateDraft,\n  primeBatchValidationCaches,\n} from \"../store/operations/node-operations\";\nimport {\n  type OverlaidSessionMint,\n  runWritePlan,\n} from \"../store/operations/write-executor\";\nimport { mixedWritePlan } from \"../store/operations/write-plan\";\nimport {\n  type EdgeInsertWork,\n  type NodeCreateWork,\n  type WriteSession,\n  type WriteTarget,\n} from \"../store/operations/write-session\";\nimport {\n  constraintFenceRefusal,\n  type WriteTransactionMode,\n} from \"../store/operations/write-transaction\";\nimport { runRecordedTransactionSavepoint } from \"../store/recorded-capture\";\nimport {\n  storeBackend,\n  storeCaptureEnabled,\n  storeRuntime,\n} from \"../store/runtime-port\";\nimport { type Store } from \"../store/store\";\nimport {\n  assertOrderedValidityWindow,\n  assertWritableValidityWindow,\n  validateOptionalCanonicalIsoDate,\n  type ValidityLowerBoundFence,\n} from \"../utils/date\";\nimport { createDataKeyedBag, hasOwnKey } from \"../utils/object\";\nimport { requireDefined } from \"../utils/presence\";\nimport { encodeTupleKey } from \"../utils/tuple-key\";\nimport {\n  type IngestionImportTarget,\n  resolveIngestionImportTarget,\n} from \"./ingestion-import-target\";\nimport { exportStreamBackend } from \"./stream-source\";\nimport {\n  type GraphData,\n  type GraphDataHeader,\n  GraphDataHeaderSchema,\n  type GraphInterchangeChunk,\n  type ImportError,\n  type ImportOptions,\n  ImportOptionsSchema,\n  type ImportResult,\n  type InterchangeEdge,\n  type InterchangeIdentityAssertion,\n  InterchangeIdentitySchema,\n  type InterchangeNode,\n  type ResolvedImportOptions,\n  type UnknownPropertyStrategy,\n} from \"./types\";\n\n// ============================================================\n// Import Function\n// ============================================================\n\n/** A normal Store or an opaque ingestion branch that interchange may stage. */\nexport type ImportTarget<G extends GraphDef> =\n  Store<G> | IngestionImportTarget<G>;\n\n/**\n * Import graph data into a store or opaque ingestion branch.\n *\n * Nodes are imported first to satisfy edge reference validation.\n * The import runs within a transaction for atomicity when supported.\n *\n * Refused with a typed {@link ConfigurationError} when the target writes through\n * a serialized database connection another long-lived interchange operation\n * holds — the same refusal, codes and `details.heldBy` / `details.requested` as\n * {@link importGraphStream}. Hand-rolling a stream as `for await (const chunk of\n * exportGraphStream(source)) await importGraph(target, ...)` on one such\n * connection is therefore refused on the first chunk instead of nesting a write\n * transaction inside the export's open snapshot.\n *\n * Also refused, with `CONSTRAINT_WRITE_FENCE_UNSUPPORTED`, when the backend\n * reports `execution.interactiveTransactions: false` AND the graph owes a claim that must be written\n * before the row it gates — any unique constraint of any scope, any node kind\n * with a `disjointWith` partner, or any edge kind whose cardinality is not\n * `many`. An import writes those reservations like every other writer and takes\n * no per-graph lock, so without a transaction a failure between a reservation\n * and its row would leave a key blocked with no repair path. The verdict is per\n * GRAPH rather than per payload, and it is reached before the first row: a\n * streamed import cannot commit part of itself and only then discover it could\n * not be fenced.\n *\n * @param target - The graph store or ingestion branch to import into\n * @param data - Graph data in interchange format\n * @param options - Import configuration\n * @returns Import statistics and any errors\n *\n * @example\n * ```typescript\n * const result = await importGraph(store, data, {\n *   onConflict: \"update\",\n *   onUnknownProperty: \"strip\",\n * });\n *\n * console.log(`Created ${result.nodes.created} nodes`);\n * ```\n */\nexport async function importGraph<G extends GraphDef>(\n  target: ImportTarget<G>,\n  data: GraphData,\n  rawOptions: ImportOptions,\n): Promise<ImportResult> {\n  const store = resolveIngestionImportTarget<G>(target);\n  // Parse ONCE at the public boundary: schema defaults (batchSize, ...)\n  // only exist after parsing, and every internal stage reads them\n  // directly.\n  const options = ImportOptionsSchema.parse(rawOptions);\n  return withImportStreamLease(store, () =>\n    importGraphData(store, data, options),\n  );\n}\n\n/**\n * Claims the target connection's exclusive stream lease for the whole of `run`,\n * or refuses with the holder named.\n *\n * GRANULARITY: an in-memory import is not one long-lived transaction — it is a\n * write transaction followed by a best-effort statistics refresh — but it IS one\n * long-lived operation on the connection, and it faces exactly the hazard the\n * streaming guard exists for: an export snapshot holding the single connection\n * this import must write on, or opening midway through it. A lease for the whole\n * call is the simplest claim that covers every write the call makes, so that is\n * what it takes.\n *\n * Claimed at each PUBLIC boundary that writes a whole import — this function's\n * own {@link importGraph} and `trustedImportGraphStream` — and nowhere else.\n * {@link importGraphStream} already holds the lease for its chunk loop and calls\n * {@link importGraphData} directly, so a per-chunk import is never refused by\n * the stream that issued it.\n */\nexport async function withImportStreamLease<G extends GraphDef, T>(\n  store: Store<G>,\n  run: () => Promise<T>,\n): Promise<T> {\n  const lease = acquireSerializedStreamLease(\n    storeBackend(store),\n    \"import-stream\",\n  );\n  if (!lease.acquired) {\n    throw serializedStreamRefusal({\n      graphId: store.graphId,\n      requested: \"import-stream\",\n      heldBy: lease.heldBy,\n    });\n  }\n  try {\n    return await run();\n  } finally {\n    lease.release();\n  }\n}\n\n/**\n * The one write frame every import leg works inside, replacing the raw backend\n * and the `GraphWriteLock` token the legs used to be threaded separately.\n *\n * `session` is the only surface that mutates graph state — a node create here\n * carries its uniqueness, fulltext and embedding rows because the session\n * fuses them, not because this module remembered to call the sidecars after\n * the insert. `target` is the read projection the same frame hands out, and\n * every preparation helper, constraint probe and identity statement this\n * module reaches now takes that projection rather than the backend union — so\n * no leg here widens it back.\n *\n * `overlaidSession` is needed by exactly one leg — the batched node slice,\n * whose in-slice update must plan its uniqueness against the pending-aware\n * overlay — and rides on the frame rather than being threaded to that leg\n * alone, because it is a property of the frame, not of the leg. It takes the\n * READS to answer; the executor owns decorating its own target with them.\n */\ntype ImportWriteFrame = Readonly<{\n  session: WriteSession;\n  target: WriteTarget;\n  allocateEdgeSavepoint: () => string;\n  transactionMode: WriteTransactionMode;\n  overlaidSession: OverlaidSessionMint<\"mixed\">;\n  /** Threaded `batchPointRead` verdict — resolved once, from `backend`. */\n  batchPointRead: BundleVerdictOf<typeof BATCH_POINT_READ>;\n  /** Threaded `uniqueSidecarBatch` verdict — resolved once, from `backend`. */\n  uniqueSidecarBatch: BundleVerdictOf<typeof UNIQUE_SIDECAR_BATCH>;\n  /** Threaded `statementExecution` verdict — resolved once, from `backend`. */\n  statementExecution: BundleVerdictOf<typeof STATEMENT_EXECUTION>;\n}>;\n\n/**\n * The counters, error list, and imported-id set one import write-plan attempt\n * accumulates. Never shared across attempts: a rolled-back commit's growth in\n * these must not leak into the attempt that succeeds. Exported for the same\n * declaration-file reason as {@link NodeSchemaEntry} — it is\n * {@link runImportWritePlanAttempt}'s return type, and that function is\n * test-only.\n */\nexport type ImportAttemptState = Readonly<{\n  result: ImportResult;\n  errors: ImportError[];\n  importedNodeIds: Set<string>;\n}>;\n\n/** Fresh, empty attempt state. Called once at the top of every attempt. */\nfunction createImportAttemptState(): ImportAttemptState {\n  return {\n    result: emptyImportResult(),\n    errors: [],\n    importedNodeIds: new Set<string>(),\n  };\n}\n\n/**\n * The inputs one import write-plan attempt needs that stay fixed across every\n * attempt a retry owner might drive it through: schema maps, the resolved\n * capability verdicts, and the target-independent pieces of the import\n * request. None of it is mutated by an attempt, and the verdicts specifically\n * must stay bound to the root `backend` they were resolved from — re-deriving\n * them from a transaction target would answer a different question than the\n * one `importGraphData` already asked once at its own root.\n */\nexport type ImportAttemptInputs<G extends GraphDef> = Readonly<{\n  graphId: string;\n  registry: KindRegistry;\n  data: GraphData;\n  nodeSchemas: ReadonlyMap<string, NodeSchemaEntry>;\n  edgeSchemas: ReadonlyMap<string, EdgeSchemaEntry>;\n  options: ResolvedImportOptions;\n  runtime: ReturnType<typeof storeRuntime<G>>;\n  batchPointRead: BundleVerdictOf<typeof BATCH_POINT_READ>;\n  uniqueSidecarBatch: BundleVerdictOf<typeof UNIQUE_SIDECAR_BATCH>;\n  statementExecution: BundleVerdictOf<typeof STATEMENT_EXECUTION>;\n}>;\n\n/**\n * One row-work attempt of an import's write plan — the function\n * `importGraphData` hands to `runWritePlan` as its `rowWork`. Builds fresh\n * attempt state via {@link createImportAttemptState}, threads it through node,\n * identity-fold, and edge processing, and returns it, so a rolled-back\n * attempt leaves nothing behind for a later one to read.\n *\n * Exported for `tests/transaction-retry.test.ts` ONLY, which drives this\n * function directly through `runRetriedUnit` and a fault-injected backend to\n * prove attempt state is fresh every time. Import itself is NOT routed\n * through the retry owner in this stage: `importGraphData` still calls this\n * function exactly once, through its own single-attempt `runWritePlan`. No\n * published entrypoint re-exports it.\n */\nexport async function runImportWritePlanAttempt<G extends GraphDef>(\n  inputs: ImportAttemptInputs<G>,\n  session: WriteSession,\n  target: WriteTarget,\n  overlaidSession: OverlaidSessionMint<\"mixed\">,\n  transactionMode: WriteTransactionMode,\n): Promise<ImportAttemptState> {\n  const { result, errors, importedNodeIds } = createImportAttemptState();\n  let nextEdgeSavepointId = 0;\n  const frame: ImportWriteFrame = {\n    session,\n    target,\n    allocateEdgeSavepoint: () =>\n      `typegraph_import_edge_row_${++nextEdgeSavepointId}`,\n    transactionMode,\n    overlaidSession,\n    batchPointRead: inputs.batchPointRead,\n    uniqueSidecarBatch: inputs.uniqueSidecarBatch,\n    statementExecution: inputs.statementExecution,\n  };\n  await processNodes(\n    frame,\n    inputs.graphId,\n    inputs.registry,\n    inputs.data.nodes,\n    inputs.nodeSchemas,\n    inputs.options,\n    result,\n    errors,\n    importedNodeIds,\n  );\n  await inputs.runtime.foldImportedIdentityNodes(\n    target,\n    inputs.data.nodes\n      .filter((node) => importedNodeIds.has(makeNodeKey(node.kind, node.id)))\n      .map((node) => ({ kind: node.kind, id: node.id })),\n  );\n  await processEdges(\n    frame,\n    inputs.graphId,\n    inputs.registry,\n    inputs.data.edges,\n    inputs.edgeSchemas,\n    inputs.nodeSchemas,\n    inputs.options,\n    result,\n    errors,\n    importedNodeIds,\n  );\n  if (inputs.data.identity !== undefined) {\n    await importIdentitySection(\n      inputs.runtime,\n      target,\n      inputs.graphId,\n      inputs.data.identity,\n      result,\n      errors,\n    );\n  }\n  return { result, errors, importedNodeIds };\n}\n\nasync function importGraphData<G extends GraphDef>(\n  store: Store<G>,\n  data: GraphData,\n  options: ResolvedImportOptions,\n): Promise<ImportResult> {\n  // Reject an identity payload aimed at an identity-disabled graph, and\n  // runtime-validate the (bounded) identity section, BEFORE any entity write —\n  // see assertIdentityImportSupported / validateIdentitySection.\n  assertIdentityImportSupported(store, data.identity !== undefined);\n  validateIdentitySection(data.identity);\n\n  const graph = store.graph;\n  const graphId = store.graphId;\n  const backend = storeBackend(store);\n  const runtime = storeRuntime(store);\n  const registry = store.registry;\n  // Resolved ONCE against the caller-visible ROOT backend, then threaded into\n  // the write-plan context and every transaction frame (ruling B8 spec item\n  // 2). Never re-resolve against a transaction target: the verdict answers\n  // what the backend promises, while the binder separately proves that the\n  // actual port can serve that promise and fails loud on a mismatch.\n  const batchPointRead = batchPointReadVerdict(backend);\n  const uniqueSidecarBatch = uniqueSidecarBatchVerdict(backend);\n  const statementExecution = statementExecutionVerdict(backend);\n\n  // Fenced or refused, before any write. An import writes claim rows like every\n  // other writer, but it takes no per-graph lock and it is not covered by\n  // `runInWriteTransaction`'s refusal, because it declares no\n  // `fencesConstraintProbe` (that option also decides the lock, and a per-graph\n  // mutex held for a whole bulk load is a different decision — see\n  // `graphOwesClaims`). So it asks the same question directly. The subject is\n  // the graph rather than the payload deliberately: `importGraphStream` imports\n  // per chunk and cannot see the whole payload, and refusing on chunk k with\n  // k-1 chunks committed is a worse answer than refusing up front.\n  const owedClaimReason = graphOwesClaims(graph, registry);\n  const claimRefusal =\n    owedClaimReason === undefined ? undefined : (\n      constraintFenceRefusal({ graphId }, backend, owedClaimReason)\n    );\n  if (claimRefusal !== undefined) throw claimRefusal;\n\n  // Build lookup maps for schema validation\n  const nodeSchemas = buildNodeSchemaMap(graph);\n  const edgeSchemas = buildEdgeSchemaMap(graph);\n  for (const [kind, entry] of edgeSchemas) {\n    assertEdgeMatchIdentityBackendSupport(\n      entry.registration.matchIdentity,\n      backend.capabilities,\n      kind,\n    );\n  }\n\n  // Fixed across every attempt a single write-plan callback runs; built once,\n  // never mutated, and threaded into runImportWritePlanAttempt so the same\n  // schema maps, verdicts, and request pieces reach whichever attempt(s) run.\n  const attemptInputs: ImportAttemptInputs<G> = {\n    graphId,\n    registry,\n    data,\n    nodeSchemas,\n    edgeSchemas,\n    options,\n    runtime,\n    batchPointRead,\n    uniqueSidecarBatch,\n    statementExecution,\n  };\n\n  // One transaction on a transactional backend; runs directly otherwise, with\n  // the per-graph write lock taken before any row work — see runWritePlan and\n  // the runInWriteTransaction contract underneath it, the shared\n  // lock-before-rows discipline every writer follows. A single, unretried\n  // attempt in this stage — see runImportWritePlanAttempt's doc comment.\n  const { result, errors } = await runWritePlan(\n    {\n      graphId,\n      registry,\n      // Interning (`createClaimsVerdictThunk`'s `WeakMap`) makes this the SAME\n      // thunk object the store's own operations use for this backend — a\n      // second, independent memoization for the same backend is exactly what\n      // interning exists to rule out.\n      claimsVerdict: createClaimsVerdictThunk(backend),\n      uniqueSidecarBatch,\n      statementExecution,\n      schemaVersion: store.introspect().schemaVersion,\n      // `storeCaptureEnabled`, not the public `historyEnabled` getter: this\n      // feeds the write pipeline's `ctx.historyEnabled`, which decides\n      // whether node/edge-operations write to TypeGraph's own recorded\n      // relations — engine-native `history: true` never does, even though\n      // the public getter now answers `true` for it too.\n      historyEnabled: storeCaptureEnabled(store),\n      revisionTrackingEnabled: store.revisionTrackingEnabled,\n      revisionSchema: store.revisionSchema,\n      // HOW this caller takes position 3. `lockIdentityImportTarget` is\n      // `lockIdentityGraph` on an identity graph and a no-op otherwise, so the\n      // participation below is unconditional and the acquirer owns the\n      // \"identity is configured\" test, exactly as before the migration.\n      identityLock: (target) => runtime.lockIdentityImportTarget(target),\n    },\n    // An import writes node rows AND edge rows in one frame, so it declares the\n    // mixed family explicitly instead of receiving either narrower session.\n    mixedWritePlan(undefined, true),\n    backend,\n    (session, target, overlaidSession, _lock, transactionMode) =>\n      runImportWritePlanAttempt(\n        attemptInputs,\n        session,\n        target,\n        overlaidSession,\n        transactionMode,\n      ),\n  );\n\n  // A bulk load runs against stale planner statistics until ANALYZE runs\n  // (documented regressions: 0.5ms → 5ms traversals on Postgres, 0.9ms →\n  // 23ms fulltext on SQLite), so a mutating import refreshes them once,\n  // after the transaction commits.\n  //\n  // Best-effort: by this point the import is committed, so a failed\n  // statistics refresh must not convert the completed (non-atomic on some\n  // backends, non-retryable) import into a thrown failure — it degrades to\n  // a warning, and the caller can run `store.refreshStatistics()`.\n  await refreshStatisticsAfterImport(store, options, result, \"importGraph\");\n\n  return {\n    ...result,\n    success: errors.length === 0,\n    errors,\n  };\n}\n\n/**\n * Imports a header-first stream of bounded interchange chunks.\n *\n * Each chunk is committed through the same implementation as an in-memory\n * {@link importGraph}, so validation and conflict semantics stay identical; the\n * chunk calls skip only that function's own lease claim, which this loop already\n * holds on their behalf.\n * Chunks are individually atomic on transactional backends; a consumer needing\n * all-or-nothing behavior can import into a disposable working-copy backend and\n * publish it only after this function succeeds.\n *\n * Nodes must precede edges. Once a node chunk commits, edge validation reads the\n * target store rather than retaining every imported node id in memory.\n *\n * Refused with a typed {@link ConfigurationError} when the target writes through\n * a serialized database connection that another long-lived interchange stream\n * already holds — either because this stream came from a snapshot export on that\n * connection, or because ANY export snapshot or streaming import holds it when\n * the first chunk arrives (which covers a stream the caller has wrapped). The\n * error's `details.heldBy` names the holder's kind and `details.code` the\n * condition: `INTERCHANGE_SHARED_SERIALIZED_BACKEND_SNAPSHOT` (or\n * `INTERCHANGE_SAME_SQLITE_BACKEND_SNAPSHOT`) behind an export snapshot,\n * `INTERCHANGE_SERIALIZED_IMPORT_IN_PROGRESS` behind another import.\n *\n * Once accepted, the import holds that connection's one stream lease for the\n * whole call — every chunk AND the trailing statistics refresh, which is a\n * write like any other — so any export snapshot or second import that tries to\n * start while a write of this import is still to come is the side refused, and\n * this import keeps running instead of stalling against a transaction it can\n * never write past.\n *\n * Connections we cannot observe are not detected: two clients dialed at one\n * server, or two SQLite handles on one file, are independent and are not\n * refused. Neither is a connection whose driver we cannot positively identify as\n * single-connection — see the residual gap documented in\n * `backend/transaction-resource.ts`.\n */\nexport async function importGraphStream<G extends GraphDef>(\n  target: ImportTarget<G>,\n  chunks: AsyncIterable<GraphInterchangeChunk>,\n  rawOptions: ImportOptions,\n): Promise<ImportResult> {\n  const store = resolveIngestionImportTarget<G>(target);\n  const options = ImportOptionsSchema.parse(rawOptions);\n  const sourceBackend = exportStreamBackend(chunks);\n  const targetBackend = storeBackend(store);\n  // Whether this export would hold the connection the import writes through is\n  // decided by the single owner of that predicate — including the\n  // `execution.interactiveTransactions: false` abstention, where nothing is held open and refusing\n  // would refuse work that succeeds.\n  const contention =\n    sourceBackend === undefined ? undefined : (\n      snapshotExportContention(sourceBackend, targetBackend)\n    );\n  if (contention !== undefined) {\n    throw serializedStreamRefusal({\n      graphId: store.graphId,\n      requested: \"import-stream\",\n      heldBy: \"export-snapshot\",\n      detector: contention,\n    });\n  }\n  const result = emptyImportResult();\n  let header: GraphDataHeader | undefined;\n  let receivedEdges = false;\n  let receivedIdentity = false;\n  let releaseImportLease: (() => void) | undefined;\n\n  try {\n    for await (const chunk of chunks) {\n      // The pre-flight check above needs the stream to still identify its source\n      // backend, which any user wrapper (a delegating generator, `Readable.from`,\n      // a tee) erases. By the time the FIRST chunk arrives the export's snapshot\n      // transaction is already open and the registry says so itself, so a wrapped\n      // stream fails the same way an unwrapped one does instead of stalling\n      // behind a transaction that cannot end until this loop does.\n      //\n      // The claim is EXCLUSIVE and its check-and-register is one synchronous\n      // section inside `acquireSerializedStreamLease`, so the two long-lived\n      // streams can never both conclude the connection was free — and the\n      // holder it reports may be an export snapshot OR another streaming\n      // import, which nests its chunk transactions inside this one's just as\n      // fatally. Whoever gets here second is refused; an export starting\n      // mid-import is refused by `exportGraphStream` claiming the same lease, so\n      // an import whose earlier chunks are already committed is never aborted\n      // for someone else's stream. Nothing between the claim and the assignment\n      // can throw, so the `finally` below owns every release path.\n      if (releaseImportLease === undefined) {\n        const lease = acquireSerializedStreamLease(\n          targetBackend,\n          \"import-stream\",\n        );\n        if (!lease.acquired) {\n          throw serializedStreamRefusal({\n            graphId: store.graphId,\n            requested: \"import-stream\",\n            heldBy: lease.heldBy,\n          });\n        }\n        releaseImportLease = lease.release;\n      }\n      switch (chunk.type) {\n        case \"header\": {\n          if (header !== undefined) {\n            throw new Error(\n              \"Graph interchange stream emitted more than one header.\",\n            );\n          }\n          // The header is bounded, so validate it at the runtime stream\n          // boundary. In particular, an invalid identity profile/mode must not\n          // slip through merely because the stream's identity assertion chunk is\n          // empty.\n          validateStreamHeader(chunk.header);\n          // Reject an identity-bearing header aimed at an identity-disabled\n          // graph before any chunk is processed, matching importGraph's guard.\n          assertIdentityImportSupported(\n            store,\n            chunk.header.identity !== undefined,\n          );\n          header = chunk.header;\n          break;\n        }\n        case \"nodes\": {\n          if (header === undefined) {\n            throw new Error(\n              \"Graph interchange stream must start with a header.\",\n            );\n          }\n          if (receivedEdges || receivedIdentity) {\n            throw new Error(\n              `Graph interchange stream cannot emit nodes after ${\n                receivedEdges ? \"edges\" : \"identity assertions\"\n              }.`,\n            );\n          }\n          if (chunk.nodes.length === 0) break;\n          mergeImportResult(\n            result,\n            await importGraphData(\n              store,\n              graphDataForChunk(header, chunk.nodes, [], []),\n              {\n                ...options,\n                refreshStatistics: false,\n              },\n            ),\n          );\n          throwIfStreamChunkFailed(result, options);\n          break;\n        }\n        case \"edges\": {\n          if (header === undefined) {\n            throw new Error(\n              \"Graph interchange stream must start with a header.\",\n            );\n          }\n          if (receivedIdentity) {\n            throw new Error(\n              \"Graph interchange stream cannot emit edges after identity assertions.\",\n            );\n          }\n          receivedEdges = true;\n          if (chunk.edges.length === 0) break;\n          mergeImportResult(\n            result,\n            await importGraphData(\n              store,\n              graphDataForChunk(header, [], chunk.edges, []),\n              {\n                ...options,\n                refreshStatistics: false,\n              },\n            ),\n          );\n          throwIfStreamChunkFailed(result, options);\n          break;\n        }\n        case \"identity\": {\n          if (header === undefined) {\n            throw new Error(\n              \"Graph interchange stream must start with a header.\",\n            );\n          }\n          if (header.identity === undefined) {\n            throw new Error(\n              \"Graph interchange stream emitted identity rows without an identity header.\",\n            );\n          }\n          receivedIdentity = true;\n          if (chunk.assertions.length === 0) break;\n          mergeImportResult(\n            result,\n            await importGraphData(\n              store,\n              graphDataForChunk(header, [], [], chunk.assertions),\n              { ...options, refreshStatistics: false },\n            ),\n          );\n          throwIfStreamChunkFailed(result, options);\n          break;\n        }\n      }\n    }\n    if (header === undefined) {\n      throw new Error(\n        \"Graph interchange stream ended before emitting a header.\",\n      );\n    }\n    // The trailing ANALYZE is a WRITE on the target connection, exactly like\n    // the chunks were, so it belongs inside the lease rather than after it.\n    // Releasing at the end of the chunk loop instead left this write outside\n    // every guard: on a serialized connection an export snapshot opening in\n    // that window takes the one connection ANALYZE has to run on and does not\n    // give it back until the export ends, and the refresh's best-effort\n    // handling swallowed the result as a warning. The lease now spans every\n    // write this call makes — the same span `withImportStreamLease` gives\n    // `importGraph`, whose refresh has always been inside it.\n    await refreshStatisticsAfterImport(\n      store,\n      options,\n      result,\n      \"importGraphStream\",\n    );\n  } finally {\n    // One release for every exit — the loop's, the missing-header throw, and\n    // the refresh's — so \"the lease lives exactly as long as the writes\" holds\n    // on the error paths too.\n    releaseImportLease?.();\n  }\n  return { ...result, success: result.errors.length === 0 };\n}\n\n/**\n * The single owner of the refusal raised when two long-lived interchange streams\n * would run on one serialized database connection — from the import's pre-flight\n * check on the stream's own backend, from its mid-stream claim, and from\n * `exportGraphStream`'s claim alike, so every path states the same detected\n * condition in the same vocabulary.\n *\n * The CODE names the condition — which kind of stream holds the connection —\n * rather than which side was refused. `INTERCHANGE_SAME_SQLITE_BACKEND_SNAPSHOT`\n * is not a second condition: it reports that the object-identity DETECTOR\n * answered (one SQLite backend exporting into itself), which is worth telling\n * apart because the fix differs — pass a second backend, rather than await\n * whatever else is running. `details.heldBy`\n * and `details.requested` then say which pairing was actually refused, so a\n * same-kind refusal (import behind import, export behind export) is never\n * reported as something it is not:\n *\n * | holder          | code                                          |\n * | --------------- | --------------------------------------------- |\n * | export snapshot | `INTERCHANGE_SHARED_SERIALIZED_BACKEND_SNAPSHOT` (or `INTERCHANGE_SAME_SQLITE_BACKEND_SNAPSHOT` when the object-identity detector answered) |\n * | import stream   | `INTERCHANGE_SERIALIZED_IMPORT_IN_PROGRESS`   |\n *\n * Every message describes exactly what is detected. None claims anything about\n * connections we cannot observe (two clients dialed at the same server, two\n * SQLite handles on one file), which are independent and are not refused.\n */\nexport function serializedStreamRefusal(\n  input: Readonly<{\n    graphId: string;\n    requested: SerializedStreamKind;\n    heldBy: SerializedStreamKind;\n    /**\n     * Which detector found the holding export snapshot, when the import's\n     * pre-flight — not the lease — is what answered. Only\n     * `\"same-sqlite-backend\"` changes the code, because only that detector\n     * identifies a distinguishable situation for the caller: the source and the\n     * target are the same SQLite backend object, which no ordering can fix.\n     */\n    detector?: SnapshotExportContention;\n  }>,\n): ConfigurationError {\n  const { graphId, requested, heldBy, detector } = input;\n  const code =\n    heldBy === \"import-stream\" ? SERIALIZED_IMPORT_IN_PROGRESS_CODE\n    : detector === \"same-sqlite-backend\" ?\n      \"INTERCHANGE_SAME_SQLITE_BACKEND_SNAPSHOT\"\n    : \"INTERCHANGE_SHARED_SERIALIZED_BACKEND_SNAPSHOT\";\n  const { message, suggestion } = serializedStreamRefusalText(\n    requested,\n    heldBy,\n  );\n  return new ConfigurationError(\n    message,\n    { code, graphId, requested, heldBy },\n    { suggestion },\n  );\n}\n\n/**\n * The refusal code for \"a streaming import holds the connection this stream\n * needs\", in either of the two orders it can be discovered.\n */\nconst SERIALIZED_IMPORT_IN_PROGRESS_CODE =\n  \"INTERCHANGE_SERIALIZED_IMPORT_IN_PROGRESS\";\n\n/**\n * What each of the four pairings actually does to the one connection. Each\n * message names both streams, because \"a stream already holds this connection\"\n * is not actionable without knowing which one.\n */\nfunction serializedStreamRefusalText(\n  requested: SerializedStreamKind,\n  heldBy: SerializedStreamKind,\n): Readonly<{ message: string; suggestion: string }> {\n  if (heldBy === \"export-snapshot\") {\n    return requested === \"import-stream\" ?\n        {\n          message:\n            \"A snapshot export cannot be streamed into a target that writes through the same serialized database connection: the export's read transaction holds that connection open for the whole stream, so this import can never take the writer slot it needs.\",\n          suggestion:\n            \"Export to a file first, or import the stream into an independent backend.\",\n        }\n      : {\n          message:\n            \"A snapshot export cannot open on a serialized database connection while another snapshot export is streaming from it: the second export's read transaction would have to nest inside the first one on the single connection they share.\",\n          suggestion:\n            \"Await the export already in flight before starting the next one, or export from an independent backend.\",\n        };\n  }\n  return requested === \"export-snapshot\" ?\n      {\n        message:\n          \"A snapshot export cannot open on a serialized database connection while a streaming import is writing through it: the export's read transaction would hold the one connection the import's next chunk has to write on.\",\n        suggestion:\n          \"Await the import before exporting, or export from an independent backend.\",\n      }\n    : {\n        message:\n          \"A streaming import cannot open on a serialized database connection while another streaming import is writing through it: the two imports commit their chunks on the single connection they share, so the second one's chunk transaction would have to nest inside the first one's.\",\n        suggestion:\n          \"Await the import already in flight before starting the next one, or import into an independent backend.\",\n      };\n}\n\nexport function summarizeImportErrors(errors: readonly ImportError[]): string {\n  return errors\n    .map(\n      (entry) =>\n        `${entry.entityType} ${entry.kind} ${entry.id}: ${entry.error}`,\n    )\n    .join(\"; \");\n}\n\nfunction throwIfStreamChunkFailed(\n  result: ImportResult,\n  options: ResolvedImportOptions,\n): void {\n  if (options.onStreamChunkError === \"continue\" || result.errors.length === 0) {\n    return;\n  }\n  throw new Error(\n    \"Graph interchange stream aborted after a chunk reported import errors. \" +\n      `Reported errors: ${summarizeImportErrors(result.errors)}. ` +\n      'Earlier chunks remain committed; use onStreamChunkError: \"continue\" for best-effort ingestion.',\n  );\n}\n\n/**\n * Rejects an identity payload aimed at an identity-disabled graph BEFORE any\n * entity write. The internal identity import coordinator raises the same\n * typed `ConfigurationError` (code `IDENTITY_IMPORT_REQUIRES_PROFILE`), but only\n * after `processNodes`/`processEdges` have run — a partial write on a\n * non-transactional backend — and only for a NON-empty assertions array (an\n * empty envelope short-circuits and silently succeeds there). This guard fires\n * first and regardless of assertion count.\n */\nfunction assertIdentityImportSupported<G extends GraphDef>(\n  store: Store<G>,\n  hasIdentitySection: boolean,\n): void {\n  if (hasIdentitySection && store.graph.identity === undefined) {\n    throw new ConfigurationError(\n      \"Cannot import identity assertions into an identity-disabled graph.\",\n      { code: \"IDENTITY_IMPORT_REQUIRES_PROFILE\", graphId: store.graphId },\n    );\n  }\n}\n\n/**\n * Runtime-validates just the identity section of an otherwise pre-typed\n * `GraphData`. {@link importGraph} deliberately trusts the type for the\n * (potentially graph-sized) node and edge arrays to preserve its per-row\n * performance, but a JS caller can still smuggle an out-of-domain `relation` or\n * a non-canonical timestamp straight into SQL — which SQLite accepts and\n * PostgreSQL rejects, a backend-parity divergence. The identity section is\n * bounded, so parsing only it closes that gap without the whole-envelope cost.\n */\nfunction validateIdentitySection(identity: GraphData[\"identity\"]): void {\n  if (identity === undefined) return;\n  const parsed = InterchangeIdentitySchema.safeParse(identity);\n  if (parsed.success) return;\n  throw new ValidationError(\n    `Invalid identity interchange section: ${parsed.error.message}`,\n    {\n      issues: parsed.error.issues.map((issue) => ({\n        path: issue.path.join(\".\"),\n        message: issue.message,\n        code: issue.code,\n      })),\n    },\n    { cause: parsed.error },\n  );\n}\n\n/**\n * An identity assertion is neither a node nor an edge, so it carries its own\n * `entityType`. The identity analogue of a node or edge kind is the relation\n * asserted, and the entity id is the assertion id. A failure that cannot be\n * attributed to a document assertion — which the coordinator's own error\n * details should always allow — falls back to naming the target graph, so the\n * entry still reaches the caller rather than being dropped or rethrown.\n */\nconst IDENTITY_IMPORT_ERROR_ENTITY_TYPE = \"identity\";\nconst IDENTITY_IMPORT_ERROR_PATH = \"identity.assertions\";\nconst UNATTRIBUTED_IDENTITY_ERROR_KIND = \"assertion\";\nconst IDENTITY_IMPORT_ID_CONFLICT_CODE = \"IDENTITY_IMPORT_ID_CONFLICT\";\n\nfunction identityImportError(\n  assertion: InterchangeIdentityAssertion | undefined,\n  graphId: string,\n  message: string,\n): ImportError {\n  const path =\n    assertion === undefined ?\n      IDENTITY_IMPORT_ERROR_PATH\n    : `${IDENTITY_IMPORT_ERROR_PATH}[${assertion.id}]`;\n  return {\n    entityType: IDENTITY_IMPORT_ERROR_ENTITY_TYPE,\n    kind: assertion?.relation ?? UNATTRIBUTED_IDENTITY_ERROR_KIND,\n    id: assertion?.id ?? graphId,\n    error: `${path}: ${message}`,\n  };\n}\n\nfunction isIdConflictError(error: unknown): error is ConfigurationError {\n  return (\n    error instanceof ConfigurationError &&\n    error.details[\"code\"] === IDENTITY_IMPORT_ID_CONFLICT_CODE\n  );\n}\n\nfunction touchesRef(\n  assertion: InterchangeIdentityAssertion,\n  ref: Readonly<{ kind: string; id: string }>,\n): boolean {\n  return (\n    (assertion.a.kind === ref.kind && assertion.a.id === ref.id) ||\n    (assertion.b.kind === ref.kind && assertion.b.id === ref.id)\n  );\n}\n\n/**\n * Converts a per-document identity failure into an {@link ImportError}, or\n * returns `undefined` for anything that is not one — a configuration or\n * programming fault must still propagate.\n */\nfunction asIdentityImportError(\n  assertions: readonly InterchangeIdentityAssertion[],\n  graphId: string,\n  error: unknown,\n): ImportError | undefined {\n  // The coordinator tags the error with the id of the assertion it was\n  // APPLYING — exact attribution. The endpoint heuristics below are only the\n  // fallback for an untagged error: they pick the first assertion touching\n  // the endpoints, which is wrong whenever an earlier assertion over the same\n  // pair succeeded.\n  const tagged = taggedAssertion(assertions, error);\n  if (error instanceof NodeNotFoundError) {\n    const ref = error.details;\n    const assertion =\n      tagged ?? assertions.find((candidate) => touchesRef(candidate, ref));\n    return identityImportError(assertion, graphId, error.message);\n  }\n  if (error instanceof IdentityContradictionError) {\n    const { a, b } = error.details;\n    const assertion =\n      tagged ??\n      assertions.find(\n        (candidate) => touchesRef(candidate, a) && touchesRef(candidate, b),\n      );\n    return identityImportError(assertion, graphId, error.message);\n  }\n  if (isIdConflictError(error)) {\n    const assertion = assertions.find(\n      (candidate) => candidate.id === error.details[\"assertionId\"],\n    );\n    return identityImportError(assertion, graphId, error.message);\n  }\n  if (isIdentityAssertionValidationError(error)) {\n    const issue = error.details.issues[0];\n    const message =\n      issue === undefined ?\n        error.message\n      : `${error.message} (${issue.message})`;\n    return identityImportError(\n      assertions.find((candidate) => candidate.id === issue?.assertionId),\n      graphId,\n      message,\n    );\n  }\n  return undefined;\n}\n\n/**\n * The assertion the coordinator tagged onto the error via\n * `IDENTITY_IMPORT_FAILED_ASSERTION` — exact, structural attribution for any\n * error shape.\n */\nfunction taggedAssertion(\n  assertions: readonly InterchangeIdentityAssertion[],\n  error: unknown,\n): InterchangeIdentityAssertion | undefined {\n  if (typeof error !== \"object\" || error === null) return undefined;\n  const id = (error as Record<PropertyKey, unknown>)[\n    IDENTITY_IMPORT_FAILED_ASSERTION\n  ];\n  if (typeof id !== \"string\") return undefined;\n  return assertions.find((candidate) => candidate.id === id);\n}\n\n/**\n * A `ValidationError` the identity import coordinator raised about assertion\n * CONTENT (ended rows in state mode, out-of-bounds validity windows, unknown\n * kinds, unnormalized pairs, self-assertions). Every issue it emits is pathed\n * at `identity.assertions` and carries the offending assertion's id\n * structurally in `assertionId` — attribution never parses the\n * human-readable message. A validation error shaped any other way is a\n * document-shape or programming fault and must still propagate.\n */\nfunction isIdentityAssertionValidationError(\n  error: unknown,\n): error is ValidationError {\n  return (\n    error instanceof ValidationError &&\n    error.details.issues.length > 0 &&\n    error.details.issues.every(\n      (issue) =>\n        issue.path === \"identity.assertions\" && issue.assertionId !== undefined,\n    )\n  );\n}\n\n/**\n * Applies the identity section, recording a per-document failure in\n * `result.errors` instead of aborting the whole import.\n *\n * {@link importGraph} promises `{ success: false, errors }` for content the\n * target rejects, and the node and edge paths honor that by recording the\n * offending row and moving on. The identity coordinator instead throws, so a\n * missing endpoint, a contradiction against the target graph, or a reused\n * assertion id escaped the transaction and turned a rejected assertion into a\n * thrown import — discarding the valid node and edge work alongside it.\n *\n * Assertions the coordinator applied before the failing one stay committed,\n * exactly as rows accepted before a failing node do. The tagged error carries\n * the coordinator's completed counts so the returned result describes those\n * durable partial effects accurately.\n */\nasync function importIdentitySection<G extends GraphDef>(\n  runtime: ReturnType<typeof storeRuntime<G>>,\n  target: IdentityTarget,\n  graphId: string,\n  identity: NonNullable<GraphData[\"identity\"]>,\n  result: ImportResult,\n  errors: ImportError[],\n): Promise<void> {\n  try {\n    const summary = await runtime.importIdentityAssertionsAtTarget(\n      target,\n      identity.assertions,\n      identity.mode,\n    );\n    result.identity.created += summary.created;\n    result.identity.skipped += summary.skipped;\n  } catch (error) {\n    const entry = asIdentityImportError(identity.assertions, graphId, error);\n    if (entry === undefined) throw error;\n    const progress = identityImportProgress(error);\n    result.identity.created += progress.created;\n    result.identity.skipped += progress.skipped;\n    errors.push(entry);\n  }\n}\n\nfunction identityImportProgress(\n  error: unknown,\n): Readonly<{ created: number; skipped: number }> {\n  if (typeof error !== \"object\" || error === null) {\n    return { created: 0, skipped: 0 };\n  }\n  const progress = (error as Record<PropertyKey, unknown>)[\n    IDENTITY_IMPORT_PROGRESS\n  ];\n  if (\n    typeof progress !== \"object\" ||\n    progress === null ||\n    !(\"created\" in progress) ||\n    typeof progress.created !== \"number\" ||\n    !(\"skipped\" in progress) ||\n    typeof progress.skipped !== \"number\"\n  ) {\n    return { created: 0, skipped: 0 };\n  }\n  return { created: progress.created, skipped: progress.skipped };\n}\n\nfunction validateStreamHeader(header: GraphDataHeader): void {\n  const parsed = GraphDataHeaderSchema.safeParse(header);\n  if (parsed.success) return;\n  throw new ValidationError(\n    `Invalid graph interchange stream header: ${parsed.error.message}`,\n    {\n      issues: parsed.error.issues.map((issue) => ({\n        path: issue.path.join(\".\"),\n        message: issue.message,\n        code: issue.code,\n      })),\n    },\n    { cause: parsed.error },\n  );\n}\n\nfunction emptyImportResult(): ImportResult {\n  return {\n    success: true,\n    nodes: { created: 0, updated: 0, skipped: 0 },\n    edges: { created: 0, updated: 0, skipped: 0 },\n    identity: { created: 0, skipped: 0 },\n    errors: [],\n  };\n}\n\nfunction graphDataForChunk(\n  header: GraphDataHeader,\n  nodes: GraphData[\"nodes\"],\n  edges: GraphData[\"edges\"],\n  assertions: readonly InterchangeIdentityAssertion[],\n): GraphData {\n  const { identity, ...headerWithoutIdentity } = header;\n  return {\n    ...headerWithoutIdentity,\n    nodes,\n    edges,\n    ...(identity === undefined ?\n      {}\n    : {\n        identity: { ...identity, assertions: [...assertions] },\n      }),\n  };\n}\nfunction mergeImportResult(target: ImportResult, source: ImportResult): void {\n  target.nodes.created += source.nodes.created;\n  target.nodes.updated += source.nodes.updated;\n  target.nodes.skipped += source.nodes.skipped;\n  target.edges.created += source.edges.created;\n  target.edges.updated += source.edges.updated;\n  target.edges.skipped += source.edges.skipped;\n  target.identity.created += source.identity.created;\n  target.identity.skipped += source.identity.skipped;\n  target.errors.push(...source.errors);\n}\n\n/**\n * Refreshes planner statistics after a mutating import.\n *\n * CALLED UNDER THE TARGET CONNECTION'S STREAM LEASE by every surface: ANALYZE\n * is a write, and a write that runs outside the lease can be stranded by an\n * export snapshot that takes the one connection it needs. `importGraph` holds\n * the lease through {@link withImportStreamLease} for its whole call;\n * `importGraphStream` holds its chunk-loop lease across this call too.\n *\n * Best-effort: by this point the import is committed, so a failed statistics\n * refresh must not convert the completed (non-atomic on some backends,\n * non-retryable) import into a thrown failure — it degrades to a warning, and\n * the caller can run `store.refreshStatistics()`.\n */\nasync function refreshStatisticsAfterImport<G extends GraphDef>(\n  store: Store<G>,\n  options: ResolvedImportOptions,\n  result: ImportResult,\n  surface: \"importGraph\" | \"importGraphStream\",\n): Promise<void> {\n  const mutationCount =\n    result.nodes.created +\n    result.nodes.updated +\n    result.edges.created +\n    result.edges.updated +\n    result.identity.created;\n  if ((options.refreshStatistics ?? true) && mutationCount > 0) {\n    try {\n      await store.refreshStatistics();\n    } catch (error) {\n      if (\n        typeof console !== \"undefined\" &&\n        typeof console.warn === \"function\"\n      ) {\n        console.warn(\n          `[typegraph] ${surface} committed its rows but the follow-up ` +\n            \"statistics refresh failed; run store.refreshStatistics() to \" +\n            \"give the planner fresh statistics.\",\n          error,\n        );\n      }\n    }\n  }\n}\n\n// ============================================================\n// Schema Maps\n// ============================================================\n\n/**\n * Exported so it can appear (structurally, via {@link ImportAttemptInputs}) in\n * the declaration file for the test-only {@link runImportWritePlanAttempt} —\n * not otherwise part of any published entrypoint.\n */\nexport type NodeSchemaEntry = Readonly<{\n  registration: NodeRegistration;\n  schema: z.ZodObject<z.ZodRawShape>;\n}>;\n\n/** See {@link NodeSchemaEntry}. */\nexport type EdgeSchemaEntry = Readonly<{\n  registration: EdgeRegistration;\n  schema: z.ZodObject<z.ZodRawShape>;\n}>;\n\n/**\n * Exported alongside {@link runImportWritePlanAttempt} so\n * `tests/transaction-retry.test.ts` can build a real\n * {@link ImportAttemptInputs} without hand-rolling the registration shape a\n * schema-map entry carries. Not otherwise part of any published entrypoint.\n */\nexport function buildNodeSchemaMap(\n  graph: GraphDef,\n): ReadonlyMap<string, NodeSchemaEntry> {\n  const map = new Map<string, NodeSchemaEntry>();\n\n  for (const kindName of getNodeKinds(graph)) {\n    const registration = graph.nodes[kindName] as NodeRegistration;\n    map.set(kindName, {\n      registration,\n      schema: registration.type.schema,\n    });\n  }\n\n  return map;\n}\n\n/** See {@link buildNodeSchemaMap}. */\nexport function buildEdgeSchemaMap(\n  graph: GraphDef,\n): ReadonlyMap<string, EdgeSchemaEntry> {\n  const map = new Map<string, EdgeSchemaEntry>();\n\n  for (const kindName of getEdgeKinds(graph)) {\n    const registration = graph.edges[kindName] as EdgeRegistration;\n    map.set(kindName, {\n      registration,\n      schema: registration.type.schema,\n    });\n  }\n\n  return map;\n}\n\n// ============================================================\n// Node Processing\n// ============================================================\n\nasync function processNodes(\n  frame: ImportWriteFrame,\n  graphId: string,\n  registry: KindRegistry,\n  nodes: readonly InterchangeNode[],\n  schemas: ReadonlyMap<string, NodeSchemaEntry>,\n  options: ResolvedImportOptions,\n  result: ImportResult,\n  errors: ImportError[],\n  importedNodeIds: Set<string>,\n): Promise<void> {\n  const batchSize = options.batchSize;\n\n  for (let index = 0; index < nodes.length; index += batchSize) {\n    const batch = nodes.slice(index, index + batchSize);\n    await processNodeSlice(\n      frame,\n      graphId,\n      registry,\n      batch,\n      schemas,\n      options,\n      result,\n      errors,\n      importedNodeIds,\n    );\n  }\n}\n\nfunction recordNodeOutcome(\n  node: InterchangeNode,\n  outcome: ProcessResult,\n  result: ImportResult,\n  errors: ImportError[],\n  importedNodeIds: Set<string>,\n): void {\n  switch (outcome.status) {\n    case \"created\": {\n      result.nodes.created++;\n      importedNodeIds.add(makeNodeKey(node.kind, node.id));\n      break;\n    }\n    case \"updated\": {\n      result.nodes.updated++;\n      importedNodeIds.add(makeNodeKey(node.kind, node.id));\n      break;\n    }\n    case \"skipped\": {\n      result.nodes.skipped++;\n      // A live skipped row is still a valid edge endpoint; a tombstone\n      // is not.\n      if (outcome.liveTarget) {\n        importedNodeIds.add(makeNodeKey(node.kind, node.id));\n      }\n      break;\n    }\n    case \"error\": {\n      errors.push({\n        entityType: \"node\",\n        kind: node.kind,\n        id: node.id,\n        error: outcome.error,\n      });\n      break;\n    }\n  }\n}\n\ntype NodeImportCandidate = Readonly<{\n  node: InterchangeNode;\n  schemaEntry: NodeSchemaEntry;\n  props: Record<string, unknown>;\n  draft: NodeCreateDraft;\n}>;\n\n/**\n * Processes one batchSize slice of nodes with batched round trips:\n * one `getNodes` per kind for existence, one `checkUniqueBatch` per\n * (constraint, kind) for uniqueness pre-checks (both priming the shared\n * batch validation caches), then one fused batch create for the accepted\n * rows — the multi-row insert and its batched side effects, in that order,\n * as one session call. Per-row semantics are unchanged — conflicts route by\n * `onConflict`, a uniqueness conflict is a per-row error entry, and rows\n * repeating an id already seen in the slice defer to the per-row path after\n * the flush (so they observe the first occurrence's row exactly as the\n * sequential implementation did).\n */\nasync function processNodeSlice(\n  frame: ImportWriteFrame,\n  graphId: string,\n  registry: KindRegistry,\n  batch: readonly InterchangeNode[],\n  schemas: ReadonlyMap<string, NodeSchemaEntry>,\n  options: ResolvedImportOptions,\n  result: ImportResult,\n  errors: ImportError[],\n  importedNodeIds: Set<string>,\n): Promise<void> {\n  const record = (node: InterchangeNode, outcome: ProcessResult): void => {\n    recordNodeOutcome(node, outcome, result, errors, importedNodeIds);\n  };\n\n  // Pass 1 (synchronous): kind + property + validity validation, and\n  // in-slice duplicate deferral.\n  const candidates: NodeImportCandidate[] = [];\n  const deferred: InterchangeNode[] = [];\n  const seenKeys = new Set<string>();\n  for (const node of batch) {\n    const schemaEntry = schemas.get(node.kind);\n    if (!schemaEntry) {\n      record(node, {\n        status: \"error\",\n        error: `Unknown node kind: ${node.kind}`,\n      });\n      continue;\n    }\n    const propsResult = validateProperties(\n      node.properties,\n      schemaEntry.schema,\n      options.onUnknownProperty,\n    );\n    if (!propsResult.success) {\n      record(node, { status: \"error\", error: propsResult.error });\n      continue;\n    }\n    const validityError = validateValidityWindow(node);\n    if (validityError !== undefined) {\n      record(node, { status: \"error\", error: validityError });\n      continue;\n    }\n    const key = makeNodeKey(node.kind, node.id);\n    if (seenKeys.has(key)) {\n      deferred.push(node);\n      continue;\n    }\n    seenKeys.add(key);\n    candidates.push({\n      node,\n      schemaEntry,\n      props: propsResult.data,\n      draft: {\n        kind: node.kind,\n        id: node.id,\n        // Interchange rows always carry an explicit id.\n        idProvided: true,\n        nodeKind: schemaEntry.registration.type,\n        uniqueConstraints: schemaEntry.registration.unique ?? [],\n        validatedProps: propsResult.data,\n        // NodeCreateDraft.validFrom is string | undefined (never null) — it\n        // only feeds batch validation-cache priming, which never inspects\n        // it, so normalizing the explicit-NULL sentinel away here is inert.\n        // The actual insert (buildImportInsertParams) reads node.validFrom\n        // directly and preserves the null.\n        validFrom: node.validFrom ?? undefined,\n        validTo: node.validTo,\n      },\n    });\n  }\n\n  // Prime the validation caches with batched reads, then route each row\n  // against memory in input order.\n  const {\n    reads,\n    reader: validationBackend,\n    registerPendingNode,\n    registerPendingUniqueEntries,\n    registerAppliedNodeUpdate,\n    seedNodeRow,\n    seedUniqueRow,\n  } = createNodeBatchValidationSeams(graphId, registry, frame.target);\n  await primeBatchValidationCaches(\n    {\n      graphId,\n      registry,\n      batchPointRead: frame.batchPointRead,\n      uniqueSidecarBatch: frame.uniqueSidecarBatch,\n    },\n    candidates.map((candidate) => candidate.draft),\n    frame.target,\n    { seedNodeRow, seedUniqueRow },\n  );\n\n  // The in-slice update leg runs on a session over the pending-aware overlay,\n  // not on the frame's own: `reviseNode` plans its uniqueness through the same\n  // handle it writes with, and that plan must see a value an unflushed create\n  // EARLIER in this slice already reserved — so the row degrades to a per-row\n  // error exactly as the sequential path does, rather than claiming the key on\n  // the real backend and colliding with that create at flush (which would\n  // throw and roll back the whole import). The overlay overrides reads only;\n  // every write it is handed still lands on the real backend. The frame is\n  // handed the same read spec this slice reads through, so the two views\n  // cannot answer differently.\n  const overlaidSession = frame.overlaidSession(reads);\n  const accepted: NodeImportCandidate[] = [];\n  for (const candidate of candidates) {\n    const { node, schemaEntry, props } = candidate;\n    const uniqueConstraints = schemaEntry.registration.unique ?? [];\n    const existing = await validationBackend.getNode(\n      graphId,\n      node.kind,\n      node.id,\n    );\n\n    if (existing) {\n      switch (options.onConflict) {\n        case \"skip\": {\n          record(node, {\n            status: \"skipped\",\n            liveTarget: isLiveNodeRow(existing),\n          });\n          break;\n        }\n        case \"error\": {\n          record(node, {\n            status: \"error\",\n            error: `Node already exists: ${node.kind}:${node.id}`,\n          });\n          break;\n        }\n        case \"update\": {\n          if (!isLiveNodeRow(existing)) {\n            // Import never resurrects a tombstone — see processNode.\n            record(node, { status: \"skipped\", liveTarget: false });\n            break;\n          }\n          const updateWindow = validateUpdateValidityWindow(\n            node,\n            existing.valid_from,\n          );\n          if (!updateWindow.ok) {\n            record(node, { status: \"error\", error: updateWindow.error });\n            break;\n          }\n          const updateError = await updateImportedNode(overlaidSession, node, {\n            existing,\n            schema: schemaEntry.registration.type.schema,\n            validatedProps: props,\n            uniqueConstraints,\n            windowFence: updateWindow.value,\n          });\n          if (updateError === undefined) {\n            // The update mutated the real backend's uniqueness rows directly;\n            // reconcile the shared prime caches so a later create in this\n            // slice sees the post-update reservation state (matching the\n            // sequential path). See registerAppliedNodeUpdate.\n            registerAppliedNodeUpdate(\n              node.kind,\n              node.id,\n              rowPropsToObject(existing.props),\n              props,\n              uniqueConstraints,\n            );\n          }\n          record(\n            node,\n            updateError === undefined ?\n              { status: \"updated\" }\n            : { status: \"error\", error: updateError },\n          );\n          break;\n        }\n      }\n      continue;\n    }\n\n    // Both declared node constraints are probed here, per row, against the\n    // pending-aware overlay — so an in-slice pair (a `Person` and a `Company`\n    // sharing an id, two rows apart) is seen through `pendingNodes` and refuses\n    // the SECOND row while the first commits. The claim behind these probes is\n    // the fence for a concurrent violation, and that one aborts the import;\n    // this is the half that must not.\n    const constraintResult = await catchDeclaredConstraintRefusal(async () => {\n      await checkUniquenessConstraints(\n        { graphId, registry, backend: validationBackend },\n        node.kind,\n        node.id,\n        props,\n        uniqueConstraints,\n      );\n      await checkDisjointnessConstraint(\n        { graphId, registry, backend: validationBackend },\n        node.kind,\n        node.id,\n      );\n    });\n    if (!constraintResult.ok) {\n      record(node, { status: \"error\", error: constraintResult.error });\n      continue;\n    }\n\n    registerPendingNode(buildImportInsertParams(graphId, node, props));\n    registerPendingUniqueEntries(node.kind, node.id, props, uniqueConstraints);\n    accepted.push(candidate);\n  }\n\n  // Flush the accepted creates as ONE fused unit: the claim groups at their\n  // declared placements, the multi-row insert, then the batched sync fans\n  // (fulltext, embeddings). The session simply makes the group unbreakable. The\n  // pre-insert claims are what make an import fenced at all — this writer takes\n  // no per-graph lock, so a claim whose axis spans kinds is the only thing that\n  // can refuse a peer, and it has to be issued BEFORE the rows it gates or a\n  // refused batch would leave the violating rows behind for a caller that\n  // recovers per row. The NO-RETURN batch shape, because import discards the\n  // rows and the returning shape would emit a different statement.\n  if (accepted.length > 0) {\n    await frame.session.createNodesNoReturn(\n      accepted.map((candidate) =>\n        importNodeCreateWork(\n          graphId,\n          registry,\n          candidate.node,\n          candidate.schemaEntry.registration,\n          candidate.props,\n        ),\n      ),\n    );\n    for (const candidate of accepted) {\n      record(candidate.node, { status: \"created\" });\n    }\n  }\n\n  // In-slice duplicate ids run per-row AFTER the flush so they observe the\n  // first occurrence's committed row, exactly as the sequential path did.\n  for (const node of deferred) {\n    record(\n      node,\n      await processNode(frame, graphId, registry, node, schemas, options),\n    );\n  }\n}\n\nfunction buildImportInsertParams(\n  graphId: string,\n  node: InterchangeNode,\n  props: Record<string, unknown>,\n): Parameters<GraphBackend[\"insertNode\"]>[0] {\n  return {\n    graphId,\n    kind: node.kind,\n    id: node.id,\n    props,\n    ...(node.validFrom !== undefined && { validFrom: node.validFrom }),\n    ...(node.validTo !== undefined && { validTo: node.validTo }),\n  };\n}\n\n/**\n * The fused create unit for one imported node: the row params, the claims the\n * row owes, and the derived data it obliges, built together.\n *\n * ONE owner for all three, shared by the batched slice and the per-row fallback.\n * Before the migration each path spelled its own insert params, its own claim\n * seam call and its own side-effect record, which is the shape in which they\n * drift — and the shape in which a path forgets one of them entirely.\n */\nfunction importNodeCreateWork(\n  graphId: string,\n  registry: KindRegistry,\n  node: InterchangeNode,\n  registration: NodeRegistration,\n  props: Record<string, unknown>,\n): NodeCreateWork {\n  const claim = {\n    kind: node.kind,\n    id: node.id,\n    props,\n    constraints: registration.unique ?? [],\n  } satisfies NodeClaimItem;\n  return {\n    params: buildImportInsertParams(graphId, node, props),\n    claim,\n    claimPlan: planNodeCreateClaims({ graphId, registry }, claim),\n    sideEffects: {\n      kind: node.kind,\n      id: node.id,\n      schema: registration.type.schema,\n      props,\n      uniqueConstraints: registration.unique ?? [],\n    },\n    projections: [],\n  };\n}\n\ntype ProcessResult =\n  | { status: \"created\" }\n  | { status: \"updated\" }\n  /**\n   * `liveTarget` distinguishes \"skipped because a LIVE row already exists\"\n   * (a valid edge endpoint) from \"skipped because the row is a tombstone\"\n   * (which must NOT be recorded as available — a live edge pointing at a\n   * soft-deleted node violates the endpoint-liveness invariant the\n   * collection API enforces).\n   */\n  | { status: \"skipped\"; liveTarget: boolean }\n  | { status: \"error\"; error: string };\n\n/**\n * What a guard hands back when its refusal is a PER-ROW fact: either the value\n * the guard produced, or the message recorded against that row while the import\n * keeps going. Shared by the declared-constraint guard and the window guard so\n * the two per-row recoveries have one shape.\n */\ntype PerRowGuardResult<T> =\n  Readonly<{ ok: true; value: T }> | Readonly<{ ok: false; error: string }>;\n\n/**\n * Runs `fn` and reports a DECLARED-CONSTRAINT refusal as a per-row result\n * instead of letting it abort the whole import. Any other error still\n * propagates.\n *\n * The subject is the family of refusals a declared constraint produces —\n * uniqueness, disjointness, edge cardinality and durable edge identity —\n * rather than one class of it.\n * A guard named for a single class is an invitation to forget the next family\n * that arrives, which is exactly how the disjointness gap this closes came\n * about: import gained a claim that could refuse a disjoint row and no per-row\n * recovery that recognized the refusal, so a violation would have aborted the\n * whole batch where the contract promises a refused ROW.\n */\nasync function catchDeclaredConstraintRefusal<T>(\n  fn: () => T | Promise<T>,\n): Promise<PerRowGuardResult<T>> {\n  try {\n    return { ok: true, value: await fn() };\n  } catch (error) {\n    if (isDeclaredConstraintRefusal(error)) {\n      return { ok: false, error: error.message };\n    }\n    throw error;\n  }\n}\n\nfunction isDeclaredConstraintRefusal(\n  error: unknown,\n): error is\n  | UniquenessError\n  | DisjointError\n  | CardinalityError\n  | EdgeMatchIdentityConflictError {\n  return (\n    error instanceof UniquenessError ||\n    error instanceof DisjointError ||\n    error instanceof CardinalityError ||\n    error instanceof EdgeMatchIdentityConflictError\n  );\n}\n\nfunction isEdgeMatchIdentityValueRefusal(\n  error: unknown,\n): error is ConfigurationError {\n  if (!(error instanceof ConfigurationError)) return false;\n  const code = error.details[\"code\"];\n  return (\n    code === \"EDGE_MATCH_IDENTITY_KEY_TOO_LARGE\" ||\n    code === \"EDGE_MATCH_IDENTITY_VALUE_NOT_SCALAR\"\n  );\n}\n\ntype EdgeCreateGuardResult<T> =\n  | Readonly<{ ok: true; value: T }>\n  | Readonly<{ ok: false; error: string; cause: Error }>;\n\ntype EdgeCreateGuardAttempt<T> = Readonly<{\n  result: EdgeCreateGuardResult<T>;\n  rollbackProtection: \"savepoint\" | \"none\";\n}>;\n\n/** Converts one row's durable-identity refusal into an import result. */\nasync function catchEdgeCreateRefusal<T>(\n  fn: () => T | Promise<T>,\n): Promise<EdgeCreateGuardResult<T>> {\n  try {\n    return { ok: true, value: await fn() };\n  } catch (error) {\n    if (\n      isDeclaredConstraintRefusal(error) ||\n      isEdgeMatchIdentityValueRefusal(error)\n    ) {\n      return { ok: false, error: error.message, cause: error };\n    }\n    throw error;\n  }\n}\n\n/**\n * Runs the one edge statement whose database refusal is a per-row outcome.\n * PostgreSQL marks the surrounding transaction failed after its unique-index\n * error, so the failed statement must be isolated behind a savepoint. Pure\n * preparation and validation stay outside this helper: they cannot poison the\n * transaction and need no extra round trips.\n */\nasync function catchEdgeCreateRefusalWithSavepoint<T>(\n  frame: Pick<\n    ImportWriteFrame,\n    | \"target\"\n    | \"allocateEdgeSavepoint\"\n    | \"transactionMode\"\n    | \"statementExecution\"\n  >,\n  fn: () => T | Promise<T>,\n): Promise<EdgeCreateGuardAttempt<T>> {\n  const { target } = frame;\n  if (frame.transactionMode === \"none\") {\n    return {\n      result: await catchEdgeCreateRefusal(fn),\n      rollbackProtection: \"none\",\n    };\n  }\n  if (!frame.statementExecution.supported) {\n    // Preserve compatibility for transactional custom backends that expose no\n    // raw statement member. A successful row remains successful; a refusal\n    // that may have poisoned the transaction is deliberately propagated.\n    try {\n      return {\n        result: { ok: true, value: await fn() },\n        rollbackProtection: \"none\",\n      };\n    } catch (error) {\n      if (isEdgeMatchIdentityValueRefusal(error)) {\n        return {\n          result: { ok: false, error: error.message, cause: error },\n          rollbackProtection: \"none\",\n        };\n      }\n      throw error;\n    }\n  }\n  const statementExecution = frame.statementExecution;\n  const result = await runRecordedTransactionSavepoint<\n    EdgeCreateGuardResult<T>\n  >(target, statementExecution, frame.allocateEdgeSavepoint(), async () => {\n    const guarded = await catchEdgeCreateRefusal(fn);\n    return guarded.ok ?\n        { action: \"release\", value: guarded }\n      : { action: \"rollback\", value: guarded, cause: guarded.cause };\n  });\n  return { result, rollbackProtection: \"savepoint\" };\n}\n\n/**\n * The stable prefix on every per-row refusal caused by an import UPDATE whose\n * target stopped matching the row this import made its decision from.\n *\n * The node counterpart of {@link EDGE_IDENTITY_CONFLICT_CODE}. Nodes need no\n * identity code — their probe is kind-scoped and they have no endpoints — but\n * they do share the temporal half of the class: the update verdict is computed\n * from the PROBED row's `valid_from`, and a concurrent hard delete + recreate\n * can replace it between the probe and the write.\n */\nconst NODE_UPDATE_TARGET_CHANGED_CODE =\n  \"INTERCHANGE_NODE_UPDATE_TARGET_CHANGED\";\n\n/**\n * Updates an existing node under the effective validity lower bound this import\n * checked it carries, and reports a write that landed on nothing as a per-row\n * error.\n *\n * THE SINGLE OWNER of the node update leg, called by both the batched slice and\n * the sequential fallback, so the assertion cannot be threaded through one and\n * forgotten on the other.\n *\n * The `windowFence` is what makes the import's own window check\n * ({@link validateUpdateValidityWindow}) binding rather than advisory. When that\n * check reads the STORED `valid_from` — because the document stated a lower\n * bound to compare against it, or a lone `validTo` to invert against it — it\n * hands back an `expectedValidFrom` predicate, and a read-then-write pair keyed\n * on `(graph_id, kind, id)` alone would otherwise re-resolve that key between the\n * two under PostgreSQL READ COMMITTED: a concurrent hard delete + recreate could\n * leave the write applying a verdict computed for a row that no longer exists —\n * the document's `validFrom` silently ignored, or a `valid_to` persisted below\n * the new row's `valid_from`. The fence puts the bound in the UPDATE's own\n * `WHERE`.\n *\n * A document naming NEITHER bound gets an empty fence, and that is the point: its\n * verdict never looked at the row's lower bound, so a recreate that moved the\n * bound changed nothing this write decided, and refusing the props update would\n * refuse a write the equivalent `store.nodes.*.update` performs. The\n * `deleted_at IS NULL` fence of the live-row update still applies.\n */\nasync function updateImportedNode(\n  session: WriteSession,\n  node: InterchangeNode,\n  args: Readonly<{\n    existing: LiveNodeRow;\n    schema: z.ZodType;\n    validatedProps: Record<string, unknown>;\n    uniqueConstraints: readonly UniqueConstraint[];\n    windowFence: ValidityLowerBoundFence;\n  }>,\n): Promise<string | undefined> {\n  try {\n    // The widened guard wraps a WRITE here, not a probe, so what it recovers\n    // from is worth stating: `reviseNode` raises neither a `DisjointError` nor a\n    // `CardinalityError` — an in-place update cannot change a node's kind, so it\n    // re-derives no disjointness verdict, and it writes no edges — and the update\n    // path's claim set carries uniqueness entries only. Widening the guard\n    // therefore changes nothing here today; it is listed because a changed\n    // contract re-audits its consumers.\n    const result = await catchDeclaredConstraintRefusal(() =>\n      // The fence is an ARGUMENT the method requires, not a spread the call\n      // site may forget: the guard's verdict travels to the statement that\n      // honors it, and an empty fence (`{}`) is the stated decision to assert\n      // nothing rather than an omission.\n      session.reviseNode(\n        {\n          existing: args.existing,\n          schema: args.schema,\n          validatedProps: args.validatedProps,\n          uniqueConstraints: args.uniqueConstraints,\n          ...(node.validTo !== undefined && { validTo: node.validTo }),\n        },\n        { validityLowerBound: args.windowFence },\n      ),\n    );\n    return result.ok ? undefined : result.error;\n  } catch (error) {\n    if (\n      !(error instanceof DatabaseOperationError) ||\n      error.details.reason !== \"no_row_returned\"\n    ) {\n      throw error;\n    }\n    return (\n      `${NODE_UPDATE_TARGET_CHANGED_CODE}: Node \"${node.kind}:${node.id}\" was ` +\n      \"not updated: no live node matching the id and the validity bound this \" +\n      \"import checked remained when the write ran, so the row changed or was \" +\n      \"removed after it was checked. Re-export the source and retry.\"\n    );\n  }\n}\n\n/**\n * The stable prefix on every per-row refusal caused by an incoming edge naming\n * an id that a DIFFERENT edge already occupies, so a caller can recognize the\n * condition without parsing prose — the same `CODE: message` idiom the validity\n * window refusals use.\n *\n * ONE code for the whole immutable-identity class — kind AND endpoints — rather\n * than a second code for endpoint mismatches. The condition is a single fact\n * (\"the row under this id is not the edge this document describes\"), the\n * recovery is a single action (\"give it a distinct id, or import it under the\n * identity the stored row carries\"), and a caller that had to match two prefixes\n * to catch one condition would eventually match only one. The message names\n * which components differ; the prefix says what class of thing went wrong.\n *\n * The token still reads `…_KIND_CONFLICT` because it is a PUBLISHED, branchable\n * prefix (documented in `interchange.md`) and renaming it would silently break\n * every caller filtering on it; the constant is named for what it now covers.\n */\nconst EDGE_IDENTITY_CONFLICT_CODE = \"INTERCHANGE_EDGE_KIND_CONFLICT\";\n\n/** The immutable identity of a stored edge, as the probe reports it. */\ntype StoredEdgeIdentity = Readonly<{\n  kind: string;\n  from_kind: string;\n  from_id: string;\n  to_kind: string;\n  to_id: string;\n}>;\n\n/**\n * Whether an existing row is actually the edge this document is describing.\n *\n * THE SINGLE OWNER of that decision, consulted by both edge-import paths (the\n * batched slice and the per-row fallback) before ANY conflict strategy runs.\n *\n * Edge ids are graph-global while every interchange edge states a kind AND both\n * endpoints, and the existence probe (`getEdge` / `getEdges`) is keyed on\n * `(graph_id, id)` alone — so an incoming edge whose id is already taken by a\n * DIFFERENT edge finds that row and, without this check, was treated as the same\n * edge by all three strategies: `update` wrote the incoming props onto the other\n * row with nothing in `result.errors`, and `skip` counted the document's edge as\n * already present when nothing matching was ever there. Both are silent, and the\n * id is unique per graph, so the incoming edge cannot be created under it\n * either. Reporting is the only honest outcome.\n *\n * Compares the FULL immutable identity — kind and all four endpoint components —\n * not kind alone. Kind is not an identity: an id already held by an edge of the\n * same kind pointing somewhere else is just as much \"not this edge\", and a\n * kind-only comparison reported `updated: 1` while overwriting that row's props\n * and silently retaining its old endpoints (endpoints are immutable, so the\n * document's stated `from`/`to` were simply discarded). Every component is\n * checked because every component is immutable for a given row.\n *\n * Deliberately checked ABOVE the `onConflict` switch rather than inside each\n * arm: the question \"is this the same edge?\" is prior to \"what do we do about\n * the same edge?\", and answering it per-arm is how two of the three arms came\n * to answer it differently.\n *\n * Nodes need no equivalent: their probe is `getNode(graphId, kind, id)`, which\n * is kind-scoped, and a node has no endpoints — so a cross-kind id collision\n * simply reads as absent there.\n */\nfunction edgeIdentityConflict(\n  edge: InterchangeEdge,\n  existing: StoredEdgeIdentity,\n): string | undefined {\n  const differences = [\n    ...(existing.kind === edge.kind ?\n      []\n    : [`kind \"${existing.kind}\" (document states \"${edge.kind}\")`]),\n    ...((\n      existing.from_kind === edge.from.kind && existing.from_id === edge.from.id\n    ) ?\n      []\n    : [\n        `from \"${existing.from_kind}:${existing.from_id}\" (document states ` +\n          `\"${edge.from.kind}:${edge.from.id}\")`,\n      ]),\n    ...(existing.to_kind === edge.to.kind && existing.to_id === edge.to.id ?\n      []\n    : [\n        `to \"${existing.to_kind}:${existing.to_id}\" (document states ` +\n          `\"${edge.to.kind}:${edge.to.id}\")`,\n      ]),\n  ];\n  if (differences.length === 0) return undefined;\n  return (\n    `${EDGE_IDENTITY_CONFLICT_CODE}: Edge \"${edge.id}\" already exists with a ` +\n    `different immutable identity — ${differences.join(\"; \")}. Edge ids are ` +\n    \"unique per graph, so the incoming edge can neither update nor be created \" +\n    \"under that id. Give it a distinct id, or import it under the identity the \" +\n    \"stored row already carries.\"\n  );\n}\n\n/**\n * Updates an existing edge under the full immutable identity the caller checked\n * it carries, and reports a write that landed on nothing as a per-row error.\n *\n * All five identity components are stated so the predicate lives in the UPDATE's\n * own `WHERE` — the contract on {@link UpdateEdgeParams}, and the only placement\n * a concurrent hard-delete-and-recreate cannot slip past, because a\n * read-then-write pair keyed on `(graph_id, id)` alone re-resolves that id\n * between the probe and the write under PostgreSQL READ COMMITTED. Omitting them\n * made the import's own identity check advisory: correct until raced.\n *\n * The endpoints move together with `kind` rather than being left out because\n * they are \"less likely\" to be raced: the window is the same window, and this\n * import HAS checked all five against a row it read, which is exactly the\n * precondition {@link UpdateEdgeParams} states for asserting them.\n *\n * The effective `valid_from` joins them for a DIFFERENT reason, and the doc on\n * {@link UpdateEdgeParams.expectedValidFrom} spells it out: the five identity\n * components are asserted because they are immutable, the bound because it is\n * NOT. {@link validateUpdateValidityWindow} decides from the row's stored\n * `valid_from` — whether the document may state a lower bound this update will\n * not apply, and whether its `validTo` sits above the bound the row keeps — so a\n * recreate that satisfies all five identity components while carrying a\n * different bound would still land a verdict computed for a row that is gone.\n *\n * Which is why the bound arrives as the guard's own `windowFence` rather than as\n * a value this function re-derives: it is present exactly when the verdict read\n * it. A document naming neither `validFrom` nor `validTo` read nothing, so it is\n * fenced on identity alone and a recreate that only moved the bound no longer\n * refuses its props update.\n *\n * When the predicate does match nothing, the backend reports it as a\n * `no_row_returned` {@link DatabaseOperationError}. By then this import has\n * already checked the identity against a row it read, so reaching here means the\n * target changed underneath us — a per-row fact about one edge, not a reason to\n * abort an import whose earlier rows are already written.\n */\nasync function updateImportedEdge(\n  session: WriteSession,\n  edge: InterchangeEdge,\n  props: Readonly<Record<string, unknown>>,\n  windowFence: ValidityLowerBoundFence,\n): Promise<string | undefined> {\n  try {\n    // Both halves of the predicate are stated as FENCES — required keys of the\n    // method's fence record, applied into the statement's own `WHERE` by their\n    // appliers — rather than assembled into the params here. The five identity\n    // components because they are immutable and this import checked them; the\n    // stored lower bound because the window guard read it.\n    await session.reviseEdge(\n      {\n        id: edge.id,\n        props,\n        ...(edge.validTo !== undefined && { validTo: edge.validTo }),\n      },\n      {\n        validityLowerBound: windowFence,\n        // Import re-admits no row to a counted population — it never resurrects\n        // and never clears an end — so it reads no stored `valid_to` and asserts\n        // none. `{}` is the stated decision, not an omission.\n        validityUpperBound: {},\n        edgeIdentity: {\n          kind: edge.kind,\n          fromKind: edge.from.kind,\n          fromId: edge.from.id,\n          toKind: edge.to.kind,\n          toId: edge.to.id,\n        },\n      },\n    );\n    return undefined;\n  } catch (error) {\n    if (\n      !(error instanceof DatabaseOperationError) ||\n      error.details.reason !== \"no_row_returned\"\n    ) {\n      throw error;\n    }\n    return (\n      `${EDGE_IDENTITY_CONFLICT_CODE}: Edge \"${edge.id}\" of kind \"${edge.kind}\" ` +\n      `from \"${edge.from.kind}:${edge.from.id}\" to \"${edge.to.kind}:${edge.to.id}\" ` +\n      \"was not updated: no live edge matching the identity and the validity \" +\n      \"bound this import checked remained when the write ran, so the row \" +\n      \"changed or was removed after it was checked. Re-export the source and \" +\n      \"retry.\"\n    );\n  }\n}\n\n/**\n * Applies the shared durable-identity update decision to interchange's\n * per-row result contract. Import validates props before reaching this seam,\n * so the before/after comparison is exactly the comparison a collection\n * update makes immediately before its write.\n */\nfunction importedEdgeIdentityUpdateError(\n  registration: EdgeRegistration,\n  edge: InterchangeEdge,\n  existing: NonNullable<Awaited<ReturnType<GraphBackend[\"getEdge\"]>>>,\n  props: Readonly<Record<string, unknown>>,\n): string | undefined {\n  return edgeMatchIdentityUpdateRefusal({\n    identity: registration.matchIdentity,\n    kind: edge.kind,\n    id: edge.id,\n    beforeProps: rowPropsToObject(existing.props),\n    afterProps: props,\n  })?.message;\n}\n\n/**\n * Runs a window guard and reports its refusal as a per-row error message\n * (recorded in the import result) instead of throwing, so one malformed row does\n * not abort the whole import. On success the guard's own verdict comes back, so\n * a write leg fences on what the guard decided rather than on a second spelling\n * of it. A window refusal that carries a stable issue code —\n * {@link INVERTED_VALIDITY_WINDOW_CODE} or\n * {@link IMMUTABLE_VALIDITY_LOWER_BOUND_CODE} — is prefixed with it, so the\n * refusal is recognizable without parsing prose.\n */\nfunction windowResultOf<T>(assert: () => T): PerRowGuardResult<T> {\n  try {\n    return { ok: true, value: assert() };\n  } catch (error) {\n    if (error instanceof ValidationError) {\n      const coded = error.details.issues.find(\n        (issue) =>\n          issue.code === INVERTED_VALIDITY_WINDOW_CODE ||\n          issue.code === IMMUTABLE_VALIDITY_LOWER_BOUND_CODE,\n      );\n      if (coded !== undefined) {\n        return { ok: false, error: `${coded.code}: ${error.message}` };\n      }\n    }\n    return {\n      ok: false,\n      error: error instanceof Error ? error.message : String(error),\n    };\n  }\n}\n\n/** {@link windowResultOf} for a guard whose only output is its refusal. */\nfunction windowErrorOf(assert: () => void): string | undefined {\n  const result = windowResultOf(assert);\n  return result.ok ? undefined : result.error;\n}\n\n/**\n * Validates an entity's validity window against the two contracts `create` /\n * `update` enforce: canonical fixed-width UTC ISO-8601 timestamps, so no import\n * write path can persist a `valid_from` / `valid_to` that later mis-sorts as\n * text against an `asOf` read coordinate, and non-negative window WIDTH, so no\n * import document can persist a row that stopped being true before it started.\n * Import writes straight to the backend rather than through the store\n * operations layer, so it carries its own copy of both — this is the only place\n * the guarantee exists for an imported row.\n *\n * The interchange schema enforces the timestamp contract at the parse boundary,\n * but `importGraph` accepts a pre-typed `GraphData` and does not re-parse it, so\n * this is also the guarantee for callers that bypass the schema.\n *\n * This is the INSERT-shaped half, judged before the existence probe so a\n * malformed document is refused whether or not the row already exists. The\n * update legs additionally call {@link validateUpdateValidityWindow}, which\n * needs the row.\n */\nfunction validateValidityWindow(\n  entity: Readonly<{\n    kind: string;\n    id: string;\n    validFrom?: string | null | undefined;\n    validTo?: string | undefined;\n  }>,\n): string | undefined {\n  return windowErrorOf(() => {\n    // null is a confirmed open-left window (see InterchangeNodeSchema's\n    // validFrom doc), not a value to format-check — treat it like\n    // \"not provided\" here, same as the canonical-date validator does.\n    validateOptionalCanonicalIsoDate(\n      entity.validFrom ?? undefined,\n      \"validFrom\",\n    );\n    validateOptionalCanonicalIsoDate(entity.validTo, \"validTo\");\n    // On an INSERT only a stated pair is judged — a lone historical validTo\n    // means \"born already ended\", exactly as it does on `create` (see\n    // assertWritableValidityWindow) — and that is the WHOLE rule, not a partial\n    // one: the insert path this feeds stamps NO lower bound for such a row\n    // (`resolveStampedValidityLowerBound`), so a document accepted here cannot\n    // become a row readable at no coordinate. `null` is a confirmed open-left\n    // window and is not a lower bound at all.\n    assertOrderedValidityWindow(\n      `${entity.kind} \"${entity.id}\"`,\n      entity.validFrom ?? undefined,\n      entity.validTo,\n    );\n  });\n}\n\n/**\n * The UPDATE-shaped half, for `onConflict: \"update\"` against a row that already\n * exists. All four update legs — batched and sequential, nodes and edges — send\n * the document's `validTo` to an in-place update of a LIVE row while its stored\n * `valid_from` stays put, so the document's end is held to that bound exactly as\n * `store.nodes.*.update` holds a caller's. Without this an import could still\n * write the inverted row the direct update path refuses, and the insert-shaped\n * check above cannot see it: such a document may state no `validFrom` at all.\n *\n * The document's `validFrom` is judged here for the same reason: import never\n * sends it on an update, so a document stating a bound that differs from the\n * row's is stating one the write will not apply. That is refused per row —\n * `onConflict: \"update\"` re-importing a document whose rows were created at a\n * different instant now reports those rows instead of silently updating their\n * props under a bound it ignored. `null` is a confirmed open-left window rather\n * than a stated bound (see `InterchangeNodeSchema`'s `validFrom`) and asserts\n * nothing.\n *\n * Returns the guard's own {@link ValidityLowerBoundFence}, which all four update\n * legs carry verbatim into their write. Import used to assert the probed\n * `valid_from` unconditionally instead — a second spelling of a decision the\n * verdict owns — which refused a props-only document (one naming neither bound)\n * whenever a concurrent recreate moved a bound this verdict never looked at.\n */\nfunction validateUpdateValidityWindow(\n  entity: Readonly<{\n    kind: string;\n    id: string;\n    validFrom?: string | null | undefined;\n    validTo?: string | undefined;\n  }>,\n  storedValidFrom: string | undefined,\n): PerRowGuardResult<ValidityLowerBoundFence> {\n  const verdict = windowResultOf(() =>\n    assertWritableValidityWindow(\n      `${entity.kind} \"${entity.id}\"`,\n      entity.validFrom ?? undefined,\n      {\n        effectiveValidFrom: storedValidFrom,\n        appliesStatedValidFrom: false,\n        // Import updates a LIVE row in place, so the effective bound is always\n        // the one the row already stores.\n        effectiveBoundIsStored: true,\n      },\n      entity.validTo,\n    ),\n  );\n  return verdict.ok ?\n      { ok: true, value: verdict.value.storedLowerBoundFence }\n    : verdict;\n}\n\nasync function processNode(\n  frame: ImportWriteFrame,\n  graphId: string,\n  registry: KindRegistry,\n  node: InterchangeNode,\n  schemas: ReadonlyMap<string, NodeSchemaEntry>,\n  options: ResolvedImportOptions,\n): Promise<ProcessResult> {\n  // Validate kind exists\n  const schemaEntry = schemas.get(node.kind);\n  if (!schemaEntry) {\n    return { status: \"error\", error: `Unknown node kind: ${node.kind}` };\n  }\n\n  // Validate and transform properties\n  const propsResult = validateProperties(\n    node.properties,\n    schemaEntry.schema,\n    options.onUnknownProperty,\n  );\n\n  if (!propsResult.success) {\n    return { status: \"error\", error: propsResult.error };\n  }\n\n  const validityError = validateValidityWindow(node);\n  if (validityError !== undefined) {\n    return { status: \"error\", error: validityError };\n  }\n\n  const { registration } = schemaEntry;\n  const uniqueConstraints = registration.unique ?? [];\n\n  // Check if node already exists\n  const existing = await frame.target.getNode(graphId, node.kind, node.id);\n\n  if (existing) {\n    switch (options.onConflict) {\n      case \"skip\": {\n        return { status: \"skipped\", liveTarget: isLiveNodeRow(existing) };\n      }\n      case \"error\": {\n        return {\n          status: \"error\",\n          error: `Node already exists: ${node.kind}:${node.id}`,\n        };\n      }\n      case \"update\": {\n        if (!isLiveNodeRow(existing)) {\n          // A soft-deleted node is not updatable: import never resurrects a\n          // tombstone, and running the live-row update pipeline here would\n          // recreate uniqueness/embedding/fulltext rows for a node that\n          // stays invisible — a uniqueness reservation held by a tombstoned\n          // node would block live creates of the same value.\n          return { status: \"skipped\", liveTarget: false };\n        }\n        const updateWindow = validateUpdateValidityWindow(\n          node,\n          existing.valid_from,\n        );\n        if (!updateWindow.ok) {\n          return { status: \"error\", error: updateWindow.error };\n        }\n        // Route through the write session so the update maintains uniqueness\n        // entries, embeddings, and fulltext — the collection API's integrity,\n        // which a raw backend.updateNode would skip. Both per-row recoveries\n        // below are safe to catch and commit past because every\n        // `UniquenessError` `reviseNode` can raise comes from its plan or its\n        // claim, both of which precede the row write (and the claim compensates\n        // itself), and a write that landed on nothing wrote nothing by\n        // definition.\n        const updateError = await updateImportedNode(frame.session, node, {\n          existing,\n          schema: registration.type.schema,\n          validatedProps: propsResult.data,\n          uniqueConstraints,\n          windowFence: updateWindow.value,\n        });\n        if (updateError !== undefined) {\n          return { status: \"error\", error: updateError };\n        }\n        return { status: \"updated\" };\n      }\n    }\n  }\n\n  // Create new node. Pre-check both declared node constraints (as the\n  // collection create does) so a conflict is a per-row error rather than an\n  // orphaned node row, then create through the session, which applies the claims\n  // and the sync fans a raw insert would bypass. No pending state is needed\n  // here: this path writes each row as it goes, so the next row's probe reads\n  // the previous one from the same transaction.\n  const constraintResult = await catchDeclaredConstraintRefusal(async () => {\n    await checkUniquenessConstraints(\n      { graphId, registry, backend: frame.target },\n      node.kind,\n      node.id,\n      propsResult.data,\n      uniqueConstraints,\n    );\n    await checkDisjointnessConstraint(\n      { graphId, registry, backend: frame.target },\n      node.kind,\n      node.id,\n    );\n  });\n  if (!constraintResult.ok) {\n    return { status: \"error\", error: constraintResult.error };\n  }\n\n  // The RETURNING single-insert shape, whose row this path discards, because\n  // that is the statement this leg emitted before the migration.\n  await frame.session.createNode(\n    importNodeCreateWork(\n      graphId,\n      registry,\n      node,\n      registration,\n      propsResult.data,\n    ),\n  );\n\n  return { status: \"created\" };\n}\n\n// ============================================================\n// Edge Processing\n// ============================================================\n\nasync function processEdges(\n  frame: ImportWriteFrame,\n  graphId: string,\n  registry: KindRegistry,\n  edges: readonly InterchangeEdge[],\n  edgeSchemas: ReadonlyMap<string, EdgeSchemaEntry>,\n  nodeSchemas: ReadonlyMap<string, NodeSchemaEntry>,\n  options: ResolvedImportOptions,\n  result: ImportResult,\n  errors: ImportError[],\n  importedNodeIds: Set<string>,\n): Promise<void> {\n  const batchSize = options.batchSize;\n  // A slice flush makes its accepted keys visible to later database reads, but\n  // candidates in the same slice have not been written yet. Keep the durable\n  // owner keys accepted by this import so two rows in one payload receive the\n  // same first-wins, per-row disposition as two rows in separate imports.\n  const pendingMatchIdentityOwners = new Set<string>();\n\n  for (let index = 0; index < edges.length; index += batchSize) {\n    const batch = edges.slice(index, index + batchSize);\n    await processEdgeSlice(\n      frame,\n      graphId,\n      registry,\n      batch,\n      edgeSchemas,\n      nodeSchemas,\n      options,\n      result,\n      errors,\n      importedNodeIds,\n      pendingMatchIdentityOwners,\n    );\n  }\n}\n\nfunction recordEdgeOutcome(\n  edge: InterchangeEdge,\n  outcome: ProcessResult,\n  result: ImportResult,\n  errors: ImportError[],\n): void {\n  switch (outcome.status) {\n    case \"created\": {\n      result.edges.created++;\n      break;\n    }\n    case \"updated\": {\n      result.edges.updated++;\n      break;\n    }\n    case \"skipped\": {\n      result.edges.skipped++;\n      break;\n    }\n    case \"error\": {\n      errors.push({\n        entityType: \"edge\",\n        kind: edge.kind,\n        id: edge.id,\n        error: outcome.error,\n      });\n      break;\n    }\n  }\n}\n\ntype EdgeImportCandidate = Readonly<{\n  edge: InterchangeEdge;\n  props: Record<string, unknown>;\n}>;\n\ntype PreparedEdgeImportCreate = Readonly<{\n  candidate: EdgeImportCandidate;\n  params: InsertEdgeParams;\n  cardinality: Cardinality;\n}>;\n\n/**\n * THE insert params one accepted edge candidate carries, built once and read by\n * three consumers: the in-slice cardinality registration, the claim, and the\n * flush. The candidate loop needs them before the flush does — that is what\n * lets an in-slice collision refuse the ROW — so they cannot be materialized\n * only at the flush the way the pre-fence path did.\n */\nfunction prepareEdgeImportCreate(\n  graphId: string,\n  candidate: EdgeImportCandidate,\n  registration: EdgeRegistration,\n): PreparedEdgeImportCreate {\n  const { edge, props } = candidate;\n  const matchIdentity = resolveEdgeMatchIdentityStorage(\n    registration.matchIdentity,\n    {\n      fromKind: edge.from.kind,\n      fromId: edge.from.id,\n      toKind: edge.to.kind,\n      toId: edge.to.id,\n      props,\n    },\n    { graphId, edgeKind: edge.kind },\n  );\n  const params: InsertEdgeParams = {\n    graphId,\n    id: edge.id,\n    kind: edge.kind,\n    fromKind: edge.from.kind,\n    fromId: edge.from.id,\n    toKind: edge.to.kind,\n    toId: edge.to.id,\n    props,\n    ...(matchIdentity === undefined ? {} : { matchIdentity }),\n    ...(edge.validFrom !== undefined && { validFrom: edge.validFrom }),\n    ...(edge.validTo !== undefined && { validTo: edge.validTo }),\n  };\n  return {\n    candidate,\n    params,\n    cardinality: registration.cardinality ?? \"many\",\n  };\n}\n\nfunction pendingEdgeMatchIdentityOwnerKey(\n  params: InsertEdgeParams,\n): string | undefined {\n  const identity = params.matchIdentity;\n  return identity === undefined ? undefined : (\n      edgeMatchIdentityOwnerKey(\n        params.graphId,\n        params.kind,\n        identity.name,\n        identity.key,\n      )\n    );\n}\n\nfunction edgeMatchIdentityOwnerKey(\n  graphId: string,\n  kind: string,\n  identityName: string,\n  identityKey: string,\n): string {\n  return encodeTupleKey([graphId, kind, identityName, identityKey]);\n}\n\n/**\n * Reads the durable identity owners that can conflict with this slice through\n * the import transaction itself. Bundled backends answer in one set-oriented\n * read; a custom backend without that optional member keeps correctness through\n * exact endpoint-pair reads instead of letting a unique-index error abort the\n * complete slice.\n */\nasync function readEdgeMatchIdentityOwnerKeys(\n  target: WriteTarget,\n  preparedCreates: readonly PreparedEdgeImportCreate[],\n): Promise<ReadonlySet<string>> {\n  const durableCandidates = preparedCreates.filter(\n    (prepared) => prepared.params.matchIdentity !== undefined,\n  );\n  if (durableCandidates.length === 0) return new Set<string>();\n  const graphId = requireDefined(durableCandidates[0]).params.graphId;\n\n  const rows: EdgeRow[] = [];\n  const setRead = target.findEdgesByHeterogeneousEndpointSet;\n  if (setRead === undefined) {\n    const exactPairs = new Map<\n      string,\n      Readonly<{\n        kind: string;\n        fromKind: string;\n        fromId: string;\n        toKind: string;\n        toId: string;\n      }>\n    >();\n    for (const { candidate } of durableCandidates) {\n      const { edge } = candidate;\n      exactPairs.set(\n        encodeTupleKey([\n          edge.kind,\n          edge.from.kind,\n          edge.from.id,\n          edge.to.kind,\n          edge.to.id,\n        ]),\n        {\n          kind: edge.kind,\n          fromKind: edge.from.kind,\n          fromId: edge.from.id,\n          toKind: edge.to.kind,\n          toId: edge.to.id,\n        },\n      );\n    }\n    for (const pair of exactPairs.values()) {\n      rows.push(\n        ...(await target.findEdgesByKind({\n          graphId,\n          ...pair,\n          excludeDeleted: false,\n          temporalMode: \"includeTombstones\",\n        })),\n      );\n    }\n  } else {\n    const endpointPairs = new Map<\n      string,\n      Readonly<{\n        kind: string;\n        id: string;\n        opposite: Readonly<{ kind: string; id: string }>;\n      }>\n    >();\n    const edgeKinds = new Set<string>();\n    for (const { candidate } of durableCandidates) {\n      endpointPairs.set(\n        encodeTupleKey([\n          candidate.edge.from.kind,\n          candidate.edge.from.id,\n          candidate.edge.to.kind,\n          candidate.edge.to.id,\n        ]),\n        {\n          kind: candidate.edge.from.kind,\n          id: candidate.edge.from.id,\n          opposite: candidate.edge.to,\n        },\n      );\n      edgeKinds.add(candidate.edge.kind);\n    }\n    rows.push(\n      ...(await setRead({\n        graphId,\n        side: \"from\",\n        endpoints: [...endpointPairs.values()],\n        edgeKinds: [...edgeKinds],\n        excludeDeleted: false,\n        temporalMode: \"includeTombstones\",\n      })),\n    );\n  }\n\n  const ownerKeys = new Set<string>();\n  for (const row of rows) {\n    if (\n      row.match_identity_name === undefined ||\n      row.match_identity_key === undefined\n    ) {\n      continue;\n    }\n    ownerKeys.add(\n      edgeMatchIdentityOwnerKey(\n        graphId,\n        row.kind,\n        row.match_identity_name,\n        row.match_identity_key,\n      ),\n    );\n  }\n  return ownerKeys;\n}\n\n/**\n * The heterogeneous endpoint read is an optimization, not a required\n * capability of import. A backend can expose it yet refuse a particular\n * request when the selected edge-kind list leaves no bind budget. Only that\n * declared refusal may fall back to the cardinality seam's singleton probes;\n * all other failures remain real import failures.\n */\nfunction isHeterogeneousReadBindBudgetRefusal(error: unknown): boolean {\n  return (\n    error instanceof ConfigurationError &&\n    error.details[\"code\"] === \"EDGE_HETEROGENEOUS_READ_BIND_BUDGET_EXCEEDED\"\n  );\n}\n\n/**\n * Processes one batchSize slice of edges with batched round trips: one\n * `getNodes` per endpoint kind for reference liveness, one `getEdges` for\n * existence, one durable-owner endpoint read when needed, and one multi-row\n * insert for the accepted creates. Per-row semantics are unchanged; duplicate\n * ids within a slice defer to the per-row path after the flush.\n */\nasync function processEdgeSlice(\n  frame: ImportWriteFrame,\n  graphId: string,\n  registry: KindRegistry,\n  batch: readonly InterchangeEdge[],\n  edgeSchemas: ReadonlyMap<string, EdgeSchemaEntry>,\n  nodeSchemas: ReadonlyMap<string, NodeSchemaEntry>,\n  options: ResolvedImportOptions,\n  result: ImportResult,\n  errors: ImportError[],\n  importedNodeIds: Set<string>,\n  pendingMatchIdentityOwners: Set<string>,\n): Promise<void> {\n  const record = (edge: InterchangeEdge, outcome: ProcessResult): void => {\n    recordEdgeOutcome(edge, outcome, result, errors);\n  };\n\n  // The store's own in-batch cardinality accounting, constructed once per\n  // slice against the REAL backend — the same wrapper `prepareEdgeBatchCreates`\n  // uses, not a second implementation. Per slice rather than per import is\n  // correct because each slice flushes its accepted inserts before the next one\n  // runs, so slice k+1's probe reads slice k's rows from the backend; the\n  // pending state only has to cover rows decided but not yet written.\n  const {\n    backend: cardinalityValidationBackend,\n    registerPendingEdgeForCardinality,\n    seedCardinalityRows,\n  } = createEdgeBatchValidationBackend(frame.target);\n\n  // Pass 1 (synchronous): kind, endpoint-kind, endpoint-assignability,\n  // property, and validity validation, plus in-slice duplicate deferral.\n  const candidates: EdgeImportCandidate[] = [];\n  const deferred: InterchangeEdge[] = [];\n  const seenIds = new Set<string>();\n  for (const edge of batch) {\n    const schemaEntry = edgeSchemas.get(edge.kind);\n    if (!schemaEntry) {\n      record(edge, {\n        status: \"error\",\n        error: `Unknown edge kind: ${edge.kind}`,\n      });\n      continue;\n    }\n    if (!nodeSchemas.has(edge.from.kind)) {\n      record(edge, {\n        status: \"error\",\n        error: `Unknown from node kind: ${edge.from.kind}`,\n      });\n      continue;\n    }\n    if (!nodeSchemas.has(edge.to.kind)) {\n      record(edge, {\n        status: \"error\",\n        error: `Unknown to node kind: ${edge.to.kind}`,\n      });\n      continue;\n    }\n    const endpointError = validateEdgeEndpoints(\n      edge.kind,\n      edge.from.kind,\n      edge.to.kind,\n      schemaEntry.registration,\n      registry,\n    );\n    if (endpointError !== undefined) {\n      record(edge, { status: \"error\", error: endpointError.message });\n      continue;\n    }\n    const propsResult = validateProperties(\n      edge.properties,\n      schemaEntry.schema,\n      options.onUnknownProperty,\n    );\n    if (!propsResult.success) {\n      record(edge, { status: \"error\", error: propsResult.error });\n      continue;\n    }\n    const validityError = validateValidityWindow(edge);\n    if (validityError !== undefined) {\n      record(edge, { status: \"error\", error: validityError });\n      continue;\n    }\n    if (seenIds.has(edge.id)) {\n      deferred.push(edge);\n      continue;\n    }\n    seenIds.add(edge.id);\n    candidates.push({ edge, props: propsResult.data });\n  }\n\n  // Batch the endpoint-liveness reads: one getNodes per endpoint kind for\n  // every key the import itself didn't create. Falls back to per-row\n  // getNode inside the routing loop when the backend lacks getNodes.\n  const liveEndpointKeys = new Set<string>();\n  const checkedEndpointKeys = new Set<string>();\n  const boundGetNodesForEndpoints = bindExtraIfReachable(\n    frame.target,\n    frame.batchPointRead.extras.getNodes,\n    BATCH_POINT_READ.id,\n  );\n  if (options.validateReferences && boundGetNodesForEndpoints !== undefined) {\n    const idsByKind = new Map<string, Set<string>>();\n    for (const { edge } of candidates) {\n      for (const endpoint of [edge.from, edge.to]) {\n        const key = makeNodeKey(endpoint.kind, endpoint.id);\n        if (importedNodeIds.has(key) || checkedEndpointKeys.has(key)) continue;\n        checkedEndpointKeys.add(key);\n        const ids = idsByKind.get(endpoint.kind) ?? new Set<string>();\n        ids.add(endpoint.id);\n        idsByKind.set(endpoint.kind, ids);\n      }\n    }\n    for (const [kind, ids] of idsByKind) {\n      const rows = await boundGetNodesForEndpoints.getNodes(graphId, kind, [\n        ...ids,\n      ]);\n      for (const row of rows) {\n        if (isLiveNodeRow(row)) {\n          liveEndpointKeys.add(makeNodeKey(kind, row.id));\n        }\n      }\n    }\n  }\n\n  const endpointIsLive = async (endpoint: {\n    kind: string;\n    id: string;\n  }): Promise<boolean> => {\n    const key = makeNodeKey(endpoint.kind, endpoint.id);\n    if (importedNodeIds.has(key)) return true;\n    if (checkedEndpointKeys.has(key)) return liveEndpointKeys.has(key);\n    const row = await frame.target.getNode(graphId, endpoint.kind, endpoint.id);\n    return row !== undefined && isLiveNodeRow(row);\n  };\n\n  // Batch the existence reads. Falls back to per-row getEdge when the\n  // backend lacks getEdges.\n  const existingById = new Map<\n    string,\n    Awaited<ReturnType<GraphBackend[\"getEdge\"]>>\n  >();\n  const boundGetEdges = bindExtraIfReachable(\n    frame.target,\n    frame.batchPointRead.extras.getEdges,\n    BATCH_POINT_READ.id,\n  );\n  if (candidates.length > 0 && boundGetEdges !== undefined) {\n    const rows = await boundGetEdges.getEdges(\n      graphId,\n      candidates.map((candidate) => candidate.edge.id),\n    );\n    for (const row of rows) {\n      existingById.set(row.id, row);\n    }\n    for (const { edge } of candidates) {\n      if (!existingById.has(edge.id)) existingById.set(edge.id, undefined);\n    }\n  }\n\n  const preparedCreates: PreparedEdgeImportCreate[] = [];\n  for (const candidate of candidates) {\n    const { edge, props } = candidate;\n\n    if (options.validateReferences) {\n      if (!(await endpointIsLive(edge.from))) {\n        record(edge, {\n          status: \"error\",\n          error: `From node not found: ${edge.from.kind}:${edge.from.id}`,\n        });\n        continue;\n      }\n      if (!(await endpointIsLive(edge.to))) {\n        record(edge, {\n          status: \"error\",\n          error: `To node not found: ${edge.to.kind}:${edge.to.id}`,\n        });\n        continue;\n      }\n    }\n\n    const existing =\n      existingById.has(edge.id) ?\n        existingById.get(edge.id)\n      : await frame.target.getEdge(graphId, edge.id);\n\n    if (existing) {\n      // Prior to every strategy: a row occupying this id under a different\n      // immutable identity is not this edge, and none of the three arms may\n      // treat it as one.\n      const identityConflict = edgeIdentityConflict(edge, existing);\n      if (identityConflict !== undefined) {\n        record(edge, { status: \"error\", error: identityConflict });\n        continue;\n      }\n      switch (options.onConflict) {\n        case \"skip\": {\n          record(edge, {\n            status: \"skipped\",\n            liveTarget: existing.deleted_at === undefined,\n          });\n          break;\n        }\n        case \"error\": {\n          record(edge, {\n            status: \"error\",\n            error: `Edge already exists: ${edge.id}`,\n          });\n          break;\n        }\n        case \"update\": {\n          if (existing.deleted_at !== undefined) {\n            record(edge, { status: \"skipped\", liveTarget: false });\n            break;\n          }\n          const identityUpdateError = importedEdgeIdentityUpdateError(\n            requireDefined(edgeSchemas.get(edge.kind)).registration,\n            edge,\n            existing,\n            props,\n          );\n          if (identityUpdateError !== undefined) {\n            record(edge, { status: \"error\", error: identityUpdateError });\n            break;\n          }\n          const updateWindow = validateUpdateValidityWindow(\n            edge,\n            existing.valid_from,\n          );\n          if (!updateWindow.ok) {\n            record(edge, { status: \"error\", error: updateWindow.error });\n            break;\n          }\n          const updateError = await updateImportedEdge(\n            frame.session,\n            edge,\n            props,\n            updateWindow.value,\n          );\n          if (updateError !== undefined) {\n            record(edge, { status: \"error\", error: updateError });\n            break;\n          }\n          record(edge, { status: \"updated\" });\n          break;\n        }\n      }\n      continue;\n    }\n\n    const preparation = await catchEdgeCreateRefusal(() =>\n      prepareEdgeImportCreate(\n        graphId,\n        candidate,\n        requireDefined(edgeSchemas.get(edge.kind)).registration,\n      ),\n    );\n    if (!preparation.ok) {\n      record(edge, { status: \"error\", error: preparation.error });\n      continue;\n    }\n    preparedCreates.push(preparation.value);\n  }\n\n  for (const ownerKey of await readEdgeMatchIdentityOwnerKeys(\n    frame.target,\n    preparedCreates,\n  )) {\n    pendingMatchIdentityOwners.add(ownerKey);\n  }\n\n  // Cardinality probes are logically per row, but their database reads are\n  // independent until the pending overlay records an accepted row. Prime all\n  // source axes and exact pairs with one heterogeneous endpoint read so a\n  // large import pays one set-oriented round trip instead of one count/exists\n  // statement per distinct source or pair. A backend without this optional\n  // read keeps the existing cached singleton fallback in the validation seam.\n  const cardinalityCounts = new Map<\n    string,\n    Parameters<GraphBackend[\"countEdgesFrom\"]>[0]\n  >();\n  const uniquePairs = new Map<\n    string,\n    Parameters<GraphBackend[\"edgeExistsBetween\"]>[0]\n  >();\n  const sourceEndpoints = new Map<\n    string,\n    Readonly<{ kind: string; id: string }>\n  >();\n  const edgeKinds = new Set<string>();\n  for (const { candidate, cardinality } of preparedCreates) {\n    const { edge } = candidate;\n    if (cardinality === \"many\") continue;\n    edgeKinds.add(edge.kind);\n    const sourceKey = encodeTupleKey([edge.from.kind, edge.from.id]);\n    sourceEndpoints.set(sourceKey, {\n      kind: edge.from.kind,\n      id: edge.from.id,\n    });\n    if (cardinality === \"unique\") {\n      const params = {\n        graphId,\n        edgeKind: edge.kind,\n        fromKind: edge.from.kind,\n        fromId: edge.from.id,\n        toKind: edge.to.kind,\n        toId: edge.to.id,\n      } satisfies Parameters<GraphBackend[\"edgeExistsBetween\"]>[0];\n      uniquePairs.set(\n        encodeTupleKey([\n          params.edgeKind,\n          params.fromKind,\n          params.fromId,\n          params.toKind,\n          params.toId,\n        ]),\n        params,\n      );\n      continue;\n    }\n    const params = {\n      graphId,\n      edgeKind: edge.kind,\n      fromKind: edge.from.kind,\n      fromId: edge.from.id,\n      activeOnly: cardinality === \"oneActive\",\n    } satisfies Parameters<GraphBackend[\"countEdgesFrom\"]>[0];\n    cardinalityCounts.set(\n      encodeTupleKey([\n        params.edgeKind,\n        params.fromKind,\n        params.fromId,\n        params.activeOnly ? \"1\" : \"0\",\n      ]),\n      params,\n    );\n  }\n  const setRead = frame.target.findEdgesByHeterogeneousEndpointSet;\n  if (setRead !== undefined && sourceEndpoints.size > 0 && edgeKinds.size > 0) {\n    try {\n      const rows = await setRead({\n        graphId,\n        side: \"from\",\n        endpoints: [...sourceEndpoints.values()],\n        edgeKinds: [...edgeKinds],\n        excludeDeleted: false,\n        temporalMode: \"includeTombstones\",\n      });\n      seedCardinalityRows(\n        [...cardinalityCounts.values()],\n        [...uniquePairs.values()],\n        rows,\n      );\n    } catch (error) {\n      if (!isHeterogeneousReadBindBudgetRefusal(error)) throw error;\n      // Leave the caches empty. The validation wrapper will issue its normal\n      // per-axis/per-pair probes, preserving correctness for a backend whose\n      // heterogeneous request cannot fit its bind budget.\n    }\n  }\n\n  const accepted: PreparedEdgeImportCreate[] = [];\n  for (const prepared of preparedCreates) {\n    const { candidate, params, cardinality } = prepared;\n    const { edge } = candidate;\n\n    // The cardinality probe, per row and against the pending-aware overlay, so\n    // two `cardinality: \"one\"` edges from one source IN ONE SLICE refuse the\n    // second row instead of both passing and colliding at the batch claim —\n    // which runs once for the whole slice, outside every per-row recovery.\n    const cardinalityResult = await catchDeclaredConstraintRefusal(() =>\n      checkCardinalityConstraint(\n        { graphId, registry, backend: cardinalityValidationBackend },\n        edge.kind,\n        cardinality,\n        edge.from.kind,\n        edge.from.id,\n        edge.to.kind,\n        edge.to.id,\n        edge.validTo,\n      ),\n    );\n    if (!cardinalityResult.ok) {\n      record(edge, { status: \"error\", error: cardinalityResult.error });\n      continue;\n    }\n\n    const pendingIdentityKey = pendingEdgeMatchIdentityOwnerKey(params);\n    if (\n      pendingIdentityKey !== undefined &&\n      pendingMatchIdentityOwners.has(pendingIdentityKey)\n    ) {\n      record(edge, {\n        status: \"error\",\n        error: new EdgeMatchIdentityConflictError({\n          attempted: [\n            {\n              id: edge.id,\n              identityName: requireDefined(params.matchIdentity).name,\n              kind: edge.kind,\n            },\n          ],\n        }).message,\n      });\n      continue;\n    }\n    registerPendingEdgeForCardinality(params, cardinality);\n    if (pendingIdentityKey !== undefined) {\n      pendingMatchIdentityOwners.add(pendingIdentityKey);\n    }\n\n    accepted.push(prepared);\n  }\n\n  if (accepted.length > 0) {\n    // The NO-RETURN batch shape. `insert-dispatch.ts` — reached through the\n    // session — owns \"does this backend have the batch member, and what does it\n    // fall back to\", which is the predicate this leg used to spell for itself,\n    // and the session issues ONE sorted claim for the slice before any row is\n    // written. This import takes no per-graph lock, so the claim is the ONLY\n    // thing that can refuse a concurrent writer of the same axis; a refusal\n    // there aborts the import, which is the honest outcome when the graph\n    // changed under a bulk load and is why the per-row probe above exists for\n    // everything that is not concurrent.\n    const acceptedWork = accepted.map((prepared) =>\n      importEdgeInsertWork(prepared.params, prepared.cardinality),\n    );\n    const retryAcceptedIndividually = async (): Promise<void> => {\n      for (const prepared of accepted) {\n        const { result: rowResult } = await catchEdgeCreateRefusalWithSavepoint(\n          frame,\n          () =>\n            frame.session.createEdge(\n              importEdgeInsertWork(prepared.params, prepared.cardinality),\n            ),\n        );\n        if (rowResult.ok) {\n          record(prepared.candidate.edge, { status: \"created\" });\n        } else {\n          record(prepared.candidate.edge, {\n            status: \"error\",\n            error: rowResult.error,\n          });\n        }\n      }\n    };\n    const durableIdentityCount = accepted.filter(\n      ({ params }) => params.matchIdentity !== undefined,\n    ).length;\n    const hasDurableIdentity = durableIdentityCount > 0;\n    const hasClaims = acceptedWork.some(({ claim }) => claim !== undefined);\n    if (\n      hasDurableIdentity &&\n      durableIdentityCount === accepted.length &&\n      !hasClaims &&\n      frame.target.insertEdgesDurableBatchReturning !== undefined\n    ) {\n      const rows = await requireDefined(frame.session.createEdgesDurable)(\n        acceptedWork,\n      );\n      const outcomes = classifyDurableEdgeBatchOutcomes(\n        accepted.map((prepared) => prepared.params),\n        rows,\n      );\n      for (const [index, prepared] of accepted.entries()) {\n        if (requireDefined(outcomes[index]) === \"conflict\") {\n          record(prepared.candidate.edge, {\n            status: \"error\",\n            error: new EdgeMatchIdentityConflictError({\n              attempted: [\n                {\n                  id: prepared.params.id,\n                  identityName: requireDefined(prepared.params.matchIdentity)\n                    .name,\n                  kind: prepared.params.kind,\n                },\n              ],\n            }).message,\n          });\n        } else {\n          record(prepared.candidate.edge, { status: \"created\" });\n        }\n      }\n    } else if (hasDurableIdentity) {\n      const batchAttempt = await catchEdgeCreateRefusalWithSavepoint(\n        frame,\n        async () => frame.session.createEdgesNoReturn(acceptedWork),\n      );\n      const batchResult = batchAttempt.result;\n      if (batchResult.ok) {\n        for (const { candidate } of accepted) {\n          record(candidate.edge, { status: \"created\" });\n        }\n      } else {\n        if (batchAttempt.rollbackProtection !== \"savepoint\") {\n          throw new ConfigurationError(\n            \"An imported durable edge batch cannot be retried row by row without savepoint rollback protection.\",\n            {\n              code: \"IMPORT_EDGE_BATCH_RETRY_REQUIRES_SAVEPOINT\",\n              graphId,\n            },\n            {\n              suggestion:\n                \"Use a transactional backend whose root capability verdict and transaction port both provide statement execution, so TypeGraph can roll back the refused batch before attributing its rows individually.\",\n            },\n          );\n        }\n        // A database-arbitrated refusal can identify only the batch, not the\n        // losing row. The slice savepoint has restored every row and claim, so\n        // retry one at a time and let each row's savepoint produce honest\n        // created/error accounting.\n        await retryAcceptedIndividually();\n      }\n    } else {\n      await frame.session.createEdgesNoReturn(acceptedWork);\n      for (const { candidate } of accepted) {\n        record(candidate.edge, { status: \"created\" });\n      }\n    }\n  }\n\n  for (const edge of deferred) {\n    record(\n      edge,\n      await processEdge(\n        frame,\n        graphId,\n        registry,\n        edge,\n        edgeSchemas,\n        nodeSchemas,\n        options,\n        importedNodeIds,\n      ),\n    );\n  }\n}\n\n/**\n * Processes rows deferred from the set-oriented slice (currently duplicate\n * ids). The savepoint cost below is therefore paid only on this exceptional\n * path, or during the rare per-row retry after a durable batch refusal.\n */\nasync function processEdge(\n  frame: ImportWriteFrame,\n  graphId: string,\n  registry: KindRegistry,\n  edge: InterchangeEdge,\n  edgeSchemas: ReadonlyMap<string, EdgeSchemaEntry>,\n  nodeSchemas: ReadonlyMap<string, NodeSchemaEntry>,\n  options: ResolvedImportOptions,\n  importedNodeIds: Set<string>,\n): Promise<ProcessResult> {\n  // Validate edge kind exists\n  const schemaEntry = edgeSchemas.get(edge.kind);\n  if (!schemaEntry) {\n    return { status: \"error\", error: `Unknown edge kind: ${edge.kind}` };\n  }\n\n  // Validate endpoint kinds exist\n  if (!nodeSchemas.has(edge.from.kind)) {\n    return {\n      status: \"error\",\n      error: `Unknown from node kind: ${edge.from.kind}`,\n    };\n  }\n  if (!nodeSchemas.has(edge.to.kind)) {\n    return { status: \"error\", error: `Unknown to node kind: ${edge.to.kind}` };\n  }\n\n  // Validate endpoint kinds are allowed for this edge type. Uses the shared,\n  // subclass-aware check (registry.isAssignableTo) that the collection API uses,\n  // so an edge whose endpoint is a subclass of a declared kind — legal in the\n  // store and emitted verbatim by export — imports cleanly instead of being\n  // rejected by an exact-kind comparison.\n  const endpointError = validateEdgeEndpoints(\n    edge.kind,\n    edge.from.kind,\n    edge.to.kind,\n    schemaEntry.registration,\n    registry,\n  );\n  if (endpointError !== undefined) {\n    return { status: \"error\", error: endpointError.message };\n  }\n\n  // Validate references exist (in DB or in import batch)\n  if (options.validateReferences) {\n    const fromKey = makeNodeKey(edge.from.kind, edge.from.id);\n    const toKey = makeNodeKey(edge.to.kind, edge.to.id);\n\n    // Check import batch first, then DB. The DB row must be LIVE: getNode\n    // returns tombstones, and inserting an edge whose endpoint is\n    // soft-deleted would bypass the endpoint-liveness invariant the\n    // collection API enforces.\n    if (!importedNodeIds.has(fromKey)) {\n      const fromExists = await frame.target.getNode(\n        graphId,\n        edge.from.kind,\n        edge.from.id,\n      );\n      if (fromExists === undefined || !isLiveNodeRow(fromExists)) {\n        return {\n          status: \"error\",\n          error: `From node not found: ${edge.from.kind}:${edge.from.id}`,\n        };\n      }\n    }\n\n    if (!importedNodeIds.has(toKey)) {\n      const toExists = await frame.target.getNode(\n        graphId,\n        edge.to.kind,\n        edge.to.id,\n      );\n      if (toExists === undefined || !isLiveNodeRow(toExists)) {\n        return {\n          status: \"error\",\n          error: `To node not found: ${edge.to.kind}:${edge.to.id}`,\n        };\n      }\n    }\n  }\n\n  // Validate and transform properties\n  const propsResult = validateProperties(\n    edge.properties,\n    schemaEntry.schema,\n    options.onUnknownProperty,\n  );\n\n  if (!propsResult.success) {\n    return { status: \"error\", error: propsResult.error };\n  }\n\n  const validityError = validateValidityWindow(edge);\n  if (validityError !== undefined) {\n    return { status: \"error\", error: validityError };\n  }\n\n  // Check if edge already exists\n  const existing = await frame.target.getEdge(graphId, edge.id);\n\n  if (existing) {\n    // Same prior question as the batched path, answered by the same owner.\n    const identityConflict = edgeIdentityConflict(edge, existing);\n    if (identityConflict !== undefined) {\n      return { status: \"error\", error: identityConflict };\n    }\n    switch (options.onConflict) {\n      case \"skip\": {\n        return {\n          status: \"skipped\",\n          liveTarget: existing.deleted_at === undefined,\n        };\n      }\n      case \"error\": {\n        return { status: \"error\", error: `Edge already exists: ${edge.id}` };\n      }\n      case \"update\": {\n        // Same contract as nodes: import never resurrects a tombstone, and\n        // the backend's update targets live rows only.\n        if (existing.deleted_at !== undefined) {\n          return { status: \"skipped\", liveTarget: false };\n        }\n        const identityUpdateError = importedEdgeIdentityUpdateError(\n          schemaEntry.registration,\n          edge,\n          existing,\n          propsResult.data,\n        );\n        if (identityUpdateError !== undefined) {\n          return { status: \"error\", error: identityUpdateError };\n        }\n        const updateWindow = validateUpdateValidityWindow(\n          edge,\n          existing.valid_from,\n        );\n        if (!updateWindow.ok) {\n          return { status: \"error\", error: updateWindow.error };\n        }\n        const updateError = await updateImportedEdge(\n          frame.session,\n          edge,\n          propsResult.data,\n          updateWindow.value,\n        );\n        if (updateError !== undefined) {\n          return { status: \"error\", error: updateError };\n        }\n        return { status: \"updated\" };\n      }\n    }\n  }\n\n  const preparation = await catchEdgeCreateRefusal(() =>\n    prepareEdgeImportCreate(\n      graphId,\n      { edge, props: propsResult.data },\n      schemaEntry.registration,\n    ),\n  );\n  if (!preparation.ok) {\n    return { status: \"error\", error: preparation.error };\n  }\n\n  // Probe first (for the error text), then create through the session, which\n  // claims before it writes — the same order the collection create uses. No\n  // pending state is needed: this path writes each edge as it goes, so the next\n  // row's probe reads the previous one from the same transaction.\n  const { cardinality, params } = preparation.value;\n  const cardinalityResult = await catchDeclaredConstraintRefusal(() =>\n    checkCardinalityConstraint(\n      { graphId, registry, backend: frame.target },\n      edge.kind,\n      cardinality,\n      edge.from.kind,\n      edge.from.id,\n      edge.to.kind,\n      edge.to.id,\n      edge.validTo,\n    ),\n  );\n  if (!cardinalityResult.ok) {\n    return { status: \"error\", error: cardinalityResult.error };\n  }\n\n  const { result: createResult } = await catchEdgeCreateRefusalWithSavepoint(\n    frame,\n    () => frame.session.createEdge(importEdgeInsertWork(params, cardinality)),\n  );\n  if (!createResult.ok) {\n    return { status: \"error\", error: createResult.error };\n  }\n\n  return { status: \"created\" };\n}\n\n/**\n * The insert unit for one imported edge: the row params and the cardinality\n * claim the row owes.\n *\n * ONE owner, shared by the batched slice and the per-row fallback, for the same\n * reason {@link importNodeCreateWork} is one: two spellings of the same row are\n * two spellings that can drift. The claim is built here and ISSUED by the\n * session, which is the only handle in this module that reaches a write member.\n */\nfunction importEdgeInsertWork(\n  params: InsertEdgeParams,\n  cardinality: Cardinality,\n): EdgeInsertWork {\n  const claim = edgeCardinalityClaim(cardinality, params);\n  return { params, claim };\n}\n\n// ============================================================\n// Property Validation\n// ============================================================\n\ntype ValidationResult =\n  | { success: true; data: Record<string, unknown> }\n  | { success: false; error: string };\n\nfunction validateProperties(\n  properties: Record<string, unknown>,\n  schema: z.ZodObject<z.ZodRawShape>,\n  unknownStrategy: UnknownPropertyStrategy,\n): ValidationResult {\n  try {\n    // Get the schema's known keys\n    const knownKeys = new Set(Object.keys(schema.shape));\n\n    // Check for unknown properties\n    const unknownKeys = Object.keys(properties).filter(\n      (key) => !knownKeys.has(key),\n    );\n\n    if (unknownKeys.length > 0) {\n      switch (unknownStrategy) {\n        case \"error\": {\n          return {\n            success: false,\n            error: `Unknown properties: ${unknownKeys.join(\", \")}`,\n          };\n        }\n        case \"strip\": {\n          // Remove unknown properties\n          // Data-keyed: `knownKeys` are schema-declared property names.\n          const stripped = createDataKeyedBag<unknown>();\n          for (const key of knownKeys) {\n            if (hasOwnKey(properties, key)) {\n              stripped[key] = properties[key];\n            }\n          }\n          // Validate stripped properties\n          const result = schema.safeParse(stripped);\n          if (!result.success) {\n            return {\n              success: false,\n              error: formatZodError(result.error),\n            };\n          }\n          return {\n            success: true,\n            data: result.data,\n          };\n        }\n        case \"allow\": {\n          // Validate the known fields, then return the ORIGINAL properties\n          // verbatim — unknown keys preserved, known values byte-for-byte.\n          // Exported data already carries post-transform values, so\n          // re-applying schema transforms here would corrupt every\n          // export→import round trip whose transforms are not idempotent.\n          // \"allow\" is the fidelity-preserving strategy; \"strip\" (and the\n          // create path) remain the normalizing ones.\n          const result = schema.safeParse(properties);\n          if (!result.success) {\n            return {\n              success: false,\n              error: formatZodError(result.error),\n            };\n          }\n          return { success: true, data: properties };\n        }\n      }\n    }\n\n    // No unknown properties - standard validation\n    const result = schema.safeParse(properties);\n    if (!result.success) {\n      return { success: false, error: formatZodError(result.error) };\n    }\n\n    return { success: true, data: result.data };\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    return { success: false, error: `Validation error: ${message}` };\n  }\n}\n\nfunction formatZodError(error: z.ZodError): string {\n  return error.issues\n    .map((issue) => {\n      const path = issue.path.join(\".\");\n      return path ? `${path}: ${issue.message}` : issue.message;\n    })\n    .join(\"; \");\n}\n\n// ============================================================\n// Helpers\n// ============================================================\n\nfunction makeNodeKey(kind: string, id: string): string {\n  return encodeTupleKey([kind, id]);\n}\n","/**\n * Graph data export functionality.\n *\n * Exports nodes and edges from a store to the interchange format.\n */\nimport { acquireSerializedStreamLease } from \"../backend/transaction-resource\";\nimport {\n  type GraphBackend,\n  rowPropsToObject,\n  type TransactionBackend,\n} from \"../backend/types\";\nimport {\n  getEdgeKinds,\n  getNodeKinds,\n  type GraphDef,\n} from \"../core/define-graph\";\nimport {\n  ConfigurationError,\n  ExportStreamCancelledError,\n  ExportStreamIdleTimeoutError,\n} from \"../errors\";\nimport { storeBackend, storeRuntime } from \"../store/runtime-port\";\nimport { type Store } from \"../store/store\";\nimport { nowIso } from \"../utils/date\";\nimport { requireDefined } from \"../utils/presence\";\nimport { serializedStreamRefusal } from \"./import\";\nimport { markExportStreamBackend } from \"./stream-source\";\nimport {\n  type ExportOptionsInput,\n  type ExportStreamOptionsInput,\n  ExportStreamOptionsSchema,\n  FORMAT_VERSION,\n  type GraphData,\n  type GraphDataHeader,\n  type GraphInterchangeChunk,\n  type InterchangeEdge,\n  type InterchangeIdentityAssertion,\n  type InterchangeNode,\n} from \"./types\";\n\n// ============================================================\n// Export Function\n// ============================================================\n\n/**\n * Export graph data from a store.\n *\n * @param store - The graph store to export from\n * @param options - Export configuration\n * @returns Graph data in interchange format\n *\n * @example\n * ```typescript\n * const data = await exportGraph(store, {\n *   nodeKinds: [\"Person\", \"Organization\"],\n *   includeMeta: true,\n * });\n *\n * // Write to file\n * await fs.writeFile(\"backup.json\", JSON.stringify(data, null, 2));\n * ```\n */\nexport async function exportGraph<G extends GraphDef>(\n  store: Store<G>,\n  options?: ExportOptionsInput,\n): Promise<GraphData> {\n  const nodes: InterchangeNode[] = [];\n  const edges: InterchangeEdge[] = [];\n  const identityAssertions: InterchangeIdentityAssertion[] = [];\n  let header: GraphDataHeader | undefined;\n  for await (const chunk of exportGraphStream(store, options)) {\n    switch (chunk.type) {\n      case \"header\": {\n        header = chunk.header;\n        break;\n      }\n      case \"nodes\": {\n        nodes.push(...chunk.nodes);\n        break;\n      }\n      case \"edges\": {\n        edges.push(...chunk.edges);\n        break;\n      }\n      case \"identity\": {\n        identityAssertions.push(...chunk.assertions);\n        break;\n      }\n    }\n  }\n  if (header === undefined) {\n    throw new Error(\"Graph export stream ended before emitting its header.\");\n  }\n  const { identity, ...headerWithoutIdentity } = header;\n  return {\n    ...headerWithoutIdentity,\n    nodes,\n    edges,\n    ...(identity === undefined ?\n      {}\n    : {\n        identity: { ...identity, assertions: identityAssertions },\n      }),\n  };\n}\n\n/**\n * Exports a graph as bounded node and edge chunks. The stream always yields one\n * header, then every node chunk, then every edge chunk. Consumers that write to\n * a network, file, or fresh working copy can process one chunk at a time rather\n * than materializing a graph-sized {@link GraphData} value.\n *\n * ## One snapshot, WHERE THE BACKEND HAS TRANSACTIONS\n *\n * On a backend reporting `capabilities.execution.interactiveTransactions`, the whole export —\n * header, every node page, every edge page, every identity page — is read\n * inside ONE `repeatable_read` / `read_only` transaction, so a slow consumer\n * still gets one point in time rather than a mixture of the graph as it was at\n * the first chunk and as it is at the last.\n *\n * A backend WITHOUT transactions (SQLite `transactionMode: \"none\"`, the\n * session-less HTTP Postgres drivers) opens no such transaction: its export\n * paginates statement by statement, and a write committed mid-stream can appear\n * in the pages that follow. There is no way to offer the guarantee on an engine\n * that cannot frame the reads, so it is a declared capability gap rather than\n * something the stream pretends to. Callers needing a coherent export from such\n * a backend must quiesce writes for its duration.\n *\n * ## Stopping a stream you will not finish\n *\n * While a transactional stream is open it holds that snapshot transaction, and\n * on a serialized connection it holds the connection's one EXCLUSIVE stream\n * lease with it. Every cooperative exit settles both, because each runs the\n * generator's `finally`: `break` or `throw` out of a `for await`, and an\n * explicit `iterator.return()`. (A non-transactional stream holds neither, so\n * it has nothing to strand — but it still owes its consumer an answer, which\n * the same cancellation path gives it.)\n *\n * A consumer that pulls `next()` and then simply DROPS the iterator has no\n * cooperative exit — async-generator `finally` blocks do not run on garbage\n * collection — so it must pass {@link ExportOptions.signal} and abort it, or\n * configure {@link ExportStreamOptions.idleTimeoutMs}. The idle clock covers\n * only time after a chunk is delivered and before the consumer asks for the\n * next one; database read time is not consumer idleness. Without either\n * mechanism, the snapshot transaction stays open for the life of the process\n * and every later interchange stream on that connection is refused on behalf\n * of a stream nobody is reading.\n *\n * ### Why there is no garbage-collection safety net (#429)\n *\n * A `FinalizationRegistry` on the iterable cannot close this: it is not merely\n * unreliable here, it can never fire. The producer is interruptible in exactly\n * one place — it is parked in {@link RendezvousChannel.push} waiting for the\n * consumer, not in the database — so any cleanup state capable of settling an\n * abandoned stream has to reach that channel. A registry holds its held value\n * STRONGLY, and holding anything that reaches the channel's scope keeps the\n * abandoned generator permanently reachable: measured on Node 24, publishing\n * just `channel.abort` is enough to stop the stream being collected, while\n * publishing an unrelated object is not. The net's own bookkeeping would\n * therefore be what kept the entry from ever firing — a safety promise that\n * reads as protection and is not there. Explicit cancellation and the idle\n * timeout are the mechanisms, and they are contracts rather than hints.\n */\nexport function exportGraphStream<G extends GraphDef>(\n  store: Store<G>,\n  options?: ExportStreamOptionsInput,\n): AsyncIterable<GraphInterchangeChunk> {\n  const backend = storeBackend(store);\n  return markExportStreamBackend(\n    exportGraphStreamFromBackend(store, backend, options),\n    backend,\n  );\n}\n\nasync function* exportGraphStreamFromBackend<G extends GraphDef>(\n  store: Store<G>,\n  backend: GraphBackend,\n  options?: ExportStreamOptionsInput,\n): AsyncIterable<GraphInterchangeChunk> {\n  const parsed = ExportStreamOptionsSchema.parse(options ?? {});\n  // Identity rows carry their effective-time windows unconditionally. Their\n  // endpoint rows must therefore carry temporal bounds too, or the store's own\n  // export could not prove on re-import that each endpoint existed throughout\n  // an assertion's window.\n  const exportsIdentity = store.graph.identity !== undefined;\n  const explicitlyDisabledTemporalFields = options?.includeTemporal === false;\n  if (exportsIdentity && explicitlyDisabledTemporalFields) {\n    throw new ConfigurationError(\n      \"Identity export requires temporal endpoint fields.\",\n      {\n        code: \"IDENTITY_EXPORT_REQUIRES_TEMPORAL_FIELDS\",\n        identityMode: parsed.identityMode,\n        includeTemporal: false,\n      },\n      {\n        suggestion:\n          \"Remove includeTemporal or set it to true when exporting an identity-enabled graph.\",\n      },\n    );\n  }\n  const resolved =\n    exportsIdentity ? { ...parsed, includeTemporal: true } : parsed;\n  const signal = resolved.signal;\n  const idleTimeoutMs = resolved.idleTimeoutMs;\n  const channel = createRendezvousChannel<GraphInterchangeChunk>();\n  let idleTimer: ReturnType<typeof setTimeout> | undefined;\n  let subscribedToSignal = false;\n  function unsubscribeFromSignal(): void {\n    if (!subscribedToSignal) return;\n    signal?.removeEventListener(\"abort\", abortStream);\n    subscribedToSignal = false;\n  }\n  function clearIdleTimer(): void {\n    if (idleTimer === undefined) return;\n    clearTimeout(idleTimer);\n    idleTimer = undefined;\n  }\n  function armIdleTimer(): void {\n    if (idleTimeoutMs === undefined) return;\n    idleTimer = setTimeout(() => {\n      idleTimer = undefined;\n      unsubscribeFromSignal();\n      channel.abort(\n        new ExportStreamIdleTimeoutError(\n          store.graphId,\n          idleTimeoutMs,\n          backend.capabilities.execution.interactiveTransactions,\n        ),\n      );\n    }, idleTimeoutMs);\n    unrefTimer(idleTimer);\n  }\n  function abortStream(): void {\n    clearIdleTimer();\n    channel.abort(\n      exportStreamCancelled(\n        \"mid-stream\",\n        store.graphId,\n        signal,\n        backend.capabilities.execution.interactiveTransactions,\n      ),\n    );\n  }\n  // REGISTER, THEN RE-CHECK — and in that order, because the two halves cover\n  // different instants and neither covers both:\n  //\n  // - The listener covers every abort from now on, including one raised\n  //   SYNCHRONOUSLY by the driver inside `backend.transaction(...)` below. That\n  //   is the window this ordering exists for: subscribing after that call\n  //   returned meant such an abort was delivered to nobody — an `AbortSignal`\n  //   does not replay `abort` to a listener that arrives late — and the export\n  //   went on holding its snapshot and its lease with `signal.aborted === true`.\n  // - The re-check covers an abort that already happened, which the event will\n  //   never deliver at all. It is not ceremonial: `parse` above reads the\n  //   caller's options object, and a getter on it can abort the controller\n  //   before this line is reached.\n  //\n  // Nothing between them can yield, so there is no instant at which an abort is\n  // neither seen by the re-check nor delivered to the listener.\n  signal?.addEventListener(\"abort\", abortStream, { once: true });\n  subscribedToSignal = signal !== undefined;\n  if (signal?.aborted === true) {\n    // Nothing has been claimed or opened yet, so this stream is over before it\n    // started rather than cancelled in flight — and it must leave no listener\n    // on a signal the caller may hold for the rest of the process.\n    unsubscribeFromSignal();\n    throw exportStreamCancelled(\n      \"before-open\",\n      store.graphId,\n      signal,\n      backend.capabilities.execution.interactiveTransactions,\n    );\n  }\n  const produce = async (\n    target: GraphBackend | TransactionBackend,\n  ): Promise<void> => {\n    await produceExportChunks(store, target, resolved, (chunk) =>\n      channel.push(chunk),\n    );\n  };\n  /**\n   * Opens the snapshot and wires the producer, or gives back EVERYTHING this\n   * stream has taken and rethrows.\n   *\n   * On a serialized backend the snapshot transaction holds the single\n   * connection for the whole stream. Claiming that connection's one stream\n   * lease for the duration makes a concurrent import — or a SECOND export,\n   * whose snapshot transaction would nest inside this one just as fatally —\n   * be refused rather than left to wait for a slot that cannot free up. This is\n   * what the stream's consumer identity cannot answer once a caller wraps the\n   * iterable. And if another stream already holds that connection, THIS side is\n   * the one refused: it is the stream that started second. The claim is\n   * deliberately inside the generator body: it must begin when the transaction\n   * opens (first pull), not when the iterable is constructed.\n   *\n   * Two things can stop the stream before it starts, and both give back what\n   * they took. The lease refusal takes nothing but the signal subscription made\n   * above. `backend.transaction(...)` is a driver call, and a driver can reject\n   * SYNCHRONOUSLY — a closed handle, a pool that refuses the checkout — before\n   * any promise exists; the release is installed on the promise it returns, so\n   * a synchronous throw would otherwise skip it and strand the lease for the\n   * life of the process, refusing every later stream on that connection on\n   * behalf of one that never ran a statement.\n   */\n  const beginProducer = (): Promise<void> => {\n    try {\n      const releaseSnapshotExport =\n        backend.capabilities.execution.interactiveTransactions ?\n          claimSnapshotExportLeaseOrRefuse(store.graphId, backend)\n        : () => {\n            // No snapshot transaction is opened here, so nothing was claimed:\n            // a non-transactional export holds nothing against a concurrent\n            // stream.\n          };\n      try {\n        const started =\n          backend.capabilities.execution.interactiveTransactions ?\n            backend.transaction((target) => produce(target), {\n              isolationLevel: \"repeatable_read\",\n              accessMode: \"read_only\",\n            })\n          : produce(backend);\n        return started.then(\n          () => {\n            releaseSnapshotExport();\n            channel.finish();\n          },\n          (error: unknown) => {\n            releaseSnapshotExport();\n            channel.fail(error);\n          },\n        );\n      } catch (error) {\n        releaseSnapshotExport();\n        throw error;\n      }\n    } catch (error) {\n      unsubscribeFromSignal();\n      throw error;\n    }\n  };\n  const producer = beginProducer();\n\n  try {\n    for (;;) {\n      const delivery = await channel.take();\n      if (delivery === undefined) return;\n      armIdleTimer();\n      yield delivery.value;\n      clearIdleTimer();\n      delivery.acknowledge();\n    }\n  } finally {\n    // Unsubscribe FIRST: this stream is settling through a cooperative path, so\n    // an abort arriving during the teardown below must not publish a terminal\n    // error in place of the clean end the consumer is owed — and a signal the\n    // caller reuses for its next export must not still reach this one, nor keep\n    // this generator's scope alive for as long as the caller holds it.\n    unsubscribeFromSignal();\n    clearIdleTimer();\n    channel.cancel();\n    await producer;\n  }\n}\n\n/** Do not let an opt-in safety timer keep a Node.js process alive by itself. */\nfunction unrefTimer(timer: ReturnType<typeof setTimeout>): void {\n  if (\n    typeof timer === \"object\" &&\n    \"unref\" in timer &&\n    typeof timer.unref === \"function\"\n  ) {\n    timer.unref();\n  }\n}\n\n/**\n * How far the stream had got when the abort landed. Every phase ends the same\n * way for the caller — nothing is held, start a new export — so they share one\n * error class and ONE `code`; only the message differs, because a refusal that\n * claimed nothing must not claim to have rolled anything back.\n *\n * - `before-open` — the abort was already visible when the stream was asked for\n *   its first chunk. No transaction was opened and no lease claimed, whatever\n *   the backend can do.\n * - `mid-stream` — the abort arrived from the moment the stream began opening\n *   onward, INCLUDING synchronously inside `backend.transaction(...)`. What was\n *   given back depends on what was taken, which is why this phase needs the\n *   backend's capability to describe itself honestly.\n */\ntype ExportAbortPhase = \"before-open\" | \"mid-stream\";\n\n/**\n * The single owner of the error an aborted export stream reports, so the\n * pre-flight refusal and the mid-stream abort state the same condition in the\n * same vocabulary — one code, the signal's own reason as `cause`, and a message\n * that is true of the phase AND of the backend it describes.\n *\n * `framed` is `backend.capabilities.execution.interactiveTransactions`. A non-transactional export\n * opened no snapshot and claimed no lease, so telling its consumer that a\n * snapshot was rolled back and a connection released would describe work that\n * never happened — and would hide the thing that consumer actually needs to\n * know, which is that the chunks it did receive were never one point in time.\n */\nfunction exportStreamCancelled(\n  phase: ExportAbortPhase,\n  graphId: string,\n  signal: AbortSignal | undefined,\n  framed: boolean,\n): ExportStreamCancelledError {\n  const message =\n    phase === \"before-open\" ?\n      \"The graph export stream was aborted through its AbortSignal before it opened: no snapshot transaction was started and no database connection claimed.\"\n    : framed ?\n      \"The graph export stream was aborted through its AbortSignal: its repeatable-read snapshot has been rolled back and the connection it held released.\"\n    : \"The graph export stream was aborted through its AbortSignal: its remaining reads were abandoned. This backend does not support transactions, so the export held no snapshot and no connection — and the chunks already delivered were never guaranteed to agree with one another.\";\n  const cause: unknown = signal?.reason;\n  // The suggestion must be capability-aware for the same reason the message is:\n  // the class default claims a snapshot rollback, which is false on the\n  // non-transactional arm and for a stream that never opened.\n  const suggestion =\n    phase === \"before-open\" ?\n      \"Start a new export; the aborted one claimed nothing.\"\n    : framed ?\n      \"Start a new export; the aborted one released its snapshot transaction and the connection it held.\"\n    : \"Start a new export; nothing was held, but discard the chunks already delivered unless partial, mutually-inconsistent data is acceptable.\";\n  return new ExportStreamCancelledError(\n    message,\n    { graphId },\n    {\n      suggestion,\n      ...(cause === undefined ? {} : { cause }),\n    },\n  );\n}\n\n/**\n * Claims the serialized connection for this export's snapshot transaction, or\n * refuses because another long-lived stream — a streaming import, or another\n * snapshot export — is already using it.\n *\n * The check and the claim are one synchronous section inside\n * {@link acquireSerializedStreamLease}, which offers no way to ask without\n * claiming. On a single-threaded event loop that makes \"no other stream held\n * this connection when the snapshot opened\" true for the whole stream: nobody\n * can slip a claim in between, and two streams cannot both conclude the\n * connection was free.\n *\n * Only called when the backend is transactional: a `transactionMode: \"none\"`\n * export holds nothing open, interleaves harmlessly, and must not be refused —\n * nor refuse anyone.\n */\nfunction claimSnapshotExportLeaseOrRefuse(\n  graphId: string,\n  backend: GraphBackend,\n): () => void {\n  const lease = acquireSerializedStreamLease(backend, \"export-snapshot\");\n  if (!lease.acquired) {\n    throw serializedStreamRefusal({\n      graphId,\n      requested: \"export-snapshot\",\n      heldBy: lease.heldBy,\n    });\n  }\n  return lease.release;\n}\n\nasync function produceExportChunks<G extends GraphDef>(\n  store: Store<G>,\n  backend: GraphBackend | TransactionBackend,\n  options: ExportOptions_ & Readonly<{ batchSize: number }>,\n  emit: (chunk: GraphInterchangeChunk) => Promise<void>,\n): Promise<void> {\n  const graphId = store.graphId;\n  const nodeKinds = options.nodeKinds ?? getNodeKinds(store.graph);\n  const edgeKinds = options.edgeKinds ?? getEdgeKinds(store.graph);\n  const schemaVersion = await backend.getActiveSchema(graphId);\n\n  await emit({\n    type: \"header\",\n    header: {\n      formatVersion: FORMAT_VERSION,\n      exportedAt: nowIso(),\n      source: {\n        type: \"typegraph-export\",\n        graphId,\n        schemaVersion: schemaVersion?.version ?? 1,\n      },\n      ...(store.graph.identity === undefined ?\n        {}\n      : {\n          identity: {\n            profile: \"typegraph-identity-v1\" as const,\n            mode: options.identityMode,\n          },\n        }),\n    },\n  });\n\n  for (const kind of nodeKinds) {\n    for await (const chunk of exportNodeChunks(\n      backend,\n      graphId,\n      kind,\n      options,\n    )) {\n      await emit(chunk);\n    }\n  }\n  for (const kind of edgeKinds) {\n    for await (const chunk of exportEdgeChunks(\n      backend,\n      graphId,\n      kind,\n      options,\n    )) {\n      await emit(chunk);\n    }\n  }\n  if (store.graph.identity === undefined) return;\n\n  let after: string | undefined;\n  for (;;) {\n    const page = await storeRuntime(store).readIdentityAssertionPageAtTarget(\n      backend,\n      options.identityMode,\n      {\n        ...(options.nodeKinds === undefined ? {} : { nodeKinds }),\n        includeDeleted: options.includeDeleted,\n        ...(after === undefined ? {} : { after }),\n        limit: options.batchSize,\n      },\n    );\n    if (page.assertions.length > 0) {\n      await emit({ type: \"identity\", assertions: [...page.assertions] });\n    }\n    if (page.done) return;\n    after = requireDefined(page.nextAfter);\n  }\n}\n\ntype ExportOptions_ = Readonly<{\n  includeTemporal: boolean;\n  includeMeta: boolean;\n  includeDeleted: boolean;\n  identityMode: \"state\" | \"archival\";\n  nodeKinds?: readonly string[] | undefined;\n  edgeKinds?: readonly string[] | undefined;\n}>;\n\ntype RendezvousDelivery<T> = Readonly<{\n  value: T;\n  acknowledge: () => void;\n}>;\n\ntype RendezvousChannel<T> = Readonly<{\n  push: (value: T) => Promise<void>;\n  take: () => Promise<RendezvousDelivery<T> | undefined>;\n  finish: () => void;\n  fail: (error: unknown) => void;\n  /** The consumer left through a cooperative path; the stream simply ends. */\n  cancel: () => void;\n  /**\n   * Nobody is coming back for this stream. Unwinds the producer — which rolls\n   * the snapshot transaction back and releases the connection's lease on its\n   * way out — AND makes `error` the channel's terminal state, so a consumer\n   * that is waiting on `next()`, or that asks again later, is told why rather\n   * than handed a silent end of stream it would read as a complete export.\n   */\n  abort: (error: Error) => void;\n}>;\n\nfunction createRendezvousChannel<T>(): RendezvousChannel<T> {\n  type PendingPush = Readonly<{\n    delivery: RendezvousDelivery<T>;\n    reject: (error: unknown) => void;\n  }>;\n  type PendingTake = Readonly<{\n    resolve: (delivery: RendezvousDelivery<T> | undefined) => void;\n    reject: (error: unknown) => void;\n  }>;\n\n  const consumerCancelledError = new Error(\"Export stream consumer cancelled.\");\n  let pendingPush: PendingPush | undefined;\n  let pendingTake: PendingTake | undefined;\n  let inFlightReject: ((error: unknown) => void) | undefined;\n  let terminal: Readonly<{ error?: Error }> | undefined;\n  /**\n   * Why the producer is being torn down, once something decided to tear it\n   * down — a cooperative consumer exit ({@link cancel}) or a cancellation\n   * ({@link abort}).\n   *\n   * The single owner of \"this stream is unwinding\": it is what every pending\n   * and future push rejects with, so the producer always unwinds through one\n   * rejection whichever side started it, and it is how {@link fail} recognizes\n   * the failure this channel caused itself.\n   */\n  let producerUnwindError: Error | undefined;\n\n  function push(value: T): Promise<void> {\n    if (producerUnwindError !== undefined) {\n      return Promise.reject(producerUnwindError);\n    }\n    if (terminal !== undefined || pendingPush !== undefined) {\n      return Promise.reject(\n        new Error(\"Cannot push to a completed or occupied export channel.\"),\n      );\n    }\n    return new Promise<void>((resolve, reject) => {\n      const delivery = {\n        value,\n        acknowledge: () => {\n          inFlightReject = undefined;\n          resolve();\n        },\n      };\n      if (pendingTake !== undefined) {\n        const take = pendingTake;\n        pendingTake = undefined;\n        inFlightReject = reject;\n        take.resolve(delivery);\n        return;\n      }\n      pendingPush = { delivery, reject };\n    });\n  }\n\n  function take(): Promise<RendezvousDelivery<T> | undefined> {\n    if (pendingPush !== undefined) {\n      const push = pendingPush;\n      pendingPush = undefined;\n      inFlightReject = push.reject;\n      return Promise.resolve(push.delivery);\n    }\n    if (terminal !== undefined) {\n      return terminal.error === undefined ?\n          Promise.resolve(undefined)\n        : Promise.reject(terminal.error);\n    }\n    if (pendingTake !== undefined) {\n      return Promise.reject(\n        new Error(\"Export channel already has a consumer.\"),\n      );\n    }\n    return new Promise<RendezvousDelivery<T> | undefined>((resolve, reject) => {\n      pendingTake = { resolve, reject };\n    });\n  }\n\n  function finish(): void {\n    if (producerUnwindError !== undefined) return;\n    terminal = {};\n    if (pendingTake !== undefined) {\n      const take = pendingTake;\n      pendingTake = undefined;\n      take.resolve(undefined);\n    }\n  }\n\n  function fail(error: unknown): void {\n    // The producer failed with the very rejection this channel handed it in\n    // order to unwind: that is this channel's own doing, not a new outcome to\n    // report. Compared against a DEFINED unwind error only — a producer that\n    // rejects with `undefined` is a real failure and must still reach the\n    // consumer.\n    if (producerUnwindError !== undefined && error === producerUnwindError) {\n      return;\n    }\n    // An abort already published the terminal state the consumer must see; the\n    // producer's own unwinding failure must not overwrite it.\n    if (terminal !== undefined) return;\n    const exportError =\n      error instanceof Error ? error : (\n        new Error(\"Graph export failed.\", { cause: error })\n      );\n    terminal = { error: exportError };\n    if (pendingTake !== undefined) {\n      const take = pendingTake;\n      pendingTake = undefined;\n      take.reject(exportError);\n    }\n  }\n\n  function cancel(): void {\n    if (producerUnwindError !== undefined) return;\n    producerUnwindError = consumerCancelledError;\n    if (pendingPush !== undefined) {\n      const push = pendingPush;\n      pendingPush = undefined;\n      push.reject(consumerCancelledError);\n    }\n    if (inFlightReject !== undefined) {\n      const reject = inFlightReject;\n      inFlightReject = undefined;\n      reject(consumerCancelledError);\n    }\n    if (pendingTake !== undefined) {\n      const take = pendingTake;\n      pendingTake = undefined;\n      take.resolve(undefined);\n    }\n  }\n\n  function abort(error: Error): void {\n    // Nothing is held any more, so this abort has nothing to take back and must\n    // not restate the outcome. The two arms are NOT alike in how they are\n    // reached:\n    //\n    // - `terminal !== undefined` IS reachable. The producer settles\n    //   (`finish`/`fail`) and resolves the consumer's pending take, but the\n    //   generator only resumes to run its `finally` — and unsubscribe — in a\n    //   later microtask. An abort landing in that window finds the outcome\n    //   already published and must leave it alone: the export really did end\n    //   the way `terminal` says, and the consumer has already been handed that\n    //   answer.\n    // - `producerUnwindError !== undefined` is defensive. `cancel()` sets it\n    //   from the generator's `finally`, which unsubscribes BEFORE calling it,\n    //   and the listener is `{ once: true }`, so there is no path today that\n    //   calls `abort` twice or calls it after `cancel`.\n    if (terminal !== undefined || producerUnwindError !== undefined) return;\n    producerUnwindError = error;\n    terminal = { error };\n    if (pendingPush !== undefined) {\n      const push = pendingPush;\n      pendingPush = undefined;\n      push.reject(error);\n    }\n    if (inFlightReject !== undefined) {\n      const reject = inFlightReject;\n      inFlightReject = undefined;\n      reject(error);\n    }\n    if (pendingTake !== undefined) {\n      const take = pendingTake;\n      pendingTake = undefined;\n      take.reject(error);\n    }\n  }\n\n  return { push, take, finish, fail, cancel, abort };\n}\n\n// ============================================================\n// Node Export\n// ============================================================\n\nasync function* exportNodeChunks(\n  backend: GraphBackend | TransactionBackend,\n  graphId: string,\n  kind: string,\n  options: ExportOptions_ & Readonly<{ batchSize: number }>,\n): AsyncIterable<GraphInterchangeChunk> {\n  let after: string | undefined;\n  for (;;) {\n    const rows = await backend.findNodesByKind({\n      graphId,\n      kind,\n      excludeDeleted: !options.includeDeleted,\n      orderBy: \"id\",\n      limit: options.batchSize,\n      ...(after === undefined ? {} : { after }),\n    });\n    if (rows.length === 0) return;\n    const nodes = rows.map((row) => {\n      const node: InterchangeNode = {\n        kind: row.kind,\n        id: row.id,\n        properties: rowPropsToObject(row.props),\n      };\n\n      if (options.includeTemporal) {\n        // validFrom is always emitted (as `null` when the row has no lower\n        // bound) so import can tell \"confirmed open-left\" apart from \"not\n        // requested\" and preserve it instead of defaulting to import time —\n        // see the schema doc on InterchangeNodeSchema.validFrom. validTo has\n        // no such ambiguity (it was never defaulted), so it stays gated.\n        // `null` (not `undefined`) is the wire-protocol signal here — JSON has\n        // no other way to say \"explicitly cleared\" vs. \"field absent\".\n        const validFrom =\n          // eslint-disable-next-line unicorn/no-null\n          row.valid_from ?? null;\n        (node as { validFrom?: string | null }).validFrom = validFrom;\n        if (row.valid_to) {\n          (node as { validTo?: string }).validTo = row.valid_to;\n        }\n      }\n\n      if (options.includeMeta) {\n        (node as { meta?: InterchangeNode[\"meta\"] }).meta = {\n          version: row.version,\n          createdAt: row.created_at,\n          updatedAt: row.updated_at,\n        };\n      }\n\n      return node;\n    });\n    yield { type: \"nodes\", nodes };\n    if (rows.length < options.batchSize) return;\n    after = requireDefined(rows.at(-1)).id;\n  }\n}\n\n// ============================================================\n// Edge Export\n// ============================================================\n\nasync function* exportEdgeChunks(\n  backend: GraphBackend | TransactionBackend,\n  graphId: string,\n  kind: string,\n  options: ExportOptions_ & Readonly<{ batchSize: number }>,\n): AsyncIterable<GraphInterchangeChunk> {\n  let after: string | undefined;\n  for (;;) {\n    const rows = await backend.findEdgesByKind({\n      graphId,\n      kind,\n      excludeDeleted: !options.includeDeleted,\n      orderBy: \"id\",\n      limit: options.batchSize,\n      ...(after === undefined ? {} : { after }),\n    });\n    if (rows.length === 0) return;\n    const edges = rows.map((row) => {\n      const edge: InterchangeEdge = {\n        kind: row.kind,\n        id: row.id,\n        from: {\n          kind: row.from_kind,\n          id: row.from_id,\n        },\n        to: {\n          kind: row.to_kind,\n          id: row.to_id,\n        },\n        properties: rowPropsToObject(row.props),\n      };\n\n      if (options.includeTemporal) {\n        // See exportNodesOfKind's validFrom comment: always emitted (as\n        // `null` when open-left) so import can distinguish \"confirmed no\n        // lower bound\" from \"not requested\".\n        const validFrom =\n          // eslint-disable-next-line unicorn/no-null\n          row.valid_from ?? null;\n        (edge as { validFrom?: string | null }).validFrom = validFrom;\n        if (row.valid_to) {\n          (edge as { validTo?: string }).validTo = row.valid_to;\n        }\n      }\n\n      if (options.includeMeta) {\n        (edge as { meta?: InterchangeEdge[\"meta\"] }).meta = {\n          createdAt: row.created_at,\n          updatedAt: row.updated_at,\n        };\n      }\n\n      return edge;\n    });\n    yield { type: \"edges\", edges };\n    if (rows.length < options.batchSize) return;\n    after = requireDefined(rows.at(-1)).id;\n  }\n}\n","import { assertEdgeMatchIdentityBackendSupport } from \"../backend/edge-match-identity\";\nimport { snapshotExportContention } from \"../backend/transaction-resource\";\nimport type {\n  InsertEdgeParams,\n  InsertNodeParams,\n  TrustedImportOptions,\n  TrustedImportSession,\n} from \"../backend/types\";\nimport type { GraphDef } from \"../core/define-graph\";\nimport { resolveGraphVectorSlots } from \"../core/embedding\";\nimport { getSearchableFields } from \"../core/searchable\";\nimport type { EdgeRegistration } from \"../core/types\";\nimport { TrustedImportError } from \"../errors\";\nimport { resolveEdgeMatchIdentityStorage } from \"../store/edge-match-key\";\nimport { storeBackend, storeCaptureEnabled } from \"../store/runtime-port\";\nimport type { Store } from \"../store/store\";\nimport { isCanonicalIsoDate, isInvertedValidityWindow } from \"../utils/date\";\nimport { serializedStreamRefusal, withImportStreamLease } from \"./import\";\nimport { exportStreamBackend } from \"./stream-source\";\nimport type {\n  GraphData,\n  GraphInterchangeChunk,\n  InterchangeEdge,\n  InterchangeNode,\n} from \"./types\";\n\n/** Counts committed by a trusted initial import. */\nexport type TrustedImportResult = Readonly<{\n  nodes: number;\n  edges: number;\n}>;\n\nfunction rejectUnsupportedStoreFeatures<G extends GraphDef>(\n  store: Store<G>,\n): void {\n  const backend = storeBackend(store);\n  for (const [kind, registration] of Object.entries(store.graph.edges)) {\n    assertEdgeMatchIdentityBackendSupport(\n      registration.matchIdentity,\n      backend.capabilities,\n      kind,\n    );\n  }\n  if (storeCaptureEnabled(store)) {\n    // Trusted import writes rows directly, bypassing the node/edge-\n    // operations layer that TypeGraph's own capture uses to populate the\n    // recorded relations — a check against `storeCaptureEnabled`, not the\n    // public `historyEnabled` getter, so an engine-native `history: true`\n    // store (whose engine versions every write to the live table itself,\n    // regardless of which code path produced it) is unaffected.\n    throw new TrustedImportError(\n      \"Trusted import does not support recorded-time history capture.\",\n      \"history_unsupported\",\n      { graphId: store.graphId },\n    );\n  }\n  if (store.revisionTrackingEnabled) {\n    throw new TrustedImportError(\n      \"Trusted import does not support revision tracking.\",\n      \"revision_tracking_unsupported\",\n      { graphId: store.graphId },\n    );\n  }\n  if (store.graph.identity !== undefined) {\n    throw new TrustedImportError(\n      \"Trusted import does not maintain Operational Identity assertions or closure.\",\n      \"identity_unsupported\",\n      { graphId: store.graphId },\n    );\n  }\n\n  const uniqueKinds = Object.values(store.graph.nodes)\n    .filter((registration) => (registration.unique?.length ?? 0) > 0)\n    .map((registration) => registration.type.kind);\n  if (uniqueKinds.length > 0) {\n    throw new TrustedImportError(\n      \"Trusted import does not maintain node uniqueness sidecars.\",\n      \"uniqueness_unsupported\",\n      { graphId: store.graphId, nodeKinds: uniqueKinds },\n    );\n  }\n\n  const searchableKinds = Object.values(store.graph.nodes)\n    .filter(\n      (registration) =>\n        getSearchableFields(registration.type.schema).length > 0,\n    )\n    .map((registration) => registration.type.kind);\n  if (searchableKinds.length > 0) {\n    throw new TrustedImportError(\n      \"Trusted import does not maintain fulltext sidecars.\",\n      \"fulltext_unsupported\",\n      { graphId: store.graphId, nodeKinds: searchableKinds },\n    );\n  }\n\n  const vectorSlots = resolveGraphVectorSlots(store.graph);\n  if (vectorSlots.length > 0) {\n    throw new TrustedImportError(\n      \"Trusted import does not maintain vector sidecars.\",\n      \"vector_unsupported\",\n      {\n        graphId: store.graphId,\n        fields: vectorSlots.map((slot) => `${slot.nodeKind}.${slot.fieldPath}`),\n      },\n    );\n  }\n}\n\nfunction invalidStream(message: string): TrustedImportError {\n  return new TrustedImportError(message, \"invalid_stream\");\n}\n\n/** The stated validity window of a streamed node or edge. */\ntype StatedValidityWindow = Readonly<{\n  validFrom?: string | null | undefined;\n  validTo?: string | undefined;\n}>;\n\ntype ValidityWindowField = \"validFrom\" | \"validTo\";\n\n/** A stated window field that is not canonical, with the offending value. */\ntype NonCanonicalWindow = Readonly<{\n  field: ValidityWindowField;\n  value: string;\n}>;\n\n/**\n * The first window field of `entity` stating a timestamp that is not canonical\n * fixed-width UTC ISO 8601 — with the offending value — or `undefined` when\n * every stated one is canonical.\n *\n * A trusted stream is never re-parsed, so this is the only place its timestamps\n * are held to the format the rest of the system assumes. It is deliberately\n * format-ONLY — the same {@link isCanonicalIsoDate} decision the untrusted\n * path's schema and the store's own write validation make, and nothing more —\n * because a non-canonical instant is not merely ugly: every temporal filter\n * compares these values AS TEXT against an `asOf` coordinate, so a variable-width\n * one (`...:00.1Z`, an offset, date-only) mis-sorts and silently includes or\n * excludes the wrong rows once stored, and it would mis-decide the negative-width\n * check below on the way in. Two field tests per row costs about a microsecond\n * against the ~4µs an in-memory SQLite row already costs — the price of the\n * stream's ordering claims meaning anything.\n *\n * An absent field states nothing, and a `null` validFrom is a confirmed\n * open-left window (see {@link nodeParams}) — neither is a timestamp to check.\n */\nfunction nonCanonicalWindowOf(\n  entity: StatedValidityWindow,\n): NonCanonicalWindow | undefined {\n  const { validFrom, validTo } = entity;\n  if (typeof validFrom === \"string\" && !isCanonicalIsoDate(validFrom)) {\n    return { field: \"validFrom\", value: validFrom };\n  }\n  if (typeof validTo === \"string\" && !isCanonicalIsoDate(validTo)) {\n    return { field: \"validTo\", value: validTo };\n  }\n  return undefined;\n}\n\n/**\n * The first entity in `entities` stating a non-canonical window timestamp, with\n * the offending field and value. Allocates only on the failing path, so a clean\n * chunk pays one predicate per stated timestamp and nothing else.\n */\nfunction findNonCanonicalWindow<Entity extends StatedValidityWindow>(\n  entities: readonly Entity[],\n): (NonCanonicalWindow & Readonly<{ entity: Entity }>) | undefined {\n  for (const entity of entities) {\n    const nonCanonical = nonCanonicalWindowOf(entity);\n    if (nonCanonical !== undefined) return { entity, ...nonCanonical };\n  }\n  return undefined;\n}\n\n/** The refusal message for a non-canonical window timestamp on `subject`. */\nfunction nonCanonicalWindowMessage(\n  subject: string,\n  field: ValidityWindowField,\n  value: string,\n): string {\n  return (\n    `Non-canonical ${field} in trusted import: ${subject} states \"${value}\". ` +\n    `Expected canonical fixed-width UTC ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ), ` +\n    `which is what makes a stored timestamp sort chronologically against an asOf ` +\n    `coordinate. Convert with new Date(value).toISOString().`\n  );\n}\n\n/**\n * An entity whose stated window has negative width. Trusted import writes\n * straight to SQL and skips schema validation for throughput, but a row that\n * stopped being true before it started is a stream SHAPE fault rather than a\n * policy check: it is unobservable at every `asOf` coordinate, and no later\n * write repairs it. `null` validFrom is a confirmed open-left window, so there\n * is no lower bound to invert against; zero width is legal (see\n * {@link isInvertedValidityWindow}).\n *\n * Only ever reached for a chunk whose timestamps {@link findNonCanonicalWindow}\n * has already accepted, which is what makes the lexicographic compare inside a\n * chronological one.\n */\nfunction hasInvertedWindow(entity: StatedValidityWindow): boolean {\n  return isInvertedValidityWindow(\n    entity.validFrom ?? undefined,\n    entity.validTo,\n  );\n}\n\nfunction nodeParams(graphId: string, node: InterchangeNode): InsertNodeParams {\n  return {\n    graphId,\n    kind: node.kind,\n    id: node.id,\n    props: node.properties,\n    ...(node.validFrom === undefined ? {} : { validFrom: node.validFrom }),\n    ...(node.validTo === undefined ? {} : { validTo: node.validTo }),\n  };\n}\n\nfunction edgeParams(\n  graphId: string,\n  edge: InterchangeEdge,\n  registration: EdgeRegistration,\n): InsertEdgeParams {\n  const matchIdentity = resolveEdgeMatchIdentityStorage(\n    registration.matchIdentity,\n    {\n      fromKind: edge.from.kind,\n      fromId: edge.from.id,\n      toKind: edge.to.kind,\n      toId: edge.to.id,\n      props: edge.properties,\n    },\n    { graphId, edgeKind: edge.kind },\n  );\n  return {\n    graphId,\n    id: edge.id,\n    kind: edge.kind,\n    fromKind: edge.from.kind,\n    fromId: edge.from.id,\n    toKind: edge.to.kind,\n    toId: edge.to.id,\n    props: edge.properties,\n    ...(matchIdentity === undefined ? {} : { matchIdentity }),\n    ...(edge.validFrom === undefined ? {} : { validFrom: edge.validFrom }),\n    ...(edge.validTo === undefined ? {} : { validTo: edge.validTo }),\n  };\n}\n\nasync function consumeTrustedChunks<G extends GraphDef>(\n  store: Store<G>,\n  session: TrustedImportSession,\n  chunks:\n    AsyncIterable<GraphInterchangeChunk> | Iterable<GraphInterchangeChunk>,\n): Promise<TrustedImportResult> {\n  const nodeKinds = new Set(\n    Object.values(store.graph.nodes).map(\n      (registration) => registration.type.kind,\n    ),\n  );\n  const edgeKinds = new Set(\n    Object.values(store.graph.edges).map(\n      (registration) => registration.type.kind,\n    ),\n  );\n  let receivedHeader = false;\n  let receivedEdges = false;\n  let nodeCount = 0;\n  let edgeCount = 0;\n\n  for await (const chunk of chunks) {\n    switch (chunk.type) {\n      case \"header\": {\n        if (receivedHeader) {\n          throw invalidStream(\n            \"Trusted graph interchange stream emitted more than one header.\",\n          );\n        }\n        if (chunk.header.identity !== undefined) {\n          throw invalidStream(\n            \"Trusted graph interchange import does not support identity data. \" +\n              \"Use importGraphStream() for an identity export.\",\n          );\n        }\n        receivedHeader = true;\n        break;\n      }\n      case \"nodes\": {\n        if (!receivedHeader) {\n          throw invalidStream(\n            \"Trusted graph interchange stream must start with a header.\",\n          );\n        }\n        if (receivedEdges) {\n          throw invalidStream(\n            \"Trusted graph interchange stream cannot emit nodes after edges.\",\n          );\n        }\n        const unknownKind = chunk.nodes.find(\n          (node) => !nodeKinds.has(node.kind),\n        )?.kind;\n        if (unknownKind !== undefined) {\n          throw invalidStream(\n            `Unknown node kind in trusted import: ${unknownKind}`,\n          );\n        }\n        const nonCanonicalNode = findNonCanonicalWindow(chunk.nodes);\n        if (nonCanonicalNode !== undefined) {\n          const { entity, field, value } = nonCanonicalNode;\n          throw invalidStream(\n            nonCanonicalWindowMessage(\n              `${entity.kind} \"${entity.id}\"`,\n              field,\n              value,\n            ),\n          );\n        }\n        const invertedNode = chunk.nodes.find((node) =>\n          hasInvertedWindow(node),\n        );\n        if (invertedNode !== undefined) {\n          throw invalidStream(\n            `Inverted validity window in trusted import: ${invertedNode.kind} \"${invertedNode.id}\" ends at ` +\n              `\"${String(invertedNode.validTo)}\", before its validFrom \"${String(invertedNode.validFrom)}\".`,\n          );\n        }\n        await session.insertNodes(\n          chunk.nodes.map((node) => nodeParams(store.graphId, node)),\n        );\n        nodeCount += chunk.nodes.length;\n        break;\n      }\n      case \"edges\": {\n        if (!receivedHeader) {\n          throw invalidStream(\n            \"Trusted graph interchange stream must start with a header.\",\n          );\n        }\n        receivedEdges = true;\n        const invalidEdge = chunk.edges.find(\n          (edge) =>\n            !edgeKinds.has(edge.kind) ||\n            !nodeKinds.has(edge.from.kind) ||\n            !nodeKinds.has(edge.to.kind),\n        );\n        if (invalidEdge !== undefined) {\n          throw invalidStream(\n            `Unknown edge or endpoint kind in trusted import: ${invalidEdge.kind}`,\n          );\n        }\n        const nonCanonicalEdge = findNonCanonicalWindow(chunk.edges);\n        if (nonCanonicalEdge !== undefined) {\n          const { entity, field, value } = nonCanonicalEdge;\n          throw invalidStream(\n            nonCanonicalWindowMessage(\n              `${entity.kind} edge \"${entity.id}\"`,\n              field,\n              value,\n            ),\n          );\n        }\n        const invertedEdge = chunk.edges.find((edge) =>\n          hasInvertedWindow(edge),\n        );\n        if (invertedEdge !== undefined) {\n          throw invalidStream(\n            `Inverted validity window in trusted import: ${invertedEdge.kind} edge \"${invertedEdge.id}\" ends at ` +\n              `\"${String(invertedEdge.validTo)}\", before its validFrom \"${String(invertedEdge.validFrom)}\".`,\n          );\n        }\n        await session.insertEdges(\n          chunk.edges.map((edge) =>\n            edgeParams(\n              store.graphId,\n              edge,\n              store.graph.edges[edge.kind] as EdgeRegistration,\n            ),\n          ),\n        );\n        edgeCount += chunk.edges.length;\n        break;\n      }\n      case \"identity\": {\n        // The trusted session writes only the node and edge relations, so it\n        // has no way to persist assertions or materialize the derived closure.\n        // Refuse rather than drop identity truth from an identity-enabled\n        // export: `importGraph` / `importGraphStream` carry it correctly.\n        throw invalidStream(\n          \"Trusted graph interchange import does not support identity assertions. \" +\n            \"Use importGraphStream() for an export that carries identity truth.\",\n        );\n      }\n    }\n  }\n\n  if (!receivedHeader) {\n    throw invalidStream(\n      \"Trusted graph interchange stream ended before emitting a header.\",\n    );\n  }\n  return { nodes: nodeCount, edges: edgeCount };\n}\n\n/**\n * Atomically imports a header-first stream into a fresh, dedicated database.\n *\n * This is an intentionally trusted path. It checks stream ordering and kind\n * names, but it does not validate properties, references, cardinality, or\n * conflicts. The caller must guarantee those invariants. Use\n * {@link importGraphStream} for untrusted data.\n *\n * Trusted of the DATA, not of the connection: this holds ONE write transaction\n * open for the entire stream, which makes it a long-lived import holder exactly\n * like {@link importGraphStream}, and it is guarded the same way — the source\n * stream's own backend is checked against the target before the first chunk, and\n * the target connection's exclusive stream lease is held for the whole import.\n * `trustedImportGraphStream(target, exportGraphStream(source))` over one\n * serialized connection is therefore refused with the shared typed\n * {@link ConfigurationError} (codes and `details.heldBy` / `details.requested`\n * as documented on `importGraphStream`) rather than reaching the driver as a\n * nested BEGIN.\n */\nexport async function trustedImportGraphStream<G extends GraphDef>(\n  store: Store<G>,\n  chunks:\n    AsyncIterable<GraphInterchangeChunk> | Iterable<GraphInterchangeChunk>,\n): Promise<TrustedImportResult> {\n  rejectUnsupportedStoreFeatures(store);\n  const backend = storeBackend(store);\n  const trustedImport = backend.trustedImport;\n  if (trustedImport === undefined) {\n    throw new TrustedImportError(\n      `The ${backend.dialect} backend does not support trusted import.`,\n      \"backend_unsupported\",\n      { dialect: backend.dialect },\n    );\n  }\n  // The same pre-flight `importGraphStream` runs, through the same owner of\n  // \"would this export hold the connection that write needs\": a synchronous\n  // iterable was materialized by its producer and holds nothing, so only an\n  // async stream can name a source backend.\n  const sourceBackend =\n    Symbol.asyncIterator in chunks ? exportStreamBackend(chunks) : undefined;\n  const contention =\n    sourceBackend === undefined ? undefined : (\n      snapshotExportContention(sourceBackend, backend)\n    );\n  if (contention !== undefined) {\n    throw serializedStreamRefusal({\n      graphId: store.graphId,\n      requested: \"import-stream\",\n      heldBy: \"export-snapshot\",\n      detector: contention,\n    });\n  }\n  const schemaVersion = store.introspect().schemaVersion;\n  const options: TrustedImportOptions | undefined =\n    schemaVersion === undefined ? undefined : (\n      {\n        schemaWrite: {\n          graphId: store.graphId,\n          expectedVersion: schemaVersion,\n        },\n      }\n    );\n  return withImportStreamLease(store, () =>\n    trustedImport(\n      (session) => consumeTrustedChunks(store, session, chunks),\n      options,\n    ),\n  );\n}\n\nfunction* graphDataChunks(data: GraphData): Iterable<GraphInterchangeChunk> {\n  const { nodes, edges, identity, ...header } = data;\n  yield {\n    type: \"header\",\n    header:\n      identity === undefined ? header : (\n        {\n          ...header,\n          identity: { profile: identity.profile, mode: identity.mode },\n        }\n      ),\n  };\n  yield { type: \"nodes\", nodes };\n  yield { type: \"edges\", edges };\n  if (identity !== undefined) {\n    yield { type: \"identity\", assertions: identity.assertions };\n  }\n}\n\n/** In-memory convenience wrapper around {@link trustedImportGraphStream}. */\nexport function trustedImportGraph<G extends GraphDef>(\n  store: Store<G>,\n  data: GraphData,\n): Promise<TrustedImportResult> {\n  return trustedImportGraphStream(store, graphDataChunks(data));\n}\n"]}