A rule the session already read counts as opened when it arrives again #229

Merged
bvandeusen merged 2 commits from dev into main 2026-11-24 07:24:33 -05:00
4 changed files with 107 additions and 2 deletions
@@ -0,0 +1,48 @@
"""a delivery of a rule the session had already opened counts as opened
Revision ID: 0135
Revises: 0134
Create Date: 2026-11-24
From now on a line for a rule the session has opened in the last six hours
is stamped opened as it is written (`rule_deliveries._read_already`). This
stamps the deliveries already recorded the same way, so the open rates, the
adherence readout and the weighing pass read one definition across old and
new rows: a rule read early in a session is not counted unread each time it
arrives again. The stamp is the delivery's own time. Only rows that carry a
plugin version are touched: every reader skips the others
(`rule_deliveries.REPORTS_OPENS`), and they are most of the table, so the
lookup runs on the few rows recorded since 0133 rather than on all of them.
Not reversible: the downgrade leaves the stamps, which the earlier code reads
as ordinary opens.
"""
from alembic import op
revision = "0135"
down_revision = "0134"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.execute(
"""
UPDATE rule_deliveries d
SET opened_at = d.delivered_at
WHERE d.opened_at IS NULL
AND d.plugin IS NOT NULL
AND EXISTS (
SELECT 1 FROM rule_deliveries e
WHERE e.user_id = d.user_id
AND e.session_id = d.session_id
AND e.rule_id = d.rule_id
AND e.opened_at IS NOT NULL
AND e.opened_at <= d.delivered_at
AND e.opened_at >= d.delivered_at - INTERVAL '6 hours'
)
"""
)
def downgrade() -> None:
pass
+3 -1
View File
@@ -20,7 +20,9 @@ class RuleDelivery(Base):
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.
it as the rule's history at that moment. A delivery made to a session that
had already opened the rule is stamped as it is written, with its own
time: it reached a reader who had the rule.
`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
+31 -1
View File
@@ -9,7 +9,9 @@ Three calls, one table (`rule_deliveries`):
that made it into the payload (`hook_payload.fit`).
- `mark_opened` — the session opened a rule: the latest unopened delivery of
it in that session gets the stamp. An open with no delivery behind it (the
agent looked a rule up unprompted) stamps nothing.
agent looked a rule up unprompted) stamps nothing. A line for a rule the
session has already opened is stamped as it is written: it reached a
reader who has the rule.
- `history` — for the ordering function: each rule's smoothed open rate at
the place it is about to be delivered, over the last `HISTORY_DAYS`.
@@ -124,11 +126,39 @@ def record(
async def _insert(rows: list[dict]) -> None:
now = datetime.now(timezone.utc)
async with async_session() as session:
read = await _read_already(session, rows, now)
for row in rows:
if (row["user_id"], row["session_id"], row["rule_id"]) in read:
row["opened_at"] = now
session.add_all(RuleDelivery(**row) for row in rows)
await session.commit()
async def _read_already(session, rows: list[dict], now: datetime) -> set:
"""`{(user_id, session_id, rule_id)}` among these rows that the session
opened within `OPEN_WINDOW` before now.
A line for a rule the session has already read is delivered to a reader
who has it, so it is stamped opened as it is written: the open rate, the
adherence readout and the weighing pass all read "opened" as "the session
had this rule", and a rule read early in a long session is no less read
when it arrives again later. Older opens do not count, for the reason
`OPEN_WINDOW` gives.
"""
keys = {(r["user_id"], r["session_id"], r["rule_id"]) for r in rows}
found = await session.execute(
select(RuleDelivery.user_id, RuleDelivery.session_id, RuleDelivery.rule_id)
.where(
tuple_(RuleDelivery.user_id, RuleDelivery.session_id, RuleDelivery.rule_id).in_(list(keys)),
RuleDelivery.opened_at >= now - OPEN_WINDOW,
)
.distinct()
)
return {tuple(k) for k in found.all()}
async def mark_opened(user_id: int, session_id: str | None, rule_id: int) -> bool:
"""Stamp the latest unopened delivery of this rule in this session.
+25
View File
@@ -68,6 +68,31 @@ async def test_an_open_is_stamped_on_the_sessions_latest_delivery_only():
assert await rule_deliveries.mark_opened(uid, "s-1", RULE) is False
async def test_a_line_for_a_rule_the_session_already_read_is_recorded_opened():
uid = await _user()
await _record(uid, "s-1", "moment_rule", [(RULE, "work.start", "full"), (OTHER, "work.start", "full")])
assert await rule_deliveries.mark_opened(uid, "s-1", RULE) is True
await _record(uid, "s-1", "pre_tool_rule", [(RULE, "pre_tool_rule", "repeat"), (OTHER, "pre_tool_rule", "full")])
await _record(uid, "s-2", "pre_tool_rule", [(RULE, "pre_tool_rule", "full")])
later = {(r.session_id, r.rule_id): r.opened_at is not None
for r in await _rows(uid) if r.at == "pre_tool_rule"}
# Read in s-1, so it reached a reader who had it; OTHER was never read,
# and another session's read is not this one's.
assert later == {("s-1", RULE): True, ("s-1", OTHER): False, ("s-2", RULE): False}
async def test_a_read_older_than_the_open_window_does_not_carry():
uid = await _user()
await _record(uid, "s-1", "moment_rule", [(RULE, "work.start", "full")])
async with async_session() as s:
await s.execute(update(RuleDelivery).where(RuleDelivery.user_id == uid).values(
opened_at=datetime.now(timezone.utc) - rule_deliveries.OPEN_WINDOW - timedelta(minutes=1)))
await s.commit()
await _record(uid, "s-1", "moment_rule", [(RULE, "work.deliver", "full")])
latest = (await _rows(uid))[-1]
assert (latest.at, latest.opened_at) == ("work.deliver", None)
async def test_an_open_with_no_delivery_behind_it_stamps_nothing():
uid = await _user()
assert await rule_deliveries.mark_opened(uid, "s-1", OTHER) is False