Skip to content

graflo.link.assertions

Statements stored as the provenance aspect's Assertion vertices, and read back.

One Assertion is one :class:~graflo.link.statements.Statement, one triple (rdf:Statement):

  • Assertion -subject-> <Type>: the entity the statement is about;
  • predicate: the property or the relation stated;
  • for a property, value: the stated value as text, read back as the property's declared type; for a relation, Assertion -object-> <Type>: the target;
  • polarity, modality, valid_from / valid_to, granularity, quote, span_start / span_end and basis, as on the statement;
  • Assertion -wasDerivedFrom-> SourceRecord: the record it was read from, whose written_at is when it was said.

Whether a statement states a property or a relation follows from whether it has an object edge; the entity's type, from its subject edge. :func:statement_container writes statements in this shape and :func:read_statements reads them back, about one entity or all of them; :func:graph_time is the newest time a record was written.

Attributes

ENDS = (vocab.SUBJECT, vocab.OBJECT) module-attribute

The relations an Assertion names its subject and its object by.

__all__ = ['ENDS', 'Evidence', 'assertion_doc', 'graph_time', 'read_statements', 'stated_types', 'statement_container', 'stored_edges'] module-attribute

Classes

Evidence

Bases: ConfigBaseModel

Statements read from a graph, with the records they were read from.

Source code in graflo/link/assertions.py
class Evidence(ConfigBaseModel):
    """Statements read from a graph, with the records they were read from."""

    statements: list[Statement] = Field(default_factory=list)
    records: dict[str, dict[str, Any]] = Field(
        default_factory=dict,
        description="``SourceRecord`` documents by ``source_record_id``.",
    )
    reserved: dict[str, dict[str, Any]] = Field(
        default_factory=dict,
        description=(
            "Per statement id, the reserved fields its ``Assertion`` carries, "
            "such as the access zones it was written in."
        ),
    )

Attributes

records = Field(default_factory=dict, description='``SourceRecord`` documents by ``source_record_id``.') class-attribute instance-attribute
reserved = Field(default_factory=dict, description='Per statement id, the reserved fields its ``Assertion`` carries, such as the access zones it was written in.') class-attribute instance-attribute
statements = Field(default_factory=list) class-attribute instance-attribute

Functions:

assertion_doc(statement)

The Assertion document for one statement, without its edges.

Source code in graflo/link/assertions.py
def assertion_doc(statement: Statement) -> dict[str, Any]:
    """The ``Assertion`` document for one statement, without its edges."""
    doc: dict[str, Any] = {
        vocab.ASSERTION_ID: statement.id,
        vocab.PREDICATE: statement.slot,
        vocab.VALUE: None if statement.kind == "relation" else _text(statement.value),
        vocab.POLARITY: statement.polarity,
        vocab.MODALITY: statement.modality,
        vocab.VALID_FROM: _iso(statement.valid_from),
        vocab.VALID_TO: _iso(statement.valid_to),
        vocab.GRANULARITY: statement.granularity,
        vocab.QUOTE: statement.quote,
        vocab.SPAN_START: statement.span_start,
        vocab.SPAN_END: statement.span_end,
        vocab.BASIS: Basis(statement.basis).name.lower(),
    }
    return {k: v for k, v in doc.items() if v is not None}

graph_time(conn, schema, *, guard=None, timeout_s=None)

The graph's own time: the newest SourceRecord.written_at guard admits.

When a record was written is the world's clock; when it was read (retrieved_at) is the reader's, so a replayed or historical world resolves at its own time. None when no record has a time.

Source code in graflo/link/assertions.py
def graph_time(
    conn: Connection,
    schema: Schema,
    *,
    guard: FilterExpression | None = None,
    timeout_s: float | None = None,
) -> datetime | None:
    """The graph's own time: the newest ``SourceRecord.written_at`` *guard* admits.

    When a record was *written* is the world's clock; when it was read
    (``retrieved_at``) is the reader's, so a replayed or historical world
    resolves at its own time. ``None`` when no record has a time.
    """
    if vocab.SOURCE_RECORD not in schema.core_schema.vertex_config.vertex_set:
        return None
    newest = _Stored(conn, schema, guard).newest(
        vocab.SOURCE_RECORD, vocab.WRITTEN_AT, timeout_s=timeout_s
    )
    return _time(newest)

read_statements(conn, schema, *, about=None, guard=None, thread_field=None, limit=1000, timeout_s=None)

The statements stored in conn, with the records they were read from.

Parameters:

Name Type Description Default
conn Connection

An open connection.

required
schema Schema

The graph's logical schema, lifted with Assertion.

required
about tuple[str, Mapping[str, Any]] | None

(vertex_type, key): only the statements whose subject or object is this entity; key is a complete key, as a traversal accepts. None reads every statement.

None
guard FilterExpression | None

A trusted read guard, as :meth:Connection.traverse takes: only assertions, entities, records and edges it admits are read.

None
thread_field str | None

The SourceRecord property naming the conversation a record belongs to, where the source has one.

None
limit int

At most this many edges per traversal step of an about read.

1000
timeout_s float | None

Seconds each traversal of an about read may run.

None

Returns:

Name Type Description
Evidence Evidence

each statement with its quote, record id, said time and

Evidence

thread, the records, and the reserved fields of each assertion.

Source code in graflo/link/assertions.py
def read_statements(
    conn: Connection,
    schema: Schema,
    *,
    about: tuple[str, Mapping[str, Any]] | None = None,
    guard: FilterExpression | None = None,
    thread_field: str | None = None,
    limit: int = 1000,
    timeout_s: float | None = None,
) -> Evidence:
    """The statements stored in *conn*, with the records they were read from.

    Args:
        conn: An open connection.
        schema: The graph's logical schema, lifted with ``Assertion``.
        about: ``(vertex_type, key)``: only the statements whose subject or
            object is this entity; *key* is a complete key, as a traversal
            accepts. ``None`` reads every statement.
        guard: A trusted read guard, as :meth:`Connection.traverse` takes:
            only assertions, entities, records and edges it admits are read.
        thread_field: The ``SourceRecord`` property naming the conversation a
            record belongs to, where the source has one.
        limit: At most this many edges per traversal step of an *about* read.
        timeout_s: Seconds each traversal of an *about* read may run.

    Returns:
        Evidence: each statement with its quote, record id, said time and
        thread, the records, and the reserved fields of each assertion.
    """
    if vocab.ASSERTION not in schema.core_schema.vertex_config.vertex_set:
        return Evidence()
    decoder = _Decoder(schema, thread_field)
    if about is None:
        _read_all(conn, schema, guard, decoder)
        return decoder.evidence()
    vertex_type, key = about
    _read_about(conn, schema, vertex_type, dict(key), guard, decoder, limit, timeout_s)
    return decoder.evidence()

stated_types(schema)

The types schema lets a statement be about: each Assertion -subject-> target.

Source code in graflo/link/assertions.py
def stated_types(schema: Schema) -> frozenset[str]:
    """The types *schema* lets a statement be about: each ``Assertion -subject->`` target."""
    return frozenset(
        edge.target
        for edge in schema.core_schema.edge_config.values()
        if edge.source == vocab.ASSERTION and edge.relation == vocab.SUBJECT
    )

statement_container(schema, statements)

The Assertion documents and their edges for statements, ready to write.

Each statement gives one Assertion, its subject edge, its object edge for a relation, and its wasDerivedFrom edge when it names a record. A statement given twice is written once.

Raises:

Type Description
ValueError

schema has no Assertion, or a statement is about a type it declares no subject (or object) edge to.

Source code in graflo/link/assertions.py
def statement_container(
    schema: Schema, statements: Iterable[Statement]
) -> GraphContainer:
    """The ``Assertion`` documents and their edges for *statements*, ready to write.

    Each statement gives one ``Assertion``, its ``subject`` edge, its ``object``
    edge for a relation, and its ``wasDerivedFrom`` edge when it names a record.
    A statement given twice is written once.

    Raises:
        ValueError: *schema* has no ``Assertion``, or a statement is about a
            type it declares no ``subject`` (or ``object``) edge to.
    """
    core = schema.core_schema
    statements = list(statements)
    if not statements:
        return GraphContainer()
    if vocab.ASSERTION not in core.vertex_config.vertex_set:
        raise ValueError("the schema has no Assertion type to store statements in")
    declared = {
        (edge.target, edge.relation)
        for edge in core.edge_config.values()
        if edge.source == vocab.ASSERTION
    }
    docs: dict[str, dict[str, Any]] = {}
    edges: dict[tuple[str, str, str | None], list[Any]] = defaultdict(list)
    for statement in statements:
        if statement.id in docs:
            continue
        ends = [(vocab.SUBJECT, statement.vertex_type, statement.key)]
        if statement.kind == "relation":
            if statement.target_type is None:
                raise ValueError(f"relation statement {statement.id} names no target")
            ends.append((vocab.OBJECT, statement.target_type, str(statement.value)))
        for relation, vertex_type, _ in ends:
            if (vertex_type, relation) not in declared:
                raise ValueError(
                    f"the schema declares no Assertion -{relation}-> {vertex_type}"
                )
        docs[statement.id] = assertion_doc(statement)
        ref = {vocab.ASSERTION_ID: statement.id}
        for relation, vertex_type, key in ends:
            edges[vocab.ASSERTION, vertex_type, relation].append(
                (ref, _key_doc(key), {})
            )
        if statement.record is not None:
            edges[vocab.ASSERTION, vocab.SOURCE_RECORD, vocab.DERIVED_FROM].append(
                (ref, {vocab.SOURCE_RECORD_ID: statement.record}, {})
            )
    return GraphContainer(
        vertices={vocab.ASSERTION: list(docs.values())} if docs else {},
        edges=dict(edges),
    )

stored_edges(conn, schema, edge, *, guard=None)

Every stored edge as (source, target) identity documents, in logical names.

Source code in graflo/link/assertions.py
def stored_edges(
    conn: Connection,
    schema: Schema,
    edge: Edge,
    *,
    guard: FilterExpression | None = None,
) -> list[tuple[dict[str, Any], dict[str, Any]]]:
    """Every stored *edge* as ``(source, target)`` identity documents, in logical names."""
    return _Stored(conn, schema, guard).edges(edge)