563 lines
17 KiB
Python
563 lines
17 KiB
Python
"""Annotation store. One ``focus_event`` row per change, same transaction.
|
|
|
|
Rows are soft-deleted. A model label never shares a write path with a
|
|
human one: ``provenance`` is ``human`` or ``model``, and ``model`` is
|
|
required when the provenance says so.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime as dt
|
|
import uuid
|
|
from dataclasses import dataclass
|
|
from typing import Any
|
|
|
|
from sqlalchemy import (
|
|
JSON,
|
|
Column,
|
|
DateTime,
|
|
Integer,
|
|
MetaData,
|
|
String,
|
|
Table,
|
|
select,
|
|
update,
|
|
)
|
|
from sqlalchemy.dialects.postgresql import JSONB
|
|
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
|
|
from sqlalchemy.engine import Connection, Engine
|
|
from sqlalchemy.types import TypeDecorator
|
|
|
|
from focus.protocols import Protocol, load
|
|
|
|
KINDS = ("responds_to", "supports", "contradicts")
|
|
PROVENANCE = ("human", "model")
|
|
|
|
|
|
class _UuidStr(TypeDecorator):
|
|
"""UUID text in Python. Postgres binds the native ``uuid`` type.
|
|
|
|
A ``String`` column is sent as varchar. Postgres rejects that for a
|
|
``uuid`` column instead of coercing it.
|
|
"""
|
|
|
|
impl = String
|
|
cache_ok = True
|
|
|
|
def load_dialect_impl(self, dialect):
|
|
if dialect.name == "postgresql":
|
|
return dialect.type_descriptor(PG_UUID(as_uuid=False))
|
|
return dialect.type_descriptor(String())
|
|
|
|
def process_result_value(self, value, dialect):
|
|
if value is None:
|
|
return None
|
|
return str(value)
|
|
|
|
|
|
class _IsoTimestamp(TypeDecorator):
|
|
"""ISO-8601 text in Python. Postgres binds ``timestamptz``."""
|
|
|
|
impl = String
|
|
cache_ok = True
|
|
|
|
def load_dialect_impl(self, dialect):
|
|
if dialect.name == "postgresql":
|
|
return dialect.type_descriptor(DateTime(timezone=True))
|
|
return dialect.type_descriptor(String())
|
|
|
|
def process_bind_param(self, value, dialect):
|
|
if value is None or dialect.name != "postgresql":
|
|
return value
|
|
if isinstance(value, dt.datetime):
|
|
parsed = value
|
|
else:
|
|
parsed = dt.datetime.fromisoformat(value)
|
|
if parsed.tzinfo is None:
|
|
parsed = parsed.replace(tzinfo=dt.timezone.utc)
|
|
return parsed
|
|
|
|
def process_result_value(self, value, dialect):
|
|
return _iso(value)
|
|
|
|
|
|
class _JsonDoc(TypeDecorator):
|
|
"""JSON in Python. Postgres binds ``jsonb`` to match the live DDL."""
|
|
|
|
impl = JSON
|
|
cache_ok = True
|
|
|
|
def load_dialect_impl(self, dialect):
|
|
if dialect.name == "postgresql":
|
|
return dialect.type_descriptor(JSONB())
|
|
return dialect.type_descriptor(JSON())
|
|
|
|
|
|
_meta = MetaData()
|
|
|
|
annotation = Table(
|
|
"focus_annotation",
|
|
_meta,
|
|
Column("id", _UuidStr, primary_key=True),
|
|
Column("item_key", String, nullable=False),
|
|
Column("attachment", String, nullable=False),
|
|
Column("protocol", String, nullable=False),
|
|
Column("protocol_version", Integer, nullable=False),
|
|
Column("label", String, nullable=False),
|
|
Column("quote", String, nullable=False),
|
|
Column("prefix", String, nullable=False),
|
|
Column("suffix", String, nullable=False),
|
|
Column("start_char", Integer),
|
|
Column("end_char", Integer),
|
|
Column("page", Integer),
|
|
Column("rects", _JsonDoc),
|
|
Column("note", String, nullable=False),
|
|
Column("actor", String, nullable=False),
|
|
Column("provenance", String, nullable=False),
|
|
Column("model", String),
|
|
Column("created_at", _IsoTimestamp, nullable=False),
|
|
Column("deleted_at", _IsoTimestamp),
|
|
)
|
|
|
|
link_table = Table(
|
|
"focus_link",
|
|
_meta,
|
|
Column("from_id", _UuidStr, primary_key=True),
|
|
Column("to_id", _UuidStr, primary_key=True),
|
|
Column("kind", String, primary_key=True),
|
|
Column("actor", String, nullable=False),
|
|
Column("created_at", _IsoTimestamp, nullable=False),
|
|
Column("deleted_at", _IsoTimestamp),
|
|
)
|
|
|
|
event = Table(
|
|
"focus_event",
|
|
_meta,
|
|
Column("id", Integer, primary_key=True),
|
|
Column("annotation_id", _UuidStr, nullable=False),
|
|
Column("op", String, nullable=False),
|
|
Column("payload", _JsonDoc, nullable=False),
|
|
Column("actor", String, nullable=False),
|
|
Column("at", _IsoTimestamp, nullable=False),
|
|
)
|
|
|
|
|
|
class NotFound(KeyError):
|
|
"""No live row for this annotation or link."""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Annotation:
|
|
id: str
|
|
item_key: str
|
|
attachment: str
|
|
protocol: str
|
|
protocol_version: int
|
|
label: str
|
|
quote: str
|
|
prefix: str
|
|
suffix: str
|
|
start_char: int | None
|
|
end_char: int | None
|
|
page: int | None
|
|
rects: Any
|
|
note: str
|
|
actor: str
|
|
provenance: str
|
|
model: str | None
|
|
created_at: str
|
|
deleted_at: str | None
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Link:
|
|
from_id: str
|
|
to_id: str
|
|
kind: str
|
|
actor: str
|
|
created_at: str
|
|
deleted_at: str | None
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Event:
|
|
id: int
|
|
annotation_id: str
|
|
op: str
|
|
payload: dict
|
|
actor: str
|
|
at: str
|
|
|
|
|
|
def _now() -> str:
|
|
return dt.datetime.now(dt.timezone.utc).isoformat()
|
|
|
|
|
|
def _iso(value: Any) -> str | None:
|
|
"""Timestamps come back as text on SQLite and as datetime on Postgres."""
|
|
if value is None:
|
|
return None
|
|
if isinstance(value, dt.datetime):
|
|
if value.tzinfo is None:
|
|
value = value.replace(tzinfo=dt.timezone.utc)
|
|
return value.astimezone(dt.timezone.utc).isoformat()
|
|
return str(value)
|
|
|
|
|
|
def _text(value: Any, field: str, *, required: bool = False) -> str:
|
|
if value is None:
|
|
value = ""
|
|
if not isinstance(value, str):
|
|
raise ValueError(f"{field} must be a string")
|
|
if required and not value.strip():
|
|
raise ValueError(f"{field} is empty")
|
|
return value
|
|
|
|
|
|
def _opt_int(value: Any, field: str) -> int | None:
|
|
if value is None:
|
|
return None
|
|
if type(value) is not int:
|
|
raise ValueError(f"{field} must be an int")
|
|
return value
|
|
|
|
|
|
def _annotation(row: Any) -> Annotation:
|
|
m = row._mapping
|
|
return Annotation(
|
|
id=m["id"],
|
|
item_key=m["item_key"],
|
|
attachment=m["attachment"],
|
|
protocol=m["protocol"],
|
|
protocol_version=m["protocol_version"],
|
|
label=m["label"],
|
|
quote=m["quote"],
|
|
prefix=m["prefix"],
|
|
suffix=m["suffix"],
|
|
start_char=m["start_char"],
|
|
end_char=m["end_char"],
|
|
page=m["page"],
|
|
rects=m["rects"],
|
|
note=m["note"],
|
|
actor=m["actor"],
|
|
provenance=m["provenance"],
|
|
model=m["model"],
|
|
created_at=_iso(m["created_at"]) or "",
|
|
deleted_at=_iso(m["deleted_at"]),
|
|
)
|
|
|
|
|
|
def _link(row: Any) -> Link:
|
|
m = row._mapping
|
|
return Link(
|
|
from_id=m["from_id"],
|
|
to_id=m["to_id"],
|
|
kind=m["kind"],
|
|
actor=m["actor"],
|
|
created_at=_iso(m["created_at"]) or "",
|
|
deleted_at=_iso(m["deleted_at"]),
|
|
)
|
|
|
|
|
|
def _event_row(row: Any) -> Event:
|
|
m = row._mapping
|
|
return Event(
|
|
id=m["id"],
|
|
annotation_id=m["annotation_id"],
|
|
op=m["op"],
|
|
payload=m["payload"],
|
|
actor=m["actor"],
|
|
at=_iso(m["at"]) or "",
|
|
)
|
|
|
|
|
|
class Store:
|
|
def __init__(self, engine: Engine) -> None:
|
|
self.engine = engine
|
|
|
|
def add(
|
|
self,
|
|
item_key: str,
|
|
attachment: str,
|
|
protocol: str,
|
|
label: str,
|
|
quote: str,
|
|
prefix: str,
|
|
suffix: str,
|
|
start_char: int | None,
|
|
end_char: int | None,
|
|
page: int | None,
|
|
rects: Any,
|
|
note: str,
|
|
actor: str,
|
|
provenance: str = "human",
|
|
model: str | None = None,
|
|
) -> Annotation:
|
|
"""Insert one annotation and an ``add`` event."""
|
|
item_key = _text(item_key, "item_key", required=True)
|
|
actor = _text(actor, "actor", required=True)
|
|
quote = _text(quote, "quote", required=True)
|
|
proto = _require_protocol(protocol)
|
|
_require_label(proto, label)
|
|
if provenance not in PROVENANCE:
|
|
raise ValueError("provenance must be 'human' or 'model'")
|
|
if provenance == "model" and not (isinstance(model, str) and model.strip()):
|
|
raise ValueError("model provenance requires model")
|
|
if model is not None and not isinstance(model, str):
|
|
raise ValueError("model must be a string")
|
|
if rects is not None and not isinstance(rects, (list, dict)):
|
|
raise ValueError("rects must be a list, object, or null")
|
|
now = _now()
|
|
ann_id = str(uuid.uuid4())
|
|
row = {
|
|
"id": ann_id,
|
|
"item_key": item_key,
|
|
"attachment": _text(attachment, "attachment"),
|
|
"protocol": proto.name,
|
|
"protocol_version": proto.version,
|
|
"label": label,
|
|
"quote": quote,
|
|
"prefix": _text(prefix, "prefix"),
|
|
"suffix": _text(suffix, "suffix"),
|
|
"start_char": _opt_int(start_char, "start_char"),
|
|
"end_char": _opt_int(end_char, "end_char"),
|
|
"page": _opt_int(page, "page"),
|
|
"rects": rects,
|
|
"note": _text(note, "note"),
|
|
"actor": actor,
|
|
"provenance": provenance,
|
|
"model": model.strip()
|
|
if isinstance(model, str) and model.strip()
|
|
else None,
|
|
"created_at": now,
|
|
"deleted_at": None,
|
|
}
|
|
with self.engine.begin() as conn:
|
|
conn.execute(annotation.insert().values(**row))
|
|
_write_event(
|
|
conn,
|
|
ann_id,
|
|
"add",
|
|
{"label": label, "quote": quote, "provenance": provenance},
|
|
actor,
|
|
now,
|
|
)
|
|
return self._get(ann_id)
|
|
|
|
def list(
|
|
self,
|
|
item_key: str,
|
|
protocol: str | None = None,
|
|
include_deleted: bool = False,
|
|
) -> list[Annotation]:
|
|
stmt = select(annotation).where(annotation.c.item_key == item_key)
|
|
if protocol is not None:
|
|
stmt = stmt.where(annotation.c.protocol == protocol)
|
|
if not include_deleted:
|
|
stmt = stmt.where(annotation.c.deleted_at.is_(None))
|
|
stmt = stmt.order_by(annotation.c.created_at, annotation.c.id)
|
|
with self.engine.connect() as conn:
|
|
return [_annotation(row) for row in conn.execute(stmt)]
|
|
|
|
def update_note(self, ann_id: str, note: str, actor: str) -> Annotation:
|
|
actor = _text(actor, "actor", required=True)
|
|
note = _text(note, "note")
|
|
now = _now()
|
|
with self.engine.begin() as conn:
|
|
self._live(conn, ann_id)
|
|
conn.execute(
|
|
update(annotation).where(annotation.c.id == ann_id).values(note=note)
|
|
)
|
|
_write_event(conn, ann_id, "update_note", {"note": note}, actor, now)
|
|
return self._get(ann_id)
|
|
|
|
def relabel(self, ann_id: str, label: str, actor: str) -> Annotation:
|
|
actor = _text(actor, "actor", required=True)
|
|
now = _now()
|
|
with self.engine.begin() as conn:
|
|
current = self._live(conn, ann_id)
|
|
_require_label(_require_protocol(current.protocol), label)
|
|
conn.execute(
|
|
update(annotation).where(annotation.c.id == ann_id).values(label=label)
|
|
)
|
|
_write_event(
|
|
conn,
|
|
ann_id,
|
|
"relabel",
|
|
{"label": label, "previous": current.label},
|
|
actor,
|
|
now,
|
|
)
|
|
return self._get(ann_id)
|
|
|
|
def delete(self, ann_id: str, actor: str) -> Annotation:
|
|
"""Soft-delete. The row and its events stay."""
|
|
actor = _text(actor, "actor", required=True)
|
|
now = _now()
|
|
with self.engine.begin() as conn:
|
|
self._live(conn, ann_id)
|
|
conn.execute(
|
|
update(annotation)
|
|
.where(annotation.c.id == ann_id)
|
|
.values(deleted_at=now)
|
|
)
|
|
_write_event(conn, ann_id, "delete", {"deleted": True}, actor, now)
|
|
return self._get(ann_id)
|
|
|
|
def link(self, from_id: str, to_id: str, kind: str, actor: str) -> Link:
|
|
"""A live link. Linking again after an unlink clears ``deleted_at``.
|
|
The event is recorded on ``from_id``."""
|
|
actor = _text(actor, "actor", required=True)
|
|
if kind not in KINDS:
|
|
raise ValueError(f"kind must be one of {KINDS}")
|
|
if from_id == to_id:
|
|
raise ValueError("a link needs two annotations")
|
|
now = _now()
|
|
with self.engine.begin() as conn:
|
|
self._live(conn, from_id)
|
|
self._live(conn, to_id)
|
|
existing = self._link_row(conn, from_id, to_id, kind)
|
|
if existing is None:
|
|
conn.execute(
|
|
link_table.insert().values(
|
|
from_id=from_id,
|
|
to_id=to_id,
|
|
kind=kind,
|
|
actor=actor,
|
|
created_at=now,
|
|
deleted_at=None,
|
|
)
|
|
)
|
|
elif existing.deleted_at is not None:
|
|
conn.execute(
|
|
update(link_table)
|
|
.where(
|
|
link_table.c.from_id == from_id,
|
|
link_table.c.to_id == to_id,
|
|
link_table.c.kind == kind,
|
|
)
|
|
.values(deleted_at=None, actor=actor)
|
|
)
|
|
else:
|
|
return existing
|
|
_write_event(
|
|
conn,
|
|
from_id,
|
|
"link",
|
|
{"to_id": to_id, "kind": kind},
|
|
actor,
|
|
now,
|
|
)
|
|
found = self._link_row_committed(from_id, to_id, kind)
|
|
if found is None: # pragma: no cover — the row was just written
|
|
raise NotFound((from_id, to_id, kind))
|
|
return found
|
|
|
|
def unlink(self, from_id: str, to_id: str, kind: str, actor: str) -> Link:
|
|
actor = _text(actor, "actor", required=True)
|
|
if kind not in KINDS:
|
|
raise ValueError(f"kind must be one of {KINDS}")
|
|
now = _now()
|
|
with self.engine.begin() as conn:
|
|
existing = self._link_row(conn, from_id, to_id, kind)
|
|
if existing is None or existing.deleted_at is not None:
|
|
raise NotFound((from_id, to_id, kind))
|
|
conn.execute(
|
|
update(link_table)
|
|
.where(
|
|
link_table.c.from_id == from_id,
|
|
link_table.c.to_id == to_id,
|
|
link_table.c.kind == kind,
|
|
)
|
|
.values(deleted_at=now)
|
|
)
|
|
_write_event(
|
|
conn,
|
|
from_id,
|
|
"unlink",
|
|
{"to_id": to_id, "kind": kind},
|
|
actor,
|
|
now,
|
|
)
|
|
found = self._link_row_committed(from_id, to_id, kind)
|
|
if found is None: # pragma: no cover — the row was just updated
|
|
raise NotFound((from_id, to_id, kind))
|
|
return found
|
|
|
|
def history(self, annotation_id: str) -> list[Event]:
|
|
stmt = (
|
|
select(event)
|
|
.where(event.c.annotation_id == annotation_id)
|
|
.order_by(event.c.id)
|
|
)
|
|
with self.engine.connect() as conn:
|
|
self._present(conn, annotation_id)
|
|
return [_event_row(row) for row in conn.execute(stmt)]
|
|
|
|
def _get(self, ann_id: str) -> Annotation:
|
|
with self.engine.connect() as conn:
|
|
return self._present(conn, ann_id)
|
|
|
|
def _present(self, conn: Connection, ann_id: str) -> Annotation:
|
|
row = conn.execute(
|
|
select(annotation).where(annotation.c.id == ann_id)
|
|
).one_or_none()
|
|
if row is None:
|
|
raise NotFound(ann_id)
|
|
return _annotation(row)
|
|
|
|
def _live(self, conn: Connection, ann_id: str) -> Annotation:
|
|
current = self._present(conn, ann_id)
|
|
if current.deleted_at is not None:
|
|
raise NotFound(ann_id)
|
|
return current
|
|
|
|
def _link_row(
|
|
self, conn: Connection, from_id: str, to_id: str, kind: str
|
|
) -> Link | None:
|
|
row = conn.execute(
|
|
select(link_table).where(
|
|
link_table.c.from_id == from_id,
|
|
link_table.c.to_id == to_id,
|
|
link_table.c.kind == kind,
|
|
)
|
|
).one_or_none()
|
|
return _link(row) if row is not None else None
|
|
|
|
def _link_row_committed(self, from_id: str, to_id: str, kind: str) -> Link | None:
|
|
with self.engine.connect() as conn:
|
|
return self._link_row(conn, from_id, to_id, kind)
|
|
|
|
|
|
def _require_protocol(name: str) -> Protocol:
|
|
try:
|
|
return load(name)
|
|
except ValueError as exc:
|
|
if "no such protocol" in str(exc):
|
|
raise ValueError(f"unknown protocol {name!r}") from exc
|
|
raise
|
|
|
|
|
|
def _require_label(proto: Protocol, label: str) -> None:
|
|
if proto.label(label) is None:
|
|
raise ValueError(f"label {label!r} is not in {proto.name}")
|
|
|
|
|
|
def _write_event(
|
|
conn: Connection,
|
|
annotation_id: str,
|
|
op: str,
|
|
payload: dict,
|
|
actor: str,
|
|
at: str,
|
|
) -> None:
|
|
conn.execute(
|
|
event.insert().values(
|
|
annotation_id=annotation_id,
|
|
op=op,
|
|
payload=payload,
|
|
actor=actor,
|
|
at=at,
|
|
)
|
|
)
|