Skip to content

fix(atlas): trash genuinely-archived events, stagger the import clock - #608

Merged
Ardnived merged 15 commits into
mainfrom
fix/atlas-archived-events-and-clock
Aug 3, 2026
Merged

Ardnived merged 15 commits into
mainfrom
fix/atlas-archived-events-and-clock

Conversation

@Ardnived

@Ardnived Ardnived commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Stacked PR — based on feat/finished-events-off-feeds (#604), not main. Review the two commits here; #604's diff is separate.

Summary

  • Two events Atlas had genuinely archived were importing as live, published documents — they now land in the trash.
  • All 417 imported events fell due within 2 days of each other; the imported verification clock is now staggered deterministically, spreading them over a month.
  • Fixes a latent duplication bug in the seed importers: soft-deleted rows were invisible to the existence cache, so every re-seed re-created them. Already live for Files/Images, which CleanupOrphanedMedia trashes.
  • Closes the gap feat(events): keep finished events published but off the public feeds #603 opened: extending a finished event's schedule put it back on the public map while leaving it stuck at verificationStage: 'finished', never re-verified.

The finding behind all of this

Atlas's status is the only authoritative current-state flag. Atlas stamped expired_at / archived_at / finished_at on transition but never cleared them on reactivation, so they're stale on almost every row:

status expired current archived current finished current count
0 no no no 419
6 no no yes 90
6 yes yes yes 2

("current" = not superseded by a later verified_at.) 287 of 289 rows with archived_at and 295 of 297 with expired_at were re-verified afterwards. So mapStatusToStage is correct as written and unchanged — including for the 12 events with a finished_at but status: 0, every one of which was reactivated. A test pins that, because deriving state from those timestamps is the trap here.

Changes

  • seeds/atlas/helpers/verification.ts — isCurrentLifecycleFlag (checks a timestamp against verified_at), importDeletedAt (a still-current archived_at → deletedAt), importCheckOffsetDays (the stagger).
  • seeds/atlas/import.ts — passes legacyId + deletedAt.
  • seeds/lib/BaseImporter.ts — trash: true on the preload find.
  • src/collections/Events/hooks/verifyOnSave.ts — revivesFinishedEvent guard.

Why the stagger is shaped this way

cadence + (legacyId % cadence) days:

  • Deterministic, keyed off legacyId — Math.random() would reshuffle all 417 due dates on every --update run. Verified: a second run reproduced the identical spread.
  • Forward-only — the jitter is added on top of the full cadence, so no event is ever due sooner than it would have been. Spreading within the cadence would shorten some leases to days, the opposite of the intent.

Why no ladder derivation

Atlas's should_update_status_at is preserved in legacyData and would let the importer place each event at its true ladder position — but the dump is a 2024-10-13 snapshot, so every non-finished event is 13–25 months overdue and a faithful simulation would push all 419 past the trash threshold, emptying the map. Each event keeps a full lease and re-expires through the live machinery instead. Recorded in MIGRATION_PLAN.md.

Test Results

  • Lint ✓ · Typecheck ✓ · Unit 907 passed (82 files) · Integration 78 passed across 6 specs
  • New: 21 unit cases in atlas-verification.spec.ts, tests/int/seed-importer-preload.int.spec.ts, 4 revival cases in event-verification.int.spec.ts

Both behavioural fixes are mutation-checked (each flipped once to confirm the test fails):

  • Restoring verifyOnSave's blanket finished bail-out → 2 revival tests fail.
  • Dropping trash: true from the preload → 2 preload tests fail.

Verified live against the local DB (pnpm seed atlas --update, twice):

check result
legacyId 75 / 199 deletedAt = 2022-09-14 / 2023-05-08 — exactly their archived_at
total events 509, unchanged
duplicate legacy_ids after a 2nd run 0 (this is the preload fix; without it the trashed pair is re-created)
due-date spread 2 days → 31 days, peak 208/day → 20/day, avg 13.5/day
determinism 2nd run reproduced the identical 28 Aug – 29 Sep window

Notes for reviewer

The onboarding window is ~4–8 weeks, not a quarter. The stagger is bounded by the manager's event_verification cadence, and all 328 managers are on Monthly (30 days) — the 90-day default is unused. So the real window is 30–59 days (28 Aug – 29 Sep locally). The burst is 10× flatter, but if a month isn't enough runway for 328 managers, the lever is the cadence setting or a deliberate multiplier on the imported lease — a policy call, so it's flagged rather than changed here.

Timing matters on production. Whenever the production --update re-seed runs is what sets the real window, since the clock is stamped from run time. Worth doing deliberately when onboarding starts, not incidentally.

Behaviour change from the preload fix: a deliberately-trashed doc is no longer re-created by a re-seed — it's skipped, or updated in --update mode. Permanently delete it to force recreation. That's the safer default; the alternative is silently accumulating duplicates.

Payload behaviours verified in source (both easy to get wrong):

  1. payload.delete is always a hard delete, even on a trash: true collection — deleteByID never writes deletedAt, and its own trash arg only widens which docs are deletable. .claude/rules/collections.md claimed the opposite (soft-delete on first call, permanent on second); it cost a wrong test fixture, so the doc is corrected here.
  2. Collection beforeChange runs before field beforeChange, so verifyOnSave can't read the schedule.lastDate that computeLastDate is about to write — revivesFinishedEvent recomputes it with the same merge.

Pre-existing, not introduced: pnpm seed atlas exits 1 with 43 registrations: Questions validation errors and a "verification not met" summary (users 717/755, events 509/511, registrations 847/886). That's dump data quality in collections this branch doesn't touch. Locally 509 events is correct — 2 Atlas test records are skipped as duplicates.

Out of scope, spotted in passing: seeds/lib/payloadHelpers.resetCollection hard-deletes and its find omits trash: true, so a reset won't purge trashed rows. Left alone.

🤖 Generated with Claude Code

Ardnived and others added 14 commits July 30, 2026 10:07
Adds a stored, indexed, hidden `lastDate` sub-field to `scheduleFields()`,
recomputed on every write by a `computeLastDate` beforeChange field hook.
Value is the end of the final occurrence's *local* day (so an event running
today stays live until its own midnight), or `null` when the recurrence never
ends. The pure `lastOccurrenceEnd()` helper is the single definition; the
column is just its DB-queryable projection.

Termination is read off the built rule's own options rather than re-derived
from the sub-fields, so it can't drift from buildRRuleTemporal's conditions.
The hook computes from `{ ...previousSiblingDoc, ...siblingData }`: a field
beforeChange hook only receives the incoming patch and Payload materialises
`{}` for an omitted group, so reading siblingData alone would NULL lastDate
on every unrelated write.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Nullable timestamp + btree index on events, app_cards and both version
tables (scheduleFields is shared with AppCards). Nullable by design: the
column degrades gracefully — a NULL reads as "never ends", so the feeds
keep showing an un-backfilled event rather than hiding it — and any write
to a row back-fills it via computeLastDate.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Replaces the `upcomingDates` finished-check with one shared definition:

- `shouldFinish` moves from the ExpireEvents stage machine into
  `@/lib/schedule/scheduleStatus` — it's now shared with the public feeds
  and (once #599 lands) the registration gate, so it can't live inside one
  job. It keys off the schedule's last occurrence instead of the virtual
  `upcomingDates`, retiring the MAX_MONTHS_AHEAD false positive that made a
  monthly-every-12-months event read as finished while still running.
- `notFinishedWhere(now)` is its SQL counterpart, over the stored column.
  A unit matrix pins the two to the same answers — they're separate
  implementations because a `where` can't call a function.
- `finishEvent` no longer sets `_status: 'draft'`: a finished event stays
  published so its Atlas page keeps resolving for a late seeker following an
  old link. `finished` therefore joins PUBLISHED_STAGES.

`shouldFinish` computes from the sub-fields rather than reading the stored
column, so the nightly sweep is correct from the moment this ships, with no
dependency on the backfill having run.

`EventScheduleInput` moves to src/types/schedule.ts now that it has a second
consumer, and becomes the parameter type of buildRRuleTemporal /
lastOccurrenceEnd so reading a schedule off a document needs no cast.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Nothing unpublishes a finished event any more, so these two filters are the
only thing keeping it off the map and out of listings:

- `GET /api/events/geojson` ANDs `notFinishedWhere(now)` onto the caller's
  `where` unconditionally. Because it's part of the read rather than a
  post-read drop, `totalDocs` and pagination reflect the filtered set, and a
  caller's own `where` cannot bring finished events back into the map feed.
- `excludeFinishedEvents` (beforeOperation) does the same for an API client's
  `find` / `count`, but with an opt-out: a `where` naming `schedule.lastDate`
  is honoured, so a client asking for past events gets them. `findByID` is
  untouched, so old Atlas links keep resolving.

Two things Payload's behaviour dictated here, both verified against it:

- `find` and `findByID` both reach a beforeOperation hook as `operation:
  'read'`, so the list/single split is made on `findByID`'s `id` arg — the
  same trick `filterMeditationsByLocale` uses. Guarding on `'find'` silently
  matched nothing.
- Only the dotted `schedule.lastDate` path is queryable; the nested-group
  shape is rejected upstream with "path cannot be queried". So the opt-out
  check needs no nested-form branch, and a test pins that rejection.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Covers the behaviour change directly: finishing sets `finished` + clears
`nextCheckAt` and leaves `_status: 'published'` (with webPath/webUrl still
non-null), an open-ended recurrence never finishes, and the unverified ladder
still unpublishes at `urgent → expired` and trashes after the grace period.

Verified non-vacuous: restoring `_status: 'draft'` in finishEvent fails the
first case with "expected 'draft' to be 'published'".

Also adds the missing `captureMessage` export to this spec's Sentry mock.
`resolveRecipients` reports an absent region manager through it, so every
region-escalating stage threw before reaching its assertions — no existing
test drove one to completion, so the ladder never actually advanced here.
It now does (advanced: 1, remindersSent: 1, failed: 0).

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`POST /api/events/{id}/register` relied on the published-only access filter to
404 an unregistrable event. A finished event is now published, so that filter
no longer catches one whose schedule has run out — registration would have
succeeded for an event that is over. Rejects with 409 + "This event has ended"
instead: the event exists and is readable, its state just conflicts.

Doing this needed one supporting change. The endpoint's own event lookup
forwards the client `req` via `asTrustedReq`, so `excludeFinishedEvents` was
filtering the event out of it — collapsing the new 409 back into a 404. The
hook now exempts trusted reqs via a new `isTrustedReq` companion to
`asTrustedReq`: an endpoint doing its own lookup needs the true state to answer
precisely. This follows the split `validateClientOriginHook` documents —
result-shaping hooks honour the trusted flag, security gates don't.

Scope note: #599 owns the broader gating rules (capacity, external mode, a
course already under way) and lands the same refusal as `event_ended`; this
closes only the hole reopened here.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Rows written before the column shipped hold NULL, which reads as "never ends" —
so a finished event would stay on the public feeds until something recomputed
it. `scripts/backfill-schedule-last-date.ts` walks `events` + `app-cards` and
fixes them; reports by default, writes with `--force`.

The routine lives in `src/lib/schedule/backfillLastDate.ts` rather than in the
script: it spans two collections, so it belongs to neither one's folder, and
keeping it out of the CLI makes it testable without the script's dotenv +
config-bootstrap side effects.

Two safety properties are pinned by tests rather than asserted:

- `skipVerifyHook` on the write. Without it the Events `verifyOnSave` hook
  treats each backfilled row as a fresh verification and silently restarts
  every escalation cycle — removing the flag fails the test on a moved
  `nextCheckAt`.
- Re-runnable. `lastOccurrenceEnd` has no clock, so a second pass reports 0
  changed.

Not verified by a live run: a dry run against the shared local dev DB blocks on
drizzle's rename-vs-create prompt, because `push: true` wants to add the column
that migration 20260730_170909 adds properly. The int tests cover the behaviour
against a schema built from the current config.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The behaviour change is only discoverable if it's written down — an existing
client whose `GET /api/events` result set shrinks needs to find out why from
/api/docs, not from the source.

- OpenAPI: the geojson description now states the exclusion, the definition of
  finished, the local-midnight rule, that `where` cannot override it there, and
  where the opt-out *does* work; register gains its 409. Guarded by
  tests/unit/openapi-custom-endpoints.spec.ts.
- `.claude/rules/endpoints.md`: a passthrough may narrow the caller's `where`
  — filter inside the read (so totalDocs/pagination stay consistent), and state
  the opt-out convention (feeds unconditional, list reads yield to an explicit
  `where`). Plus the two Payload behaviours that bite: `find`/`findByID` both
  arrive as `operation: 'read'`, and trusted forwarded reads must be exempt.
- `.claude/rules/api-clients.md`: per-read contract table + `isTrustedReq`.
- `.claude/rules/collections.md`: `lastDate` alongside the virtuals, the
  read-termination-off-`options()` and partial-update traps, refreshed key files
  (also fixes a stale `scheduleField.ts` → `scheduleFields.ts` filename).
- `.claude/docs/architecture.md`: adds the missing `ExpireEvents` section.
- `tests/COVERAGE.md`: events row, a new ExpireEvents scheduled-job row, and the
  shouldFinish/notFinishedWhere agreement subject.
- `.claude/rules/scripts.md`: the backfill script.

Two claims in the ticket turned out not to hold, so nothing was changed for
them: the `finished` copy in VerificationStageField/timeline.ts already said
"no longer publicly listed", and architecture.md had no ExpireEvents section to
correct. The genuinely stale copy was the admin notice telling managers to
"republish" a finished event, and a comment in lifecycle/verify.ts.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- `lastOccurrenceEnd` calls `rule.options()` once instead of twice.
- Drops the dead `EventScheduleInput` re-exports from scheduleHooks and
  icsBuilder — every consumer imports it from `@/types/schedule`. (The
  `ScheduleSubFields` re-export stays; SendSessionReminders and AppCards use it.)
- Inlines the single-use `LAST_DATE_PATH` constant.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Found by measuring while triaging a review note, not by reading. The claim under
test was "the backfill deletes historical exclusion records"; it doesn't —
`cleanupExpiredExclusions` strips a >1-day-past exclusion on *every* write,
including the original create, so such a row never had one to lose.

What is real is subtler: `computeLastDate` runs against the incoming patch, so a
create can store a `lastDate` that reflects an exclusion the same write is
removing. The stored value is then not reproducible from the stored sub-fields
(tail excluded at create → the earlier date; a recompute → the later one), and
the first backfill pass rewrites it. Behaviourally inert — a stripped exclusion
is by definition past, so both candidates are behind `now` and the event is
finished either way — but it explains why a first pass can move a `lastDate`
that looked fine, which would otherwise read as a bug.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`event-verification.int.spec.ts` asserted `_status: 'draft'` after the sweep
marks an event finished — the exact contract #603 inverts. Now asserts
`published` plus non-null webPath/webUrl, which is the point of the change:
the event's Atlas page has to keep resolving for a late arrival.

Caught by CI, not locally: my targeted integration set covered events,
events-geojson, event-registration, expire-events and the backfill, but not
event-verification, which also drives the ExpireEvents job.

Refs #603

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three related fixes to the Atlas event import, plus the trash bug the first
one exposed.

**Trash the 2 genuinely-archived events.** Atlas never cleared its lifecycle
timestamps on reactivation, so `archived_at` / `expired_at` / `finished_at` are
stale on almost every row — 287 of 289 `archived_at` and 295 of 297
`expired_at` values are superseded by a later `verified_at`. Only legacyId 75
and 199 carry an `archived_at` that nothing supersedes; they now import with
`deletedAt` set, matching Atlas's `archived` terminal to Payload's soft delete.
`mapStatusToStage` is unchanged and stays status-only: all 12 events with a
`finished_at` but `status: 0` were reactivated, so `verified` is correct for
them, and a test pins that.

**Stagger `nextCheckAt`.** A flat `now + cadence` put all 417 imported events
due inside one week — ~417 reminder emails in that week, region escalations the
next, mass unpublish 21 days later. Now `cadence + (legacyId % cadence)` days:
deterministic (a re-seed reproduces the same date, unlike `Math.random()`) and
forward-only, so no event is ever due sooner than before. ~5/day instead of
~60, at the cost of a doubled worst-case lease — accepted as a one-off
migration artifact.

**Make the importer trash-aware.** `preloadCollection` queried without
`trash: true`, so Payload's default `deletedAt exists: false` filter hid
soft-deleted rows from the existence cache. `upsert` then takes its
`isPreloaded && !preloadedDoc` branch straight to `payload.create` with no
fallback find — duplicating the row on every re-seed. Trashing 75/199 would
have triggered it, and it was already live for Files/Images, which
CleanupOrphanedMedia trashes. Safe to pass unconditionally: Payload's
`appendNonTrashedFilter` ignores `trash` unless the collection enables it.

**Revive a finished event when its schedule is extended.** #603 made the feeds
filter on `schedule.lastDate` rather than `verificationStage`, but
`verifyOnSave` still treated `finished` as absolutely terminal. So extending a
finished event's schedule and saving put it back on the public map while it
stayed at `finished` with `nextCheckAt: null` — publicly listed, never
re-verified, counted inactive by the manager sidebar, which is exactly what the
admin notice instructs. It now re-verifies when the save pushes the schedule's
end into the future. The prospective `lastDate` is recomputed in the hook
because collection `beforeChange` runs before field `beforeChange`, so
`computeLastDate` hasn't written it yet.

Both behavioural fixes are mutation-checked: reverting the `verifyOnSave` guard
fails the revival tests, and dropping `trash: true` fails the preload tests.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- `.claude/rules/collections.md` claimed `payload.delete` soft-deletes on the
  first call and permanently deletes on the second. It doesn't: `deleteByID`
  never writes `deletedAt`, and its `trash` arg only widens which docs are
  deletable. It is always a hard delete; trashing is `update({ deletedAt })`,
  which is what ExpireEvents and the Atlas importer both do. This cost a wrong
  test fixture (a `payload.delete` that hard-deleted, then 404'd on read), so
  it's worth correcting rather than working around. Also adds Events to the
  trash-enabled list and documents why an existence check needs `trash: true`.
- `seeds/lib/AGENTS.md`: the preload cache now includes soft-deleted docs, and
  the consequence — a deliberately-trashed doc is no longer re-created by a
  re-seed.
- `seeds/atlas/MIGRATION_PLAN.md`: `status` is the only authoritative flag, the
  lifecycle timestamps are stale on ~99% of rows, and why the importer does not
  derive a ladder position from a 2024-10-13 snapshot.
- `tests/COVERAGE.md`: the revival case + the new seed-importer preload spec.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@railway-app

railway-app Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-608 environment in sahajcloud

Service Status Web Updated (UTC)
SahajCloud ✅ Success (View Logs) Web Aug 3, 2026 at 9:56 pm

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-608 August 1, 2026 20:35 Destroyed
Base automatically changed from feat/finished-events-off-feeds to main August 3, 2026 21:44
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-608 August 3, 2026 21:54 Destroyed
@Ardnived
Ardnived merged commit 15295da into main Aug 3, 2026
2 checks passed
@Ardnived
Ardnived deleted the fix/atlas-archived-events-and-clock branch August 3, 2026 22:48
Ardnived added a commit that referenced this pull request Aug 4, 2026
The highest-timestamp snapshot on main
(20260803_221051_registrations_full_flag.json) was stale: it merged in via
PR #601, whose registrations_full migration was generated before #605/#608's
schema landed (region level `venue`, events contact_email / address_venue_name,
translations event_title). Those migrations are timestamped earlier than 0803
but merged later — the out-of-order snapshot trap in .claude/rules/migrations.md.

The next migrate:create would have diffed against that stale snapshot and
re-emitted the already-applied DDL. This lands a no-op migration whose
regenerated .json reflects the full current schema, so the chain is healed:
migrate:create now detects no changes (verified). The .ts does nothing — every
column already ships in an earlier migration.

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-608 — e399552e Deployed Aug 3, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant