Repository navigation
Resolve is_current once per request (port of sg-dev stack #524–#526) - #552
Merged
Merged
Conversation
Category#is_current has had no direct test coverage. recommendation_spec stubs both is_current and has_reporting_cycle_taxonomy?, so the logic itself was guarded by nothing - and it took eight commits to settle: 29f1f8e taxonomy id from config, replacing a discovery query 1c07069 has_reporting_cycle_taxonomy? extracted f0f147f sibling lookup scoped to .published 6e631bc draft cycles count as current, or their recs vanish 90ce6b1 fix 7043024 fix (self not parent) 98a524a fix 0361984 only-child rule; date.present? moved inside the sibling branch Each test names the commit whose behaviour it pins, so a regression points at the bug it reintroduces. Also characterises a latent bug rather than fixing it: order(date: :desc) does not exclude undated siblings and Postgres sorts NULLs first on DESC, so one undated published cycle becomes .first and knocks out every sibling - the undated one fails date.present?, the dated ones fail (first == self). Every recommendation under that treaty then drops out of current_only. It has been latent since 29f1f8e, which replaced order(Arel.sql("COALESCE(date, created_at) DESC")) with order(date: :desc) when the logic moved from Recommendation to Category. Not live today: every reporting cycle currently carries a date.
Adds the branches the existing suite never reached: siblings in a different sub-taxonomy, same-date ties, archived siblings, future dates and undated siblings, plus unstubbed coverage of the propagation chain from ProgressReport down to Category. The only end-to-end current_only test made its non-current recommendation non-current by having no parent category, so it failed the category.present? guard and never exercised the sibling date comparison. It now loses that comparison instead: dating it newer fails the test, which it did not before.
Two problems, both leaving is_current at the mercy of the query plan. Postgres sorts NULLs FIRST on DESC, so an undated published cycle became .first: it then fails date.present?, and every dated sibling fails (first == self). One undated cycle made every cycle under that treaty non-current, dropping all of its recommendations out of current_only. Siblings sharing a date had no tie-break at all, so which one won was undefined - "exactly one cycle is current" was incidental rather than a property of the code. Ordering now puts NULLs last and breaks ties on id, so an undated sibling cannot displace a dated one and a tie resolves to the newest created. Undated categories stay non-current themselves, which is the existing date.present? guard: with no date there is nothing to rank them by. Restoring the historical COALESCE(date, created_at) ordering, dropped at 29f1f8e when this logic moved from Recommendation to Category, would not have fixed the first problem: an undated row created recently still sorts above an older dated one, and the date.present? guard means it can never be current itself, so it would go on poisoning its siblings. Two expectations flip, both from the pair that characterised this deliberately.
Archiving a cycle category is meant to remove it from consideration entirely - it is a soft delete. But published only filtered draft, so an archived category stayed in both the only-child count and the ordering: archiving the current cycle did not promote the runner-up, the archived one kept winning and the live one stayed non-current. Addresses #524 (comment)
Narrowing published changed every caller and left archived non-draft categories in neither draft nor published. The bug is specific to the sibling comparison, so filter there instead. Also cover archiving the current cycle directly, which is the scenario the previous commit describes.
Leaving archived siblings out of the only-child count meant an archived category with one live sibling counted that sibling as itself and came out current. Archiving is a soft delete, so guard on self as well - including drafts, which otherwise short-circuit to current.
recommendation_categories and measure_indicators back CurrentCycle's hot queries but, unlike recommendation_measures, were never indexed on either foreign key - every lookup by category_id, recommendation_id, measure_id or indicator_id was a sequential scan over the whole table.
is_current walks ProgressReport -> indicator -> measures -> recommendations -> categories. Asked of one record it is an N+1 at every hop, and because it is also a serialiser attribute it runs twice per request: once to filter ?current_only=true, once to serialise. On UAT GET /recommendations issued ~3100 queries for 1.5s. CurrentCycle resolves the id sets for the whole request in a fixed number of queries - 10 in a two-cycle fixture, whether there are 5 records or 40. It does not reimplement Category#is_current. That predicate took eight commits to settle and its sibling comparison is not scoped to the cycle taxonomy, so it runs exactly as it stands, once per cycle category (a handful) rather than once per recommendation (thousands). Only the trivial "empty? || any?" propagation above it is resolved set-wise. The join tables are read through the stale set rather than in full: only rows touching a stale child can produce a stale parent, and a parent is spared as soon as it has a child outside that set, so neither query reads more of the table than the stale set reaches. Nothing is read at all when no child is stale. Null foreign keys are excluded. The join models validate both keys so the app cannot write one, but the columns are nullable and the associations this replaces skip such a row entirely, yielding no record - so a null must neither make a parent stale nor rescue one. The controller filters still return a relation, so ordering, paging and policy_scope compose as before. The per-model is_current specs stubbed the level below on a specific loaded instance, which a request-scoped resolver cannot honour - and two of them asserted on the stubbed object itself, so they could never have failed. They are superseded by is_current_propagation_spec, which exercises the same chain against real records.
after_commit with no on: fired on every save of seven models, several of which cannot affect cycle membership - a title edit on a Recommendation reset the resolver even though nothing relevant changed. In a batch import that is a reset per record, and each reset rebuilds the whole set on next access. Recommendation, Measure and Indicator drop the include entirely: the resolver never reads their attributes, only the join tables between them. Category narrows to the attributes #is_current actually reads (draft, date, parent_id, taxonomy_id) plus destroy. The three join models (RecommendationCategory, RecommendationMeasure, MeasureIndicator) narrow to create/destroy - their foreign keys ARE the membership, so an update to any other column cannot change it.
The comment claimed a treaty carrying children in several competing sub-taxonomies as the reason not to rewrite Category#is_current. No current deployment's taxonomy has more than one child under a parent, so that claim was about data this repo cannot verify, not the code. The weaker, code-level argument (an unscoped rewrite would change an uncharacterised answer, on a predicate that took eight commits to settle) holds regardless and doesn't depend on it.
indicator_current?(nil) returned true (nil is never in the non-current set), while current_only's own controller filter - where.not(indicator_id: stale_ids) - excludes a null indicator_id regardless of what's in stale_ids, since NULL NOT IN (...) is never true in SQL. A legacy ProgressReport with no indicator reported itself current while being filtered out of every current_only list.
CurrentCycle exists to replace an N+1 with a fixed number of queries, and that property has no test: nothing else in the suite fails if a serialiser change, an added association, or a stray is_current call reinstates it. Asserts a ceiling rather than an exact count - the true number drifts with unrelated changes without the fixed-cost property being violated.
This branch was previously 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.
Brings the
is_currentoptimisation stack from sg-dev (#524, #525, #529, #528, #526) to the NZ branch. The 12 commits are cherry-picked unchanged apart from conflict resolutions, plus one NZ-specific spec fix.What it does
is_currentfor recommendations, measures, indicators and progress reports is resolved once per request byCurrentCycleinstead of per record (N+1 at every hop, run twice per request: filter + serialiser).Category#is_currentitself is unchanged in approach and runs once per reporting-cycle category.recommendation_categoriesandmeasure_indicatorsforeign keys (Index CurrentCycle's join-table lookups #528).ResetsCurrentCycleinvalidates the per-request resolver on relevant writes only.NZ-specific changes
:publishedtrait (draft defaults to false here); NZ'sonly_manager_and_admin_users_can_be_assignedvalidation kept.enable_mfawhere it exists.Tested on nz-uat
Response sizes unchanged to the byte. Sibling logic additionally verified with test data (newest wins, drafts current, undated cycle no longer unseats dated ones, archived runner-up promoted, recs without a cycle stay current, propagation to measures/indicators), and cache invalidation confirmed in the running app.
User-visible changes
None expected with current NZ data (one cycle per treaty). In general:
current_only.current_onlyinstead of erroring.