Repository navigation
fix(meditations): cache the node weights on the save itself, not after it - #845
Conversation
`persistMeditationNodeWeightsCache` wrote the derived `subtleSystemNodeWeights` with a raw `payload.db.updateOne`, which touches the main row and no version row. Meditations is drafts-enabled (`maxPerDoc: 3`, `drafts.schedulePublish`), so `updateByID` loads the document it is about to change through `getLatestCollectionVersion` — `parent = id AND latest = true`, falling back to the main row only when no version row exists. It never compares the two timestamps. So the next `payload.update` on that meditation — an admin save, a scheduled publish — started from the stale version row and wrote the pre-cache value back over the main row. Both writers reach the helper: `recomputeMeditationNodeWeights` on Meditations and `cascadeFrameNodeChange` on Frames. Nothing served wrong data. `payload.findByID` without `draft: true` reads the main row, so API consumers stayed fresh until the next save. What degraded is downstream of the null: the virtual `title` afterRead returns `null` for an empty map so the auto title disappears, and `/api/meditations/:id/related-lectures` falls through to an ad-hoc compute per request. The bypass stays. Instead the helper now does the version half that payload's own `versions/updateLatestVersion.js` performs, inside the same `try`, so a failure in either write still reports through `reportMeditationNodeWeightsCacheError` and returns `false` rather than throwing (#390). Two details were read out of `[email protected]` rather than assumed: - **It targets the `latest: true` row, not merely the newest.** `updateLatestVersion` filters on `parent` alone, while the read in `getLatestCollectionVersion` filters on `latest` as well. Copying the writer's own filter can update a row the reader never looks at. - **It passes the whole `versionData` shape.** `updateVersion` hands `versionData` straight to `upsertRow`, whose header states it "replaces the entire row and does not support partial updates". So the write mirrors `updateLatestVersion`: `createdAt`, `latest`, `parent`, `updatedAt`, and the current `version` spread with the one field changed. A meditation with no version row stops after the main-row write and returns `true` — every read of it resolves to the row already written. `payload.update({ unpublishAllLocales: true })`, the route #835 and #842 took for Events, was rejected here and the ticket says why: both writers are `afterChange` hooks, and a re-validating write there re-introduces #835's failure mode on a path #390 ruled must never throw — the cascade writer runs it once per affected meditation. The JSDoc's reason 1 is corrected while the function is open. It claimed the bypass means "no need for a `skipRecomputeNodeWeights` context flag". The flag exists, is checked in `recomputeMeditationNodeWeights`, and two existing specs already set it. What the bypass actually buys is no re-validation of the whole document on a derived-field write — #835's failure mode — so that is what it now says. Five cases in `meditationFrames.int.spec.ts`, four of them watched failing against the defect at its own site. The fifth is the no-version-row no-op, which passes either way by construction: - the version row carries the same map as the main row; - an unrelated update does not resurrect the pre-cache value. It edits `label` deliberately — an update touching `frames` or `duration` re-fires `recomputeMeditationNodeWeights` and re-persists the cache, so the case would pass with the defect in place; - the rewritten row keeps its `id`, `latest`, `parent`, `createdAt` and the rest of its document; - a throw from `payload.db.updateVersion` does not fail the save. The existing sibling spies on `updateOne` with a single-key `data`, so it covered only half the failure surface. The fixture gives its frame a real `subtleSystemNode`. Verified against `src/collections/Frames/Frames.ts` (a `relationship` to `subtle-system-nodes`) and `src/lib/meditations/nodeWeights.ts` (only a populated object with a string `slug` contributes weight): the suite's shared frames carry no node, so a meditation built from them caches `{}` and every assertion above would have held vacuously. Closes #843 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RhoCD7JoCgHVcRetwEut3X
…lding From the review pass. The JSDoc's reason 1 rested on a premise the source does not support, and the spec carried three pieces of state vitest already records. **Reason 1 was wrong, and the ticket's own rejected alternative is why.** It said a write back through `payload.update` re-validates the whole document. `unpublishAllLocales: true` — the route #835 took for Events — sets `skipValidation: true`, so validation is not what the bypass buys. What it actually buys is checkable: the update operation stamps `updatedAt` on the main row before writing it, so a derived-field write would make the document look edited, and the Frames cascade would bump every meditation using the frame. The comment now says that, and names the rejected alternative so the next reader does not re-derive it. `cascadeFrameNodeChange`'s docblock claimed "each Meditation update sets `context.skipRecomputeNodeWeights`". It sets no context and performs no update — it calls the DB bypass, which is why the hook cannot re-fire. Same class of stale claim the ticket asked to be corrected in `frames.ts`, one file over. In the spec: `mockRejectedValue` replaces a hand-rolled implementation, so `versionWriteAttempted`, the two type casts and an unreachable `else` branch go — `expect(spy).toHaveBeenCalled()` is the same assertion. The non-empty-cache guard moves into `meditationWithWeights`, which now returns both halves, dropping two `as Record<string, number>` casts and two repeated assertions. One comment narrating the line below it is cut. All four regression cases were watched failing again after the refactor, to confirm none went vacuous. Findings not taken, each with its reason: - **Use `payload.update({ unpublishAllLocales: true })` instead.** The ticket decided against it and said to decide before implementing. Its stated reason does not hold, but a better one does: `updatedAt`, above. It also re-enters the write path's other obligations — `enforceMaxVersions` against `maxPerDoc: 3`, `saveSnapshot` — on a best-effort cache write. - **Hoist the `findVersions` out of the Frames cascade loop** into one `parent: { in: [...] }` read. Real N+1, but it widens the PR into a second hook and an optional parameter. Left for the reviewer to call. - **Compute the weights in `beforeChange` instead**, so the cache rides the save payload already performs. The right long-term shape, and a larger change than this fix. - **Fold the two version-row cases into one.** They assert different properties, and folding makes a failure ambiguous about which broke. - **Drop `new Date(latest.createdAt).toISOString()` as a no-op round trip.** It mirrors `updateLatestVersion`'s `versionData` shape exactly, which is the point of the ⚠ above it. - **Drop `sort` and `pagination: false` from the read.** `pagination: false` skips the count query, and the sort matches the reader's own query, so the row written is the row `getLatestCollectionVersion` will pick. Refs #843 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RhoCD7JoCgHVcRetwEut3X
The `frames` row of the coverage map named the hooks but not the drafts half the new cases cover. Refs #843 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RhoCD7JoCgHVcRetwEut3X
|
🚅 Deployed to the SahajCloud-pr-845 environment in sahajcloud
1 service not affected by this PR
|
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
Scope is right: 4 files, 208 lines.
Decision 1 holds. payload.update stamps updatedAt (utilities/update.js:254); db.updateOne does not, since drizzle's upsertRow deletes an absent one rather than defaulting it (upsertRow:57-60). Keep the bypass. The latest: true ⚠ checks out. Decision 2: agreed, decline both here.
It is a hand-copy of updateLatestVersion pinned to 3.86.0 internals, covered by int specs through the real API, so an upgrade breaks loudly. Acceptable — but your declined beforeChange finding makes #843 unreachable. Land this, file that.
Findings
consider—frames.ts:320bumps the version row'supdatedAtwhile preservingcreatedAt. See thread.- A ticket, not this PR:
recomputeMeditationNodeWeightshas no_statusgate, so a draft save writes draft weights onto the published main row.
Checked — read: frames.ts, both callers, Meditations.ts, the new specs, #843. Unpacked payload/drizzle 3.86.0 for the version helpers and upsertRow. No meditations field is localized.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
The version half copied `updateLatestVersion`'s `updatedAt: now` along with the rest of its `versionData` shape. That stamp is exactly the churn the docblock's reason 1 says the bypass exists to avoid on the main row: a frames cascade would restamp the latest version row of every meditation using the frame, and the admin's draft view reads that row. `updateLatestVersion` bumps it because a user save is in flight. Here only a derived field moved, so the row keeps both timestamps, the way it already kept `createdAt`. It also removes a way to mislead payload's own concurrency check: `updateLatestVersion`'s failure path treats a version row whose `updatedAt` has advanced as a concurrent commit and returns it instead of calling `createVersion`. A cache write that bumped the stamp could stand in for a save that never happened. The version-row shape case now pins `updatedAt` beside `createdAt`, watched failing against the old line. Refs #843 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_014yz4WC61TfwW9QT2aq59fK
|
Addressed the adversarial review. Pushed Adopted — the version row's Not filed — the missing Lean gate green. Full integration lane: 1372 passed. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
@sydevs-bot It looks like we have two decisions that would result in a better long term shape but were deemed beyond the scope of this change. It would be best to widen the scope and adopt the best long term shape. Make that change |
Ardnived asked for the two shapes the PR body had declined as out of scope. **The cache rides the save.** `invalidateMeditationNodeWeights` (null it) and `recomputeMeditationNodeWeights` (recompute, then write through the DB adapter) collapse into one beforeChange hook that puts the weights in `data`. Payload then writes the main row and the `latest: true` version row from one value, so #843 is unreachable rather than repaired: there is no second write for a later save to start behind. It also closes the `_status` gap the review pass raised as a follow-up ticket. The old afterChange write went to the main row whatever the save's status, so a draft save published its draft weights. Riding the save means a draft's weights stop at the draft's version row. **One version-row read per cascade.** `persistMeditationNodeWeightsCache` stays for the one writer with no save to ride — the Frames cascade, which touches other documents — so #390's never-throw guarantee and the `updatedAt` bypass reasoning are untouched. Its `findVersions` was an N+1 inside the cascade loop. `findLatestMeditationVersionRows` hoists it to one `parent: { in: [...] }` read, and the helper takes the row through a new `latestVersion` argument. Safe to hoist because `latest` is unique per parent, each meditation is visited once, and the main-row write in between does not touch the version table. The N writes still cannot be batched: `upsertRow` replaces the whole row. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_019JiPrv947aDfE2aQXyPpo9
|
Widened as asked. Pushed Adopted — the Adopted — the cascade's N+1. One Two new cases watched failing at the causing site: One thing still unwidened, in the body: the cascade writes to the main row whatever the meditation's Lean gate green. Targeted integration specs: 27 + 56 passed. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
… version row The version-row half of `persistMeditationNodeWeightsCache` existed because the Frames cascade writes the main row alone, leaving the `latest: true` version row holding the pre-cascade weights for the next save to recombine from (#843). Closing that on the read side instead removes the need for it: `cacheMeditationNodeWeights` now recomputes on every meditation save rather than only when `frames` or `duration` changed, so a recombine can no longer carry a stale value onto the main row. That deletes `findLatestMeditationVersionRows`, the `db.updateVersion` call and its `latestVersion` argument, the cascade's hoisted batch read (which existed only to feed it), and the now-unused `meditationFramesChanged`. The cost is one frames read per meditation save that does not touch frames. The regression case moves with the mechanism: the cascade repoints a frame's node, then a label-only save must keep the cascaded weights. Watched failing with the change gate reintroduced — `{ mooladhara: 42 }` against `{ swadhistan: 42 }`. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01UR5gyuZ9FXScrTKdL9N637
|
Pushed Adopted. What makes that safe. A recombine reads the Not taken — skipping non-published rows. Your call. The cache also feeds Regression case moved to the cascade, watched failing. Lean gate green, 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
No push. One thread, rebutted. A node-weights change gate cannot see the cascade. The hook's The gate is safe only if the cascade also writes the version row. That is the write you asked me to delete last round. One of the two has to exist. Publish-only gating is separate, and it is safe. The publish itself recomputes. It costs the admin auto-title on drafts, which Nothing changed on the branch, so no gate ran and nothing was pushed. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Summary
subtleSystemNodeWeightscache is now computed inbeforeChangeand handed to the save already in flight. Payload writes the main row and thelatest: trueversion row from one value, so fix(meditations): the node-weights cache write is overwritten from the stale version row #843 is unreachable rather than repaired — there is no second write for a later save to start behind._statusgap this PR had raised as a follow-up. The old afterChange write went to the main row whatever the save's status, so a draft save published its draft weights.framesordurationchanged, so the pre-cascade value the Frames cascade leaves on the version row cannot survive a recombine. That is what letspersistMeditationNodeWeightsCachestay a plain main-row write.Changes
src/collections/Meditations/hooks/cacheMeditationNodeWeights.ts— new. ReplacesinvalidateMeditationNodeWeights(null it) andrecomputeMeditationNodeWeights(recompute, then write back). Runs afterextractAudioDuration, so the weights are computed against the duration this save stores. Recomputes unconditionally. Never throws (fix(meditations): intermittent 500 on PATCH /api/meditations/:id during publish #390): a compute failure clears the column and reports.src/lib/meditations/frames.ts—persistMeditationNodeWeightsCacheis documented as the cascade's writer and writes the main row alone.meditationFramesChangedis gone with the change gate.src/collections/Frames/hooks/cascadeFrameNodeChange.ts— says why its write reaches the main row alone, and what brings the version row back in line.src/lib/meditations/nodeWeights.ts—recomputeWeightsForMeditationno longer asks for anidit never read, so a create can call it.tests/int/meditationFrames.int.spec.ts— the version-row surgery cases are gone with the code they covered; the fix(meditations): the node-weights cache write is overwritten from the stale version row #843 case now runs through the cascade, watched failing.Preview
nullwhile the cache isTest results
typecheck,typecheck:tests, 2163 unit testsmeditationFrames.int.spec.ts— 24 passedManual verification
Notes for reviewer
Open question, from the last round's thread. Skipping the compute for non-published rows is not taken. The cache feeds
fallbackTitle, the auto-title the admin shows for drafts and unpublished meditations, so skipping blanks it until publish. And a collectionbeforeChangehook receives the mergeddata, so_statusreadsdraftfor any unpublished meditation — not only for a save that writes no main row, which payload does not signal to the hook. Say the word and it goes in.Decision 1 stands and was not asked about.
payload.updatestampsupdatedAton the main row, which a frames cascade would do to every meditation using the frame, so the cascade keeps the bypass.Detail
Why the shape is correct, not merely nicer. Payload's
updateDocumentruns collectionbeforeChangehooks before the field ones (collections/operations/utilities/update.js:123vs:138), then writes:db.updateOneonly when!isSavingDraft, thensaveVersionalways. So onedatareaches both rows, and a draft save reaches only the version row. The old pair could not express that —persistMeditationNodeWeightsCacheis adb.updateOneon the main row, with no status in scope.data.framesat that point is still whatever the client posted, because theframesfield's ownbeforeChangenormalizer has not run yet.normalizeMeditationFramesis what makes it safe to read —FrameListManagerposts the enriched array straight back.Why the recompute is unconditional. The Frames cascade has no save to ride, so its write reaches the main row alone and the
latest: trueversion row keeps the pre-cascade weights. The nextpayload.updatestarts from that row (getLatestCollectionVersion), so a save gated onframes/durationchanging would carry the stale value back onto the main row. Recomputing every time closes #843 on the read side, and it is why no version-row write exists anywhere. The cost is one frames read per meditation save that does not touch frames.Watched failing. At the site that causes it. Reintroducing the change gate reds the cascade case:
expected { mooladhara: 42 } to deeply equal { swadhistan: 42 }— the frame's previous node, recombined back over the cascaded value.An earlier version of that case staged the staleness with a direct
persistMeditationNodeWeightsCachecall, which puts the wrong value on the main row and leaves the version row correct — the opposite of #843. It passed with the defect in place. Only the cascade produces the real arrangement.Draft isolation. Re-adding the old afterChange main-row write alongside the new
dataassignment reds it:expected { mooladhara: 37 } to deeply equal { mooladhara: 42 }— the draft's 37-second window on the published row.The case that changed rather than moved. Cache-write failure. The old case spied
db.updateOnefor a lonesubtleSystemNodeWeightspayload, which a meditation save no longer performs. It now forces the compute's frames read to throw and asserts the save survives with anullcache. The spy keys onselect.subtleSystemNode, which theframesafterRead enrichment does not send — otherwise it would catch the wrong read. The cascade's own failure case spiesdb.updateOnescoped tomeditations, since that is the write the cascade still makes.context.skipRecomputeNodeWeightsstill works.meditation-lectures.int.spec.tsuses it to set the column deliberately. The hook honours it first.Security review: skipped. No changed path matches
securityReview.triggerPattern.No migration. No collection or field config changed.
Closes #843
🤖 Written by the sydevs autonomous loop — see what this is