Repository navigation
fix(atlas): trash genuinely-archived events, stagger the import clock - #608
Merged
Merged
Conversation
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]>
|
🚅 Deployed to the SahajCloud-pr-608 environment in sahajcloud
|
railway-app
Bot
temporarily deployed
to
sahajcloud / SahajCloud-pr-608
August 1, 2026 20:35
Destroyed
railway-app
Bot
temporarily deployed
to
sahajcloud / SahajCloud-pr-608
August 3, 2026 21:54
Destroyed
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
CleanupOrphanedMediatrashes.verificationStage: 'finished', never re-verified.The finding behind all of this
Atlas's
statusis the only authoritative current-state flag. Atlas stampedexpired_at/archived_at/finished_aton transition but never cleared them on reactivation, so they're stale on almost every row:status("current" = not superseded by a later
verified_at.) 287 of 289 rows witharchived_atand 295 of 297 withexpired_atwere re-verified afterwards. SomapStatusToStageis correct as written and unchanged — including for the 12 events with afinished_atbutstatus: 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 againstverified_at),importDeletedAt(a still-currentarchived_at→deletedAt),importCheckOffsetDays(the stagger).seeds/atlas/import.ts— passeslegacyId+deletedAt.seeds/lib/BaseImporter.ts—trash: trueon the preload find.src/collections/Events/hooks/verifyOnSave.ts—revivesFinishedEventguard.Why the stagger is shaped this way
cadence + (legacyId % cadence)days:legacyId—Math.random()would reshuffle all 417 due dates on every--updaterun. Verified: a second run reproduced the identical spread.Why no ladder derivation
Atlas's
should_update_status_atis preserved inlegacyDataand 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 inMIGRATION_PLAN.md.Test Results
atlas-verification.spec.ts,tests/int/seed-importer-preload.int.spec.ts, 4 revival cases inevent-verification.int.spec.tsBoth behavioural fixes are mutation-checked (each flipped once to confirm the test fails):
verifyOnSave's blanketfinishedbail-out → 2 revival tests fail.trash: truefrom the preload → 2 preload tests fail.Verified live against the local DB (
pnpm seed atlas --update, twice):deletedAt=2022-09-14/2023-05-08— exactly theirarchived_atlegacy_ids after a 2nd runNotes for reviewer
The onboarding window is ~4–8 weeks, not a quarter. The stagger is bounded by the manager's
event_verificationcadence, and all 328 managers are onMonthly(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
--updatere-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
--updatemode. 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):
payload.deleteis always a hard delete, even on atrash: truecollection —deleteByIDnever writesdeletedAt, and its owntrasharg only widens which docs are deletable..claude/rules/collections.mdclaimed the opposite (soft-delete on first call, permanent on second); it cost a wrong test fixture, so the doc is corrected here.beforeChangeruns before fieldbeforeChange, soverifyOnSavecan't read theschedule.lastDatethatcomputeLastDateis about to write —revivesFinishedEventrecomputes it with the same merge.Pre-existing, not introduced:
pnpm seed atlasexits 1 with 43registrations: Questionsvalidation 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.resetCollectionhard-deletes and its find omitstrash: true, so a reset won't purge trashed rows. Left alone.🤖 Generated with Claude Code