from datetime import datetime from sqlalchemy import BigInteger, DateTime, Index, Text, func from sqlalchemy.orm import Mapped, mapped_column from grimoire.models import Base from grimoire.models.base import iso FULL = "full" REPEAT = "repeat" FORMS = (FULL, REPEAT) class RuleDelivery(Base): """One rule line put in front of one session, and whether it was opened after. WHAT IT ANSWERS that `rule_usage_events` cannot. A surfaced event and a pulled event are counted separately, so "was THIS delivery opened" has no answer there: a rule opened once in a session reads as pulled whether it was delivered once or twenty times. Here each delivery is a row, and the open is stamped on the delivery it followed — so the open rate per rule, per moment and per arm is a count of rows, and the ordering function reads it as the rule's history at that moment. `at` is where the rule was delivered: the moment it was mounted on (`work.finish`) or the arm that found it (`pre_tool_rule`). `form` is whether the line carried the rule's trigger (`full`) or only cited it (`repeat`). Repeats are recorded too: they are deliveries a session can open, and the case for retiring a rule rests on how rarely they are. FK-free on `rule_id` and `user_id`, like the other telemetry tables: the evidence that a rule was delivered forty times and opened never outlives the rule, because it is the case for having deleted it. """ __tablename__ = "rule_deliveries" id: Mapped[int] = mapped_column(BigInteger, primary_key=True) user_id: Mapped[int] = mapped_column(BigInteger, nullable=False) session_id: Mapped[str] = mapped_column(Text, nullable=False) rule_id: Mapped[int] = mapped_column(BigInteger, nullable=False) source: Mapped[str] = mapped_column(Text, nullable=False) at: Mapped[str] = mapped_column(Text, nullable=False) form: Mapped[str] = mapped_column(Text, nullable=False) delivered_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), nullable=False, server_default=func.now(), ) opened_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True) __table_args__ = ( # Stamping an open: this session's latest delivery of this rule. Index("ix_rule_deliveries_session_rule", "user_id", "session_id", "rule_id", "delivered_at"), # History: a batch of rules at one moment. Index("ix_rule_deliveries_rule_at", "rule_id", "at"), Index("ix_rule_deliveries_delivered_at", "delivered_at"), ) def to_dict(self) -> dict: return { "id": self.id, "user_id": self.user_id, "session_id": self.session_id, "rule_id": self.rule_id, "source": self.source, "at": self.at, "form": self.form, "delivered_at": iso(self.delivered_at), "opened_at": iso(self.opened_at), }