Skip to content

Graph Store API

GraphStore is the interface the pipeline uses to write to the graph (and to make the reads that go with the writes). It is the interface to implement for a new graph backend. The library ships two implementations: Neo4jGraphStore (scinr.newton.graph.neo4j.store), which runs the same Cypher the pipeline always had, and SqlGraphStore (scinr.newton.graph.sql.store), which serves PostgreSQL and SQLite through SQLAlchemy Core. Read-only exploration of the graph goes through Navigation, not through the store.

Obtain the process-wide store with get_graph_store(). It is a singleton chosen by graph_backend; configure() discards it, and set_graph_store() / reset_graph_store() replace or discard it (for tests and custom backends).

Rules every backend follows:

  • No engine objects (driver, session, transaction, query text) cross the interface.
  • Each method owns its sessions and transactions.
  • Retries live inside the implementation.
  • Only the exceptions of the graph hierarchy leave a method when the engine fails, with the engine's message and the original in __cause__.
  • sync_scope() shares one synchronous connection among the calls made inside the block, including the worker threads started with asyncio.to_thread.

The contract test suite that every backend must pass lives in tests/contract/. It uses only GraphStore (never query text or engine objects), runs every test once per registered backend and observes the graph through a neutral dump; tests/contract/conftest.py explains how to register a new backend. It wipes the database it runs against, so each backend refuses to run unless that is safe:

  • neo4j (with MongoDB for storage) runs only against the disposable containers of the golden harness, with SCINR_GOLDEN_ALLOW_WIPE=1, and is skipped otherwise.
  • sqlite always runs: every test uses a new database file in a temporary directory.
  • postgres runs only against the disposable postgres-test container with SCINR_SQL_ALLOW_WIPE=1 (it drops its own test schema before each test) and is skipped otherwise.

Obtaining the store

scinr.newton.graph

graph — Write-path interface to the graph (GraphStore) and its backends.

Public surface: :func:get_graph_store, :func:set_graph_store and :func:reset_graph_store. The interface itself lives in :mod:scinr.newton.graph.base, its domain types in :mod:scinr.newton.graph.types and the Neo4j implementation in :mod:scinr.newton.graph.neo4j.

Outside graph/neo4j/ and navigation/neo4j/ the library imports only this package, never the engine.

get_graph_store

get_graph_store() -> GraphStore

Return the :class:GraphStore for the active configuration's graph_backend.

One store is cached per set of connection parameters (backend, Neo4j uri / user / database, SQL url / schema), created on first use. It is synchronous to obtain and opens no connection by itself. :func:~scinr.newton.configure discards them all, so a new configuration is picked up by the next call.

Raises:

Type Description
ConfigurationError

If graph_backend is unknown.

set_graph_store

set_graph_store(store: GraphStore | None) -> None

Replace the process-wide store (for tests and custom backends).

None is equivalent to :func:reset_graph_store.

reset_graph_store

reset_graph_store() -> None

Discard every cached store and any installed one; the next :func:get_graph_store builds a new one.

Interface

scinr.newton.graph.base

graph/base.py — The :class:GraphStore interface (write path of the graph).

A GraphStore is a facade with one sub-interface per group of operations (schema, documents, annotation, extraction, tabular, deletion, gc, freeze, restore). Rules for every method:

  1. No engine objects in the signature: no driver, session, transaction, runner or query text.
  2. Each method owns its sessions and transactions. What shares a transaction today is one method.
  3. Sync or async as the code is today. S methods are synchronous (they run in worker threads), A methods are coroutines.
  4. Tenant: each method documents whether it takes the stored tenant key ("__public__" for public documents) or the API value (None = public).
  5. Retries live inside the implementation and wrap exactly what they wrap today.
  6. Semaphores stay with the caller.
  7. Only :mod:scinr.newton.exceptions errors leave a method when the engine fails (see :class:~scinr.newton.exceptions.GraphError). Errors that do not come from the engine (validation, FreezeError, errors raised by a caller's callback) pass through untouched.

Every group has its final signatures.

GcPassKind module-attribute

GcPassKind = Literal[
    "entity_model_instance", "labeled_entity"
]

The two tenant-wide collection passes of GcOps.run_pass.

AnnotationOps

Bases: ABC

Catalog, themes and the annotation of StructureNodes (all A).

Tenants are the API value (None = public) in the readers and in write_manual_annotation; write_annotation addresses StructureNodes by their composite id, which already carries the stored tenant.

catalog_sink abstractmethod

catalog_sink() -> AbstractAsyncContextManager[CatalogSink]

Open the sink that writes the model catalog and the themes (one engine session).

Used as async with store.annotation.catalog_sink() as sink; the domain traversal in :mod:scinr.newton.annotation.catalog calls it once per setup (catalog, themes). Calls are autocommit. Idempotent writes. Engine failures leave the sink methods as GraphError.

Raises:

Type Description
GraphError

If the engine fails.

count_annotated_nodes abstractmethod async

count_annotated_nodes(selector: DocumentSelector) -> int

How many StructureNodes of the latest documents selector selects carry a model decision.

Raises:

Type Description
GraphError

If the engine fails.

fetch_document_context_instructions abstractmethod async

fetch_document_context_instructions(
    *, tenant_id: str | None, doc_path: str
) -> str | None

context_instructions of the latest document at doc_path, or None.

Parameters:

Name Type Description Default
tenant_id str | None

API value (None = public).

required

Raises:

Type Description
GraphError

If the engine fails.

fetch_node_context abstractmethod async

fetch_node_context(
    full_node_id: str,
    node_id: str,
    title: str | None = None,
    role: str | None = None,
    depth: int = 0,
    max_depth: int = 3,
    visited: set[str] | None = None,
) -> dict

Context of a StructureNode: its information units and, recursively, its qualifying children.

One session serves the whole traversal. The dict has node_id, full_id, title, role, info_units, children, depth and depth_limit_reached.

Raises:

Type Description
GraphError

If the engine fails.

fetch_nodes_to_annotate abstractmethod async

fetch_nodes_to_annotate(
    *,
    tenant_id: str | None,
    doc_path: str,
    only_unannotated: bool = False,
) -> list[dict]

StructureNodes with information units of the latest document at doc_path.

Each dict has full_id, node_id, title, role, appearance_order and theme. With only_unannotated, nodes that already carry a model decision are left out.

Parameters:

Name Type Description Default
tenant_id str | None

API value (None = public).

required

Raises:

Type Description
GraphError

If the engine fails.

write_annotation abstractmethod async

write_annotation(
    full_node_id: str,
    decision: AnnotationDecision,
    document_name: str,
) -> None

Write one automatic annotation (autocommit: each statement commits on its own).

Replaces the stale decision subtree of the node; some statements are retried on transient errors.

Parameters:

Name Type Description Default
full_node_id str

Composite StructureNode id (carries the stored tenant).

required

Raises:

Type Description
RuntimeError

If the StructureNode does not exist.

GraphError

If the engine fails.

write_manual_annotation abstractmethod async

write_manual_annotation(
    document_name: str,
    matched_model_class: str,
    *,
    tenant_id: str | None,
    doc_path: str,
) -> int

Assign a manual decision to every StructureNode with information units of a document (autocommit).

Replaces each node's extraction result and decision.

Parameters:

Name Type Description Default
tenant_id str | None

API value (None = public).

required

Returns:

Type Description
int

The number of StructureNodes updated (0 if none qualifies).

Raises:

Type Description
GraphError

If the engine fails.

DeletionOps

Bases: ABC

Document deletion (all S). Tenants are the stored key; selectors carry it too.

cascade_delete abstractmethod

cascade_delete(
    tenant: str,
    keys: Sequence[dict[str, Any]],
    collector: OrphanCollector | None,
    *,
    caller: str,
) -> dict[str, int]

Delete the subtree of the documents (not the documents) in resumable batches, feeding collector (from GcOps.collector) with the nodes it can orphan. Returns the summed counters; caller is only the log prefix.

Raises:

Type Description
GraphError

If the engine fails.

delete_documents abstractmethod

delete_documents(
    tenant: str, keys: Sequence[dict[str, Any]]
) -> int

Delete the documents themselves, in batches and in the order given.

Raises:

Type Description
GraphError

If the engine fails.

fetch_document_keys abstractmethod

fetch_document_keys(
    selector: DocumentSelector,
) -> tuple[
    list[dict[str, Any]], list[DeletedDocument], bool
]

(keys, deleted_documents, interrupted) of the selected documents and their descendants: {"path", "version"} keys (descendants first), the same documents as DeletedDocument and whether an earlier delete or freeze was interrupted.

Raises:

Type Description
GraphError

If the engine fails.

fetch_existing_versions abstractmethod

fetch_existing_versions(
    selector: DocumentSelector,
) -> list[int]

Sorted versions that exist for the selected documents.

Raises:

Type Description
GraphError

If the engine fails.

fetch_raw_file_ids abstractmethod

fetch_raw_file_ids(
    selector: DocumentSelector,
) -> list[tuple[str, str | None]]

Distinct (raw_file_id, stored tenant) pairs referenced by the selected documents and their descendants.

Raises:

Type Description
GraphError

If the engine fails.

mark_deletion_pending abstractmethod

mark_deletion_pending(
    tenant: str, keys: Sequence[dict[str, Any]]
) -> None

Mark documents as half-deleted before anything is removed (in batches).

Raises:

Type Description
GraphError

If the engine fails.

DocumentOps

Bases: ABC

:Document nodes: versions, loading, replacement, leaf resolution.

Unless a method says otherwise, tenants are the stored key (utils.tenancy.tenant_key() applied, "__public__" for public documents). Selectors carry the public-API value (None = public).

apply_replacement abstractmethod

apply_replacement(
    replaces_name: str,
    new_root_doc_names: Sequence[str],
    *,
    tenant: str,
    replaced_path: str | None,
) -> None

Link the replaced document to the new root document(s). (S)

Raises:

Type Description
GraphError

If the engine fails.

count_latest_documents abstractmethod async

count_latest_documents(selector: DocumentSelector) -> int

How many latest documents selector selects. (A)

Raises:

Type Description
GraphError

If the engine fails.

create_tabular_document abstractmethod

create_tabular_document(
    *,
    document_name: str,
    doc_path: str,
    version: int,
    raw_file_id: str,
    tenant: str,
    created_by_user_id: str | None,
    job_id: str | None,
) -> None

Hierarchy, :Document, versioning and link of a tabular file, in one transaction. (S)

Raises:

Type Description
GraphError

If the engine fails.

current_latest_version abstractmethod

current_latest_version(
    path: str, tenant: str
) -> int | None

Version flagged latest for path within tenant, if any. (S)

Raises:

Type Description
GraphError

If the engine fails.

insert_document_graph abstractmethod

insert_document_graph(
    doc: Document, version: int, update_mode: bool
) -> None

Load one document in one transaction, with retry. (S)

Raises:

Type Description
DocumentVersionConflict

The version was already ingested.

GraphError

If the engine fails.

next_version abstractmethod

next_version(path: str, tenant: str) -> int

Next version number for path within tenant (1 if none). (S)

Raises:

Type Description
GraphError

If the engine fails.

preflight_replaces abstractmethod

preflight_replaces(name: str, tenant: str) -> list[dict]

{"path", "version"} of each latest document of tenant named name. (S)

Raises:

Type Description
GraphError

If the engine fails.

resolve_batch_version abstractmethod

resolve_batch_version(
    paths: Sequence[str],
    tenants: Iterable[str | None],
    update_mode: bool,
) -> int

The single version shared by every document of one run. (S)

tenants are in public-API form (None = public). paths are the leaves plus their ancestor folders.

Raises:

Type Description
GraphError

If the engine fails.

resolve_leaf_documents abstractmethod

resolve_leaf_documents(
    selector: DocumentSelector,
) -> list[LeafDocument]

Leaf documents under the roots a latest selector selects; empty if none. (S)

Raises:

Type Description
GraphError

If the engine fails.

resolve_leaf_documents_async abstractmethod async

resolve_leaf_documents_async(
    selector: DocumentSelector,
) -> list[LeafDocument]

Leaf documents under the roots a latest selector selects; empty if none. (A)

Raises:

Type Description
GraphError

If the engine fails.

ExtractionOps

Bases: ABC

Entity extraction targets and subgraphs (all A).

fetch_targets abstractmethod async

fetch_targets(
    *,
    tenant_id: str | None,
    doc_path: str,
    only_unextracted: bool = False,
) -> list[ExtractionTarget]

Extraction targets of the latest document at doc_path, in document order.

A target is a StructureNode with a model decision and at least one information unit (their order ascending); nodes of a raw tabular extraction are excluded, and so are the already extracted ones when only_unextracted is set. model_class is None for a node with no matched model (Triple fallback). Falls back to an unsorted query if the engine lacks the APOC sort function.

Parameters:

Name Type Description Default
tenant_id str | None

API value (None = public).

required

Raises:

Type Description
GraphError

If the engine fails.

mark_info_units_extracted abstractmethod async

mark_info_units_extracted(node_full_id: str) -> None

Flag as extracted (timestamp) the information units of a node that are not yet.

Idempotent.

Parameters:

Name Type Description Default
node_full_id str

Composite StructureNode id.

required

Raises:

Type Description
GraphError

If the engine fails.

sink abstractmethod

sink() -> AbstractAsyncContextManager[ExtractionSink]

Open the sink that writes an extraction subgraph (one engine session).

Used as async with store.extraction.sink() as sink by write_extraction_subgraph and write_triple_subgraph in :mod:scinr.newton.entity_extraction.graph_mapper, which walk the extracted instance and call the sink once per statement. Calls are autocommit. Engine failures leave the sink methods as GraphError.

Raises:

Type Description
GraphError

If the engine fails.

FreezeOps

Bases: ABC

Freeze and snapshot export (all S). Tenants are the stored key.

Every method may raise :class:~scinr.newton.exceptions.GraphError when the engine fails.

clear_cleanup_pending abstractmethod

clear_cleanup_pending(
    tenant: str, docs: Sequence[DocumentInfo]
) -> None

Remove the pending-cleanup marks from docs, in batches (the last step of a freeze).

Raises:

Type Description
GraphError

If the engine fails.

export_snapshot abstractmethod

export_snapshot(
    docs: Sequence[DocumentInfo],
    tenant: str,
    attempt: Callable[[ExportReader], T],
) -> T

Run attempt with a reader inside one session, retrying it whole.

A retry starts attempt again from scratch (it opens the output file inside). The reader streams: attempt must consume each iterator it asks for before asking for the next, and write as it reads. Exceptions raised by attempt that do not come from the engine pass through untouched; engine errors raised while iterating the reader are retried and translated on the way out.

Parameters:

Name Type Description Default
docs Sequence[DocumentInfo]

The documents to export (the reader is asked about each).

required
tenant str

Stored tenant key of the snapshot.

required
attempt Callable[[ExportReader], T]

Reads from the reader and writes the snapshot; its return value is returned.

required

Raises:

Type Description
GraphError

If the engine fails after the retries.

fetch_document_set abstractmethod

fetch_document_set(
    selector: DocumentSelector,
) -> list[DocumentInfo]

The selected :Document nodes and their IS_COMPOSED_OF* descendants, each once.

Parameters:

Name Type Description Default
selector DocumentSelector

Filters selector; tenant_id is the stored key.

required

Raises:

Type Description
ValueError

If the selector carries no tenant.

GraphError

If the engine fails.

mark_backup abstractmethod

mark_backup(
    tenant: str,
    docs: Sequence[DocumentInfo],
    blob_id: str,
    backup_at: str,
) -> None

Record the last backup (blob_id, backup_at) on the documents.

Raises:

Type Description
GraphError

If the engine fails.

mark_frozen abstractmethod

mark_frozen(
    tenant: str,
    docs: Sequence[DocumentInfo],
    *,
    blob_id: str,
    frozen_at: str,
    keep_flags: KeepFlags,
) -> None

Mark the stubs frozen in one transaction, before anything is deleted.

Raises:

Type Description
FreezeError

If the documents changed since they were read (one is missing or already frozen); nothing is marked.

GraphError

If the engine fails.

reduce_to_stubs abstractmethod

reduce_to_stubs(
    tenant: str,
    docs: Sequence[DocumentInfo],
    keep_flags: KeepFlags,
    collector: OrphanCollector | None,
    *,
    caller: str,
) -> dict[str, int]

Delete the subtree of docs that keep_flags do not keep, in bounded batches.

Resumable: it only deletes what is still there. collector (from GcOps.collector) is handed what the ExtractionResults about to be deleted point at. Returns the summed subtree counters.

Raises:

Type Description
GraphError

If the engine fails.

GcOps

Bases: ABC

Orphan collection (all S).

collector abstractmethod

collector(tenant: str, caller: str) -> OrphanCollector

A collector for one operation; it stores opaque handles the pipeline never inspects.

Raises:

Type Description
GraphError

If the engine fails.

run_pass abstractmethod

run_pass(
    kind: GcPassKind, tenant_id: str, caller: str
) -> tuple[int, int]

One tenant-wide pass: (nodes deleted, iterations run).

Raises:

Type Description
GraphError

If the engine fails.

sweep_tenant abstractmethod

sweep_tenant(tenant_id: str, caller: str) -> dict[str, int]

Collect every orphan of one tenant; returns the gc_* counters.

Raises:

Type Description
GraphError

If the engine fails.

GraphStore

Bases: ABC

Facade over every write-path operation of the graph.

Obtain the process-wide instance with :func:scinr.newton.graph.get_graph_store.

aclose abstractmethod async

aclose() -> None

Release the asynchronous resources the store owns.

close abstractmethod

close() -> None

Release the synchronous resources the store owns.

sync_scope abstractmethod

sync_scope() -> AbstractContextManager[None]

Share one synchronous connection among the calls made inside the block.

Worker threads started with asyncio.to_thread inside the block see the same connection; other concurrent runs do not. Without a scope, each synchronous method opens and closes its own. Scopes nest: an inner one reuses the outer connection.

OrphanCollector

Bases: Protocol

Collects the orphans one operation leaves, from its candidates.

gather() reads the candidates of a set of documents before their extraction results are deleted; chunk_done() tells the collector they are gone; collect() deletes the candidates that ended up orphaned, and then the orphans among what those pointed at, until a round deletes nothing.

The candidates are opaque handles the collector keeps (e.g. element ids in a graph database); the pipeline never inspects them. They only live in the process, so an operation that dies between deleting the extraction results and collect() loses them: its caller must leave a mark in the graph first and run GcOps.sweep_tenant instead when it finds the mark.

Each method documents Raises: :class:~scinr.newton.exceptions.GraphError.

chunk_done

chunk_done() -> None

Tell the collector the extraction results gathered so far are deleted.

collect

collect() -> None

Delete the candidates that ended up orphaned (and what they pointed at).

Raises:

Type Description
GraphError

If the engine fails.

counts

counts() -> dict[str, int]

The gc_* counters shared by DeletionResult and FreezeResult.

gather

gather(keys: Sequence[dict[str, Any]]) -> None

Read and keep the orphan candidates of the documents keys.

Raises:

Type Description
GraphError

If the engine fails.

RestoreOps

Bases: ABC

Restore from stubs or snapshots (sync methods are S). Tenants are the stored key.

Every method may raise :class:~scinr.newton.exceptions.GraphError when the engine fails.

batch_writer abstractmethod

batch_writer(concurrency: int) -> RestoreWriter

A writer shared by the stale-subtree deletion and the rebuild. (Its methods are A)

Must be called from the event loop that will use it.

Raises:

Type Description
GraphConfigurationError

If the credentials are not configured.

count_blob_references abstractmethod

count_blob_references(tenant: str, blob_id: str) -> int

How many documents of tenant still reference the snapshot blob_id.

Raises:

Type Description
GraphError

If the engine fails.

existing_documents abstractmethod

existing_documents(
    tenant: str, keys: Sequence[dict[str, Any]]
) -> list[DocumentInfo]

The :Document nodes among keys ({"path", "version"}) that exist.

Raises:

Type Description
GraphError

If the engine fails.

finish_restore abstractmethod

finish_restore(
    tenant: str,
    docs: Sequence[DocumentInfo],
    recreated_paths: Sequence[str],
) -> None

Drop the temporary links and unmark the stubs, in bounded batches, then recompute latest for recreated_paths.

Raises:

Type Description
GraphError

If the engine fails.

frozen_stubs_of_blob abstractmethod

frozen_stubs_of_blob(
    tenant: str, blob_id: str
) -> list[DocumentInfo]

The documents of tenant frozen with the snapshot blob_id.

Raises:

Type Description
GraphError

If the engine fails.

has_stale_extraction_results abstractmethod

has_stale_extraction_results(
    node_id_groups: Iterable[Sequence[str]],
) -> bool

Whether any of the StructureNodes (one id list per snapshot entry) still carries an ExtractionResult the restore is about to delete.

Raises:

Type Description
GraphError

If the engine fails.

RestoreWriter

Bases: Protocol

Batch writer of a restore (see RestoreOps.batch_writer).

lane and the writer's concurrency are suggestions a backend may ignore. The contract: drain() waits for everything submitted and re-raises the first error, and two batches of the same lane never run at once. Every method may raise :class:~scinr.newton.exceptions.GraphError.

abort async

abort() -> None

Cancel every batch in flight.

Raises:

Type Description
GraphError

If the engine fails.

create_relationships async

create_relationships(
    lane: Hashable,
    group: tuple[str, str, str],
    rows: Sequence[dict[str, Any]],
    on_done: Callable[[RestoreCounters], None],
) -> None

Create a batch of relationships of group (type, source label, target label) unless an identical one exists; each row is {"from", "to", "props"} (business keys).

Raises:

Type Description
GraphError

If the engine fails.

delete_stale async

delete_stale(
    lane: Hashable,
    node_ids: Sequence[str],
    *,
    model_decisions: bool,
    extraction_results: bool,
) -> None

Delete the stale ModelDecision / ExtractionResult subtrees hanging from StructureNodes.

Raises:

Type Description
GraphError

If the engine fails.

drain async

drain() -> None

Wait for every batch in flight and re-raise the first failure.

Raises:

Type Description
GraphError

If the engine fails.

merge_nodes async

merge_nodes(
    lane: Hashable,
    labels: tuple[str, ...],
    rows: Sequence[dict[str, Any]],
    on_done: Callable[[RestoreCounters], None],
) -> None

Merge a batch of nodes sharing labels; each row is {"key", "props"}.

Raises:

Type Description
GraphError

If the engine fails.

SchemaOps

Bases: ABC

Constraints and indexes.

ensure_indexes abstractmethod

ensure_indexes(names: Iterable[str]) -> int

Create the named indexes if they are missing, waiting until they are online. (S)

Best effort: a failure to create them is logged, not raised.

Returns:

Type Description
int

The number of indexes created.

Raises:

Type Description
ValueError

If a name is not a known index.

GraphConfigurationError

If the credentials are not configured.

setup abstractmethod

setup() -> None

Create the constraints and indexes (idempotent), checking the engine's minimum version. (S)

Raises:

Type Description
ConfigurationError

If the engine is older than the minimum version.

GraphConfigurationError

If the credentials are not configured.

GraphError

If the engine fails.

TabularOps

Bases: ABC

Tabular subgraphs (all A).

delete_tabular_subgraph abstractmethod async

delete_tabular_subgraph(
    doc_path: str,
    resolved_version: int,
    sheet_index: int,
    *,
    tenant_id: str,
) -> None

Delete the Table of one sheet and its Row descendants (explicit transaction).

Parameters:

Name Type Description Default
doc_path str

Path of the owning document.

required
resolved_version int

Document version the table belongs to.

required
sheet_index int

Index of the sheet whose table is deleted.

required
tenant_id str

Stored tenant key of the owning :Document; it prefixes the Table id, so only that tenant's table is touched.

required

Raises:

Type Description
GraphError

If the engine fails.

sink abstractmethod

sink() -> AbstractAsyncContextManager[TabularSink]

Open the sink that writes a sheet's Table and Rows.

Used as async with store.tabular.sink() as sink by write_tabular_subgraph in :mod:scinr.newton.tabular.graph_writer, which walks the sheet and calls the sink once per statement. Engine failures leave the sink methods as GraphError.

Raises:

Type Description
GraphError

If the engine fails.

Sinks

A sink is the write side of a traversal that lives in the domain code: the domain walks the Pydantic models and calls one sink method per statement. A sink is one engine session, opened as an asynchronous context manager by the store. store.annotation.catalog_sink() returns the CatalogSink that ensure_catalog_models and ensure_theme_structure (scinr.newton.annotation.catalog) write through; a backend implements those eleven methods and does not need to reimplement the model traversal. store.extraction.sink() returns the ExtractionSink that write_extraction_subgraph and write_triple_subgraph (scinr.newton.entity_extraction.graph_mapper) write through: the traversal of the extracted instance (uids, timestamp, entity registry, which fields are written) is domain code, and a backend implements the seventeen statement-level methods. store.tabular.sink() returns the TabularSink that write_tabular_subgraph (scinr.newton.tabular.graph_writer) writes through: the sheet traversal (batches of rows, normalization passes, per-row extraction) is domain code, and a backend implements four methods (create_table, write_row_batch, replace_raw_extraction_result, link_raw_column_value). This sink opens its own session per call instead of sharing one.

scinr.newton.graph.sinks

graph/sinks.py — Protocols of the use-case sinks (work package 8).

A sink is the write side of one traversal that lives in the domain code: the domain walks the Pydantic model (or the rows) and calls one sink method per statement it emits today. The three sinks are::

ExtractionSink   entity extraction and triples (``entity_extraction/graph_mapper.py``)
TabularSink      tabular subgraphs (``tabular/graph_writer.py``)
CatalogSink      catalog models and themes (``annotation/catalog.py``)

Work package 8 fills the protocols one at a time (one method per query of today, in the order of emission). CatalogSink is done and returned by store.annotation.catalog_sink(); ExtractionSink is done and returned by store.extraction.sink(); TabularSink is done and returned by store.tabular.sink().

CatalogSink

Bases: Protocol

Write side of the catalog and theme setup (annotation/catalog.py).

One sink is one engine session: every call is written on its own (autocommit) and the sink keeps nothing between calls. The domain emits in this order (each loop walks the models and their fields in the same order as before):

  • catalog: merge_catalog_model per model, merge_model_field per field, merge_aggregates per model reference, set_field_metadata per annotated field, one ensure_instance_key_indexes, link_produces_entity, merge_field_relationship and merge_instance_relationship;
  • themes: merge_theme per theme, link_subtopic per nested theme, link_model_to_theme per model of each theme.

Relationship types reaching merge_field_relationship and merge_instance_relationship are already validated by the domain ([A-Z][A-Z0-9_]*). Engine failures leave as :class:~scinr.newton.exceptions.GraphError, except ensure_instance_key_indexes, which is best effort.

ensure_instance_key_indexes async

ensure_instance_key_indexes(props: Collection[str]) -> None

Create one (tenant_id, <prop>) index per property, in alphabetical order.

Best effort: a failed index is logged and does not raise.

link_model_to_theme(model_name: str, path: str) -> None

Link a CatalogModel to its theme (BELONGS_TO_THEME).

link_produces_entity(
    model_name: str, field_name: str, entity_label: str
) -> None

Link the model to the EntityLabel its field produces.

link_subtopic(parent_path: str, child_path: str) -> None

Link a theme to its nested theme (HAS_SUBTOPIC).

merge_aggregates async

merge_aggregates(
    src_name: str,
    tgt_name: str,
    field_name: str,
    is_list: bool,
    required: bool,
) -> None

Link two CatalogModel nodes where a field of src_name references tgt_name.

merge_catalog_model async

merge_catalog_model(
    name: str, description: str, selectable: bool
) -> None

Create or update the CatalogModel called name.

merge_field_relationship async

merge_field_relationship(
    rel_type: str,
    source_label: str,
    target_label: str,
    via_model: str,
    from_field: str,
    to_field: str,
) -> None

Link two EntityLabel nodes with a relationship of type rel_type.

merge_instance_relationship async

merge_instance_relationship(
    rel_type: str,
    src_name: str,
    tgt_name: str,
    via_field: str,
    join_via_json: str,
    is_composite: bool,
) -> None

Link two CatalogModel nodes with a relationship of type rel_type.

merge_model_field async

merge_model_field(
    model_name: str,
    field_name: str,
    field_type: str,
    description: str,
    required: bool,
) -> None

Create the ModelField and link it to its model (HAS_FIELD).

merge_theme async

merge_theme(path: str, name: str) -> None

Create or update the Theme at path.

set_field_metadata async

set_field_metadata(
    model_name: str,
    field_name: str,
    is_instance_key: bool,
    entity_label: str | None,
) -> None

Record on the ModelField whether it is an instance key and its entity label.

ExtractionSink

Bases: Protocol

Write side of write_extraction_subgraph / write_triple_subgraph.

One sink is one engine session; every call is one autocommit statement of the writers of today. The domain (entity_extraction/graph_mapper.py) emits, for a model extraction: read_node_provenance, delete_stale_extraction_result, create_extraction_result, link_catalog_model (primary, then one per complementary model), then the fields of each instance (merge_keyed_instance / create_instance for sub-models, merge_labeled_entity + link_reference for entity fields, at the end of each instance merge_instance_shell + link_instance_relationship per target and set_instance_properties) and, last, link_field_relationship. For a triple extraction: read_node_provenance, delete_triple_extraction_result, create_triple_extraction_result and, per complete triple, merge_entity (subject, object), link_triple_entity (subject, object) and merge_predicate.

parent_label is "ExtractionResult" or "ModelInstance" (checked again by the backend). list_index is None outside lists and picks the variant of the statement with the index. Relationship types are already validated by the domain. Engine failures leave as :class:~scinr.newton.exceptions.GraphError.

create_extraction_result async

create_extraction_result(
    node_full_id: str,
    uid: str,
    document_name: str,
    model_class: str,
    timestamp: str,
    prov: Provenance,
) -> None

Create the ExtractionResult of a model extraction and link it to the node.

create_instance async

create_instance(
    parent_label: str,
    parent_uid: str,
    rel_name: str,
    child_uid: str,
    model_class: str,
    prov: Provenance,
    list_index: int | None,
) -> None

Create a keyless ModelInstance and link it to its parent.

create_triple_extraction_result async

create_triple_extraction_result(
    node_full_id: str,
    uid: str,
    document_name: str,
    timestamp: str,
    prov: Provenance,
) -> None

Create the ExtractionResult of a triple extraction and link it to the node.

delete_stale_extraction_result async

delete_stale_extraction_result(node_full_id: str) -> None

Delete the node's ExtractionResult with every ModelInstance reachable from it.

delete_triple_extraction_result async

delete_triple_extraction_result(node_full_id: str) -> None

Delete the node's ExtractionResult (the ModelInstance nodes are not purged).

link_catalog_model(
    er_uid: str, name: str, *, primary: bool
) -> None

Link the ExtractionResult to a CatalogModel (primary or complementary).

Retried on transient errors.

link_field_relationship(
    src_uid: str, tgt_uid: str, rel_type: str
) -> None

Link two LabeledEntity nodes through a declared field relationship.

link_instance_relationship(
    src_label: str,
    src_uid: str,
    tgt_uid: str,
    rel_type: str,
) -> None

Link two ModelInstance nodes. Retried on transient errors.

link_reference(
    parent_label: str,
    parent_uid: str,
    le_uid: str,
    field_name: str,
    list_index: int | None,
) -> None

Link a parent to a LabeledEntity through the field that holds the value.

link_triple_entity(
    er_uid: str,
    entity_uid: str,
    role: Literal["subject", "object"],
) -> None

Link the ExtractionResult to an Entity with the given role.

merge_entity async

merge_entity(
    uid: str,
    value: str,
    normalized_value: str,
    prov: Provenance,
) -> None

Merge an Entity. Retried on transient errors.

merge_instance_shell async

merge_instance_shell(
    tgt_uid: str,
    model_class: str,
    key_fields: dict[str, str],
    prov: Provenance,
) -> None

Merge the target ModelInstance of an instance relationship. Retried on transient errors.

merge_keyed_instance async

merge_keyed_instance(
    parent_label: str,
    parent_uid: str,
    rel_name: str,
    child_uid: str,
    model_class: str,
    key_fields: dict[str, str],
    prov: Provenance,
    list_index: int | None,
) -> None

Merge the ModelInstance identified by its key and link it to its parent.

merge_labeled_entity async

merge_labeled_entity(
    uid: str,
    label: str,
    value: str,
    normalized_value: str,
    prov: Provenance,
) -> None

Merge a LabeledEntity. Retried on transient errors.

merge_predicate async

merge_predicate(
    subj_uid: str,
    obj_uid: str,
    rel_type: str,
    predicate_raw: str,
) -> None

Link the subject and object Entity nodes with the predicate relationship.

read_node_provenance async

read_node_provenance(
    node_full_id: str,
) -> RawProvenance | None

Provenance stored on the StructureNode, or None if it does not exist.

set_instance_properties async

set_instance_properties(
    parent_label: str,
    parent_uid: str,
    props: dict[str, Any],
) -> None

Set the scalar properties of a parent node, in the order of props.

TabularSink

Bases: Protocol

Write side of write_tabular_subgraph (tabular/graph_writer.py).

Unlike the other sinks it holds no session: each method opens the session (and transaction) the writer of today used for the same statement. The domain emits, per sheet: create_table; per batch of rows write_row_batch (the batch is written and dropped: the sink keeps nothing between calls); then, per row of the batch and under a local concurrency bound, either the extraction-subgraph writer of the domain (rows with a model) or replace_raw_extraction_result followed by one link_raw_column_value per non-empty column (rows without a model). Relationship types are already sanitized by the domain. Engine failures leave as :class:~scinr.newton.exceptions.GraphError.

create_table async

create_table(table: TableNode) -> None

Create the Table node under the tenant's Document (explicit transaction).

table.doc_key is (tenant_id, path, version) of the owning Document.

Raises:

Type Description
RuntimeError

If the Document does not exist (the transaction is rolled back).

link_raw_column_value(
    er_uid: str,
    rel_type: str,
    entity_uid: str,
    value: str,
    normalized_value: str,
    provenance: Provenance,
) -> None

Merge the Entity of a column value and link the ExtractionResult to it.

Autocommit, own session; retried on transient errors.

replace_raw_extraction_result async

replace_raw_extraction_result(
    row_id: str,
    extraction_uid: str,
    document_name: str,
    timestamp: str,
) -> Provenance | None

Replace the Row's ExtractionResult by a fresh GenericTabularRow one.

Autocommit, one session for its two statements. Returns the Row's validated provenance, or None (nothing created) if the Row does not exist.

write_row_batch async

write_row_batch(
    table_id: str,
    rows: list[RowData],
    md_uid: str,
    theme: str,
    page_id: str,
) -> None

Create the Row nodes, their InfoUnit and their link to the ModelDecision.

One explicit transaction in its own session.

SQL implementation

SqlGraphStore has the same nine operation groups as Neo4jGraphStore, written in SQLAlchemy Core against the tables created by the migrations in scinr.newton.sql. It uses the process-wide engines of scinr.newton.sql.engine and is selected with graph_backend="postgres" or "sqlite" plus sql_url. Driver errors are translated to the same graph exceptions by scinr.newton.sql.errors. See the SQL graph backends guide.

scinr.newton.graph.sql.store

graph/sql/store.py — :class:SqlGraphStore (Postgres and SQLite).

The same nine operation groups as :class:~scinr.newton.graph.neo4j.store.Neo4jGraphStore, translated to SQLAlchemy Core over the schema of sql/migrations. The engines are the process-wide ones of :mod:scinr.newton.sql.engine.

SqlGraphStore

Bases: GraphStore

:class:GraphStore over SQL; replicates the behaviour of the Neo4j store.

aclose async

aclose() -> None

Dispose both engines; the next call creates new ones.

close

close() -> None

Dispose the pool of the synchronous engine of the active configuration, if any.

sync_scope

sync_scope() -> AbstractContextManager[None]

A no-op scope: the SQLAlchemy Engine is already a thread-safe pool, so the synchronous methods share it without a connection of their own.

Types

scinr.newton.graph.types

graph/types.py — Domain types that cross the :class:~scinr.newton.graph.base.GraphStore interface.

Nothing here depends on a graph engine. The types that already exist elsewhere (DocumentInfo, LeafDocument, ExtractionTarget, KeepFlags) move here in the work package that first needs them across the interface; the module they come from re-exports them.

DELETE_BATCH_ROWS module-attribute

DELETE_BATCH_ROWS = 1000

Nodes deleted per write transaction (deletion, GC, freeze, restore).

DOCUMENTS_PER_QUERY module-attribute

DOCUMENTS_PER_QUERY = 50

Documents whose subtree one query walks.

GC_FLUSH_CANDIDATES module-attribute

GC_FLUSH_CANDIDATES = 100000

Candidates an orphan collector holds before it collects them.

Bounds the memory of the client on a large operation. Collecting early is safe: a node still reachable from an :ExtractionResult not deleted yet is left alone, and is a candidate again when that one goes.

GC_MAX_PASSES module-attribute

GC_MAX_PASSES = 7

Maximum number of iterations the tenant-wide orphan sweep runs for each pass.

GC_REACHABILITY_MAX_HOPS module-attribute

GC_REACHABILITY_MAX_HOPS = 7

Hop bound of the "still reachable from an :ExtractionResult" check.

Not to be confused with :data:GC_MAX_PASSES. The same bound limits what export_document_snapshot() archives from each :ExtractionResult, so that export, GC and keep_extraction_results agree on what hangs from one.

DocumentInfo dataclass

One :Document of a resolved freeze / restore set (matched or descendant).

cleanup_pending property

cleanup_pending: bool

Marked frozen by a freeze that did not get to delete the whole subtree.

keep_flags property

keep_flags: KeepFlags

The keep_* flags the stub was frozen with.

DocumentSelector dataclass

Which :Document nodes an operation targets.

A single class for the two selection styles of the pipeline:

  • Filters (delete / freeze / restore): tenant_id (the stored tenant key, never None; "__public__" selects public documents) plus any of path, version, job_id and created_by_user_id. Only the fields that are set restrict the selection. job_id and created_by_user_id accept one value or several (any-of).
  • Latest (annotation / extraction): latest=True selects the latest version of the document at path, or, when only document_name is given, of every document with that name. tenant_id is None for the public documents.

The domain code builds the selector; each backend translates it to its own query language.

ExportReader

Bases: Protocol

Read side of a snapshot export, valid inside one export_snapshot attempt.

Each method streams: callers iterate it once and must not assume the backend materialised the result.

document_relationships

document_relationships(
    doc: Any,
) -> Iterator[RawRelationship]

Relationships that leave the :Document node of doc.

subtree_nodes

subtree_nodes(doc: Any) -> Iterator[RawNode]

Nodes of the subtree of doc (a DocumentInfo).

subtree_relationships

subtree_relationships(
    doc: Any,
) -> Iterator[RawRelationship]

Relationships inside the subtree of doc.

LeafDocument

Bases: NamedTuple

A leaf document to process: its display name and its path (the selector, together with the tenant, of its latest :Document).

Provenance dataclass

Validated provenance copied onto the nodes an extraction writes.

tenant_id is the stored value, already validated.

RawNode dataclass

A node as read for a snapshot export: its labels and properties.

RawProvenance dataclass

Provenance of a StructureNode exactly as stored (tenant_id may be None).

RawRelationship dataclass

A relationship as read for a snapshot export.

The ends are identified by their labels and business key, never by an engine-internal id.

RestoreCounters dataclass

What a restore batch created (the engine's write counters).

RowData dataclass

Fields of a :Row node written by the tabular sink.

TableNode dataclass

Fields of a :Table node written by the tabular sink.

doc_key is (tenant_id, path, version) of the owning :Document (the stored tenant key).