feat(versions): auto-pin scan promotes stable versions

_promote_stable_versions_for_note is the pure-function core: walks
versions chronologically and pins any with a >= AUTO_PIN_STABILITY_DAYS
(2-day) gap to the next version (or to now, for the latest). Auto-
generated label describes the stability window.

_scan_one_note loads versions for one note, runs the promotion, commits
mutations to the attached rows, then calls prune_auto_pins to cap the
auto bucket. scan_user_for_auto_pins fans out across the user's notes;
scan_all_users_for_auto_pins is the top-level entrypoint for the cron.
Per-note and per-user errors are caught and logged.
This commit is contained in:
2026-05-13 13:57:56 -04:00
parent bb6249e00e
commit 37c704e875
2 changed files with 285 additions and 0 deletions
@@ -90,6 +90,130 @@ async def unpin_version(
return version
def _format_auto_pin_label(
start: datetime.datetime, end: datetime.datetime | None,
) -> str:
"""Auto-generated label describing the stability window.
end=None → version is the latest with no successor; render as
"stable since {start_iso}". Otherwise render as
"stable {start_iso}{end_iso}".
"""
s = start.date().isoformat()
if end is None:
return f"stable since {s}"
return f"stable {s}{end.date().isoformat()}"
def _promote_stable_versions_for_note(versions_chrono: list) -> list:
"""Mutate the input list: set pin_kind='auto' + auto-label on any
unpinned version whose gap to its successor (or to now, for the
latest) is >= AUTO_PIN_STABILITY_DAYS.
Returns the list of versions that were newly pinned (caller uses
this for logging / counts).
"""
now = datetime.datetime.now(timezone.utc)
newly_pinned: list = []
for i, v in enumerate(versions_chrono):
if v.pin_kind is not None:
continue
if i + 1 < len(versions_chrono):
next_ts = versions_chrono[i + 1].created_at
is_latest = False
else:
next_ts = now
is_latest = True
v_ts = v.created_at
if v_ts.tzinfo is None:
v_ts = v_ts.replace(tzinfo=timezone.utc)
if next_ts.tzinfo is None:
next_ts = next_ts.replace(tzinfo=timezone.utc)
gap_days = (next_ts - v_ts).total_seconds() / 86400
if gap_days >= AUTO_PIN_STABILITY_DAYS:
v.pin_kind = "auto"
v.pin_label = _format_auto_pin_label(
v_ts, None if is_latest else next_ts,
)
newly_pinned.append(v)
return newly_pinned
async def _list_user_note_ids_with_versions(user_id: int) -> list[int]:
"""Return note_ids belonging to user_id that have at least one row in
note_versions. Notes with no version history are ignored."""
async with async_session() as session:
rows = (
await session.execute(
text(
"""
SELECT DISTINCT note_id FROM note_versions
WHERE user_id = :user_id
"""
).bindparams(user_id=user_id)
)
).all()
return [r[0] for r in rows]
async def _scan_one_note(user_id: int, note_id: int) -> int:
"""Run the promote+prune flow for one note. Returns count of newly-
pinned versions."""
async with async_session() as session:
versions = (
await session.execute(
select(NoteVersion)
.where(
NoteVersion.note_id == note_id,
NoteVersion.user_id == user_id,
)
.order_by(NoteVersion.created_at.asc())
)
).scalars().all()
if not versions:
return 0
newly_pinned = _promote_stable_versions_for_note(list(versions))
if newly_pinned:
await session.commit()
if newly_pinned:
await prune_auto_pins(user_id=user_id, note_id=note_id)
return len(newly_pinned)
async def scan_user_for_auto_pins(user_id: int) -> int:
"""Run the scan across every versioned note for one user. Returns
total newly-pinned-this-pass."""
total = 0
note_ids = await _list_user_note_ids_with_versions(user_id)
for note_id in note_ids:
try:
total += await _scan_one_note(user_id, note_id)
except Exception:
logger.exception(
"auto-pin scan failed for user=%d note=%d", user_id, note_id,
)
return total
async def scan_all_users_for_auto_pins() -> dict[int, int]:
"""Top-level scan entrypoint. Iterates over all users and runs the
per-user scan. Returns {user_id: newly_pinned_count}. Per-user errors
are caught and logged so one user's failure doesn't stop the scan."""
from fabledassistant.models import User
async with async_session() as session:
users = (await session.execute(select(User.id))).scalars().all()
out: dict[int, int] = {}
for uid in users:
try:
out[uid] = await scan_user_for_auto_pins(uid)
except Exception:
logger.exception("auto-pin scan failed for user=%d", uid)
out[uid] = 0
return out
async def prune_auto_pins(user_id: int, note_id: int) -> None:
"""FIFO-prune the auto-pinned bucket for one note past MAX_AUTO_PINS.