Skip to content

graflo.link.statements

Which facts hold, given what was stated about them, when, and how.

A statement says that one entity's property has a value, or that it relates to a target, as one source stated it: affirmed or denied (polarity), reported as done, intended or uncertain (modality), with the time the statement says it holds (valid_from / valid_to) and the time it was said (said_at). A slot is what holds the values: one property, or one relation from one entity.

:func:resolve turns statements into the facts that hold as_of a time:

  1. Withdrawals. A denial withdraws the affirmations of the same value said no later than it, or said in the same record or thread when either time is unknown. A denial that cannot be ordered against an affirmation is a conflict.
  2. Ordering. In a single-valued slot, of two values the one with the later stated time holds; failing stated times on both, the later said time; failing both, the stronger basis (how it was obtained), and the pair is a conflict. A missing time is unknown, never the oldest. Where no value outranks every other, the slot is a conflict and holds nothing.
  3. Modality. A planned value counts once its whole stated period has passed by as_of: the period ends one granularity unit after valid_to, or after valid_from when no end is stated (an instant, or no granularity, ends where it starts). Until then, and when as_of is not given, it is pending, so a plan is never reported done before it could have happened. A hedged statement never decides a slot; it is pending.
  4. Exclusive slots. A second value is always a conflict; the value with the strongest basis stays current when one has it.
  5. History. In a stateful slot, each value the current one replaced is kept with its interval, when both are ordered by time.

The result does not depend on the order of the statements. Which slots are single-valued, exclusive or stateful is read from a schema by :func:slot_rules. Statements are stored as the provenance aspect's Assertion vertices (:mod:graflo.link.assertions).

Attributes

Granularity = Literal['instant', 'day', 'week', 'month', 'year'] module-attribute

Modality = Literal['actual', 'planned', 'hedged'] module-attribute

Polarity = Literal['stated', 'denied'] module-attribute

SlotId = tuple[str, str] module-attribute

(vertex_type, slot): which rule applies.

SlotKind = Literal['property', 'relation'] module-attribute

__all__ = ['Basis', 'Conflict', 'Fact', 'Granularity', 'Modality', 'Polarity', 'Resolution', 'SlotKind', 'SlotRule', 'Statement', 'Withdrawal', 'entity_key', 'resolve', 'slot_rules'] module-attribute

Classes

Basis

Bases: IntEnum

How a statement was obtained, weakest first; it weighs when time does not decide.

Source code in graflo/link/statements.py
class Basis(IntEnum):
    """How a statement was obtained, weakest first; it weighs when time does not decide."""

    EXTRACTED = 0
    """Read from text by a model."""
    CONFIRMED = 1
    """Confirmed by a person."""
    RECORDED = 2
    """Recorded by a system of record."""

Attributes

CONFIRMED = 1 class-attribute instance-attribute

Confirmed by a person.

EXTRACTED = 0 class-attribute instance-attribute

Read from text by a model.

RECORDED = 2 class-attribute instance-attribute

Recorded by a system of record.

Conflict

Bases: ConfigBaseModel

Values of one slot that nothing orders, or that an exclusive slot refuses.

Source code in graflo/link/statements.py
class Conflict(ConfigBaseModel):
    """Values of one slot that nothing orders, or that an exclusive slot refuses."""

    vertex_type: str
    key: str
    slot: str
    values: list[Fact]
    reason: str

Attributes

key instance-attribute
reason instance-attribute
slot instance-attribute
values instance-attribute
vertex_type instance-attribute

Fact

Bases: ConfigBaseModel

A value a slot holds, with the statements behind it.

Source code in graflo/link/statements.py
class Fact(ConfigBaseModel):
    """A value a slot holds, with the statements behind it."""

    vertex_type: str
    key: str
    slot: str
    kind: SlotKind
    value: Any
    target_type: str | None = None
    modality: Modality = "actual"
    valid_from: datetime | None = None
    valid_to: datetime | None = None
    supports: list[str] = Field(default_factory=list)

Attributes

key instance-attribute
kind instance-attribute
modality = 'actual' class-attribute instance-attribute
slot instance-attribute
supports = Field(default_factory=list) class-attribute instance-attribute
target_type = None class-attribute instance-attribute
valid_from = None class-attribute instance-attribute
valid_to = None class-attribute instance-attribute
value instance-attribute
vertex_type instance-attribute

Resolution

Bases: ConfigBaseModel

What holds as_of, what is pending, what was replaced, withdrawn or disputed.

Source code in graflo/link/statements.py
class Resolution(ConfigBaseModel):
    """What holds ``as_of``, what is pending, what was replaced, withdrawn or disputed."""

    current: list[Fact] = Field(default_factory=list)
    pending: list[Fact] = Field(default_factory=list)
    history: list[Fact] = Field(default_factory=list)
    conflicts: list[Conflict] = Field(default_factory=list)
    withdrawn: list[Withdrawal] = Field(default_factory=list)

Attributes

conflicts = Field(default_factory=list) class-attribute instance-attribute
current = Field(default_factory=list) class-attribute instance-attribute
history = Field(default_factory=list) class-attribute instance-attribute
pending = Field(default_factory=list) class-attribute instance-attribute
withdrawn = Field(default_factory=list) class-attribute instance-attribute

SlotRule

Bases: ConfigBaseModel

How one slot holds values.

Source code in graflo/link/statements.py
class SlotRule(ConfigBaseModel):
    """How one slot holds values."""

    single: bool = False
    exclusive: bool = False
    stateful: bool = False

Attributes

exclusive = False class-attribute instance-attribute
single = False class-attribute instance-attribute
stateful = False class-attribute instance-attribute

Statement

Bases: ConfigBaseModel

One source's statement about one slot.

id left empty is minted from the record, the quote's start, the entity, the slot and the value, so re-reading the same record gives the same ids.

Source code in graflo/link/statements.py
class Statement(ConfigBaseModel):
    """One source's statement about one slot.

    ``id`` left empty is minted from the record, the quote's start, the entity,
    the slot and the value, so re-reading the same record gives the same ids.
    """

    id: str = Field(default="", description="Stable id: the stored assertion's key.")
    vertex_type: str
    key: str = Field(description="The entity's key, as :func:`entity_key` gives it.")
    slot: str = Field(description="The property, or the relation, stated.")
    kind: SlotKind = "property"
    value: Any = Field(
        description="The property value, or the relation's target key (entity_key)."
    )
    target_type: str | None = None
    polarity: Polarity = "stated"
    modality: Modality = "actual"
    valid_from: datetime | None = None
    valid_to: datetime | None = None
    granularity: Granularity | None = None
    said_at: datetime | None = Field(
        default=None, description="When the source said it: its record's time."
    )
    basis: Basis = Basis.EXTRACTED
    record: str | None = Field(default=None, description="The record it was read from.")
    thread: str | None = Field(
        default=None, description="The conversation the record belongs to."
    )
    quote: str | None = Field(default=None, description="The words it was read from.")
    span_start: int | None = None
    span_end: int | None = None

    @model_validator(mode="after")
    def _times_in_utc_and_an_id(self) -> Statement:
        for name in ("valid_from", "valid_to", "said_at"):
            value = getattr(self, name)
            if value is not None and value.tzinfo is None:
                object.__setattr__(self, name, value.replace(tzinfo=UTC))
        if not self.id:
            object.__setattr__(self, "id", _mint(self))
        return self

Attributes

basis = Basis.EXTRACTED class-attribute instance-attribute
granularity = None class-attribute instance-attribute
id = Field(default='', description="Stable id: the stored assertion's key.") class-attribute instance-attribute
key = Field(description="The entity's key, as :func:`entity_key` gives it.") class-attribute instance-attribute
kind = 'property' class-attribute instance-attribute
modality = 'actual' class-attribute instance-attribute
polarity = 'stated' class-attribute instance-attribute
quote = Field(default=None, description='The words it was read from.') class-attribute instance-attribute
record = Field(default=None, description='The record it was read from.') class-attribute instance-attribute
said_at = Field(default=None, description="When the source said it: its record's time.") class-attribute instance-attribute
slot = Field(description='The property, or the relation, stated.') class-attribute instance-attribute
span_end = None class-attribute instance-attribute
span_start = None class-attribute instance-attribute
target_type = None class-attribute instance-attribute
thread = Field(default=None, description='The conversation the record belongs to.') class-attribute instance-attribute
valid_from = None class-attribute instance-attribute
valid_to = None class-attribute instance-attribute
value = Field(description="The property value, or the relation's target key (entity_key).") class-attribute instance-attribute
vertex_type instance-attribute

Withdrawal

Bases: ConfigBaseModel

An affirmation a denial withdrew.

Source code in graflo/link/statements.py
class Withdrawal(ConfigBaseModel):
    """An affirmation a denial withdrew."""

    statement: str
    by: str

Attributes

by instance-attribute
statement instance-attribute

Functions:

entity_key(doc, fields)

An entity's key as one string: its identity fields, sorted, as JSON.

Source code in graflo/link/statements.py
def entity_key(doc: Mapping[str, Any], fields: Iterable[str]) -> str:
    """An entity's key as one string: its identity *fields*, sorted, as JSON."""
    return json.dumps({f: doc.get(f) for f in fields}, sort_keys=True, default=str)

resolve(statements, rules, *, as_of=None)

The facts that hold as_of, from statements under rules.

Parameters:

Name Type Description Default
statements Iterable[Statement]

Every statement to weigh, in any order.

required
rules Mapping[SlotId, SlotRule]

Per (vertex_type, slot), how the slot holds values; a slot left out is multi-valued.

required
as_of datetime | None

The time to resolve at, for planned values. None keeps every planned value pending.

None
Source code in graflo/link/statements.py
def resolve(
    statements: Iterable[Statement],
    rules: Mapping[SlotId, SlotRule],
    *,
    as_of: datetime | None = None,
) -> Resolution:
    """The facts that hold ``as_of``, from *statements* under *rules*.

    Args:
        statements: Every statement to weigh, in any order.
        rules: Per ``(vertex_type, slot)``, how the slot holds values; a slot
            left out is multi-valued.
        as_of: The time to resolve at, for planned values. ``None`` keeps every
            planned value pending.
    """
    if as_of is not None and as_of.tzinfo is None:
        as_of = as_of.replace(tzinfo=UTC)
    by_slot: dict[tuple[str, str, str], list[Statement]] = defaultdict(list)
    for statement in sorted(statements, key=lambda s: s.id):
        by_slot[statement.vertex_type, statement.key, statement.slot].append(statement)

    result = Resolution()
    for (vertex_type, key, slot), group in sorted(by_slot.items()):
        rule = rules.get((vertex_type, slot), SlotRule())
        _resolve_slot(group, rule, as_of, result)
    return result

slot_rules(schema)

The single-valued, exclusive and stateful slots schema declares.

A property is single-valued unless it is a LIST that merges by union, and exclusive when its match declaration says so. A relation is single-valued with merge: replace and exclusive with exclusive. Either is stateful when the type's <Type>State carries it. A slot left out is multi-valued.

Source code in graflo/link/statements.py
def slot_rules(schema: Schema) -> dict[SlotId, SlotRule]:
    """The single-valued, exclusive and stateful slots *schema* declares.

    A property is single-valued unless it is a LIST that merges by union, and
    exclusive when its match declaration says so. A relation is single-valued
    with ``merge: replace`` and exclusive with ``exclusive``. Either is stateful
    when the type's ``<Type>State`` carries it. A slot left out is multi-valued.
    """
    from graflo.architecture.evolution.aspects.state.vocabulary import (
        state_type_name,
    )

    core = schema.core_schema
    vertices = {v.name: v for v in core.vertex_config.vertices}

    def stateful(vertex_type: str, slot: str) -> bool:
        state = vertices.get(state_type_name(vertex_type))
        return state is not None and slot in state.property_names

    rules: dict[SlotId, SlotRule] = {}
    for vertex in core.vertex_config.vertices:
        for field in vertex.properties:
            many = field.type == FieldType.LIST and field.merge == "union"
            if many or field.name in vertex.identity:
                continue
            rules[vertex.name, field.name] = SlotRule(
                single=True,
                exclusive=bool(field.match and field.match.exclusive),
                stateful=stateful(vertex.name, field.name),
            )
    for edge in core.edge_config.edges:
        if edge.relation is None or edge.merge != "replace":
            continue
        rules[edge.source, edge.relation] = SlotRule(
            single=True,
            exclusive=edge.exclusive,
            stateful=stateful(edge.source, edge.relation),
        )
    return rules