Problem/Motivation
Follow-up for #3635771: Clarify anonymous flag removal via cron, especially see #12 and #15.
The setting "Settings for anonymous flag removal via cron" (added in #3018713: Add optional deletion of anonymous flaggings whose session has expired) deletes expired anonymous flaggings (uid = 0 and created < now - session.gc_maxlifetime) in FlagCronService::runCronLogic(). The flaggings are deleted through the entity API (ExpiredCollector::deleteMultipleFlagging() → $storage->delete()). This calls Flagging::preDelete(), which dispatches FlagEvents::ENTITY_UNFLAGGED, and FlagCountManager::decrementFlagCounts() then reduces flag_counts.
As a result, every expired anonymous flagging also lowers the totals (and flag_counts rows that reach zero are deleted). On sites that use flags with public, anonymous flagging counters (likes, votes, "useful" ratings, popularity sorting in Views), the counters drop after each cron run, even though no visitor withdrew their flag. For these sites, the cleanup is only meant to stop the flagging table from growing with records that can never be unflagged again (the session is gone), not to change the result.
There is currently no way to remove stale anonymous flagging records while keeping the totals.
#3635771: Clarify anonymous flag removal via cron documented the current behavior; this issue adds an option to change it.
Steps to reproduce (current behavior)
- Create a flag that anonymous users can use and enable anonymous flag removal via cron on it.
- Flag a node as several anonymous users.
flag_counts.countfor the node increases accordingly. - Wait longer than
session.gc_maxlifetime(or backdateflagging.created), then run cron. - The flaggings are deleted and
flag_counts.countfor the node is reduced. If all flaggings were anonymous, the row is deleted.
Proposed resolution
Add a per-flag boolean option to the cron removal settings, e.g. anon_cron_preserve_counts (default FALSE, so the current behavior is kept). When enabled, expired anonymous flaggings are still deleted, but flag_counts is not decremented for them.
Implementation: keep the entity API, skip only the count decrement
The deletion must keep going through the entity API. A direct DELETE FROM flagging query is not an option, because it would:
- leave orphaned rows in
flagging__field_*tables (flaggings are fieldable via Field UI); - skip invalidation of the flagging cache tags and
flagging_list:*tags, leaving links and count output stale; - silently skip
hook_entity_delete(),hook_flagging_delete()and all otherENTITY_UNFLAGGEDsubscribers (search indexing, logging, custom code); - hardcode the storage layout and bypass alternative storage handlers.
Agreed approach (see #13 in #3635771: Clarify anonymous flag removal via cron): a runtime marker on the flagging entities.
- Add a runtime (non-stored) marker on
Flagging, e.g.$flagging->setPreserveCounts(TRUE), whichpreDelete()reads when building the event. The decision stays tied to the deleted entities and is visible to all subscribers. - Add an optional context to
UnflaggingEvent(optional constructor argument pluspreservesCounts(): bool, or a more generalgetReason()returning e.g.'expired_anonymous'), so other subscribers can tell cleanup deletions from user unflags. - In
FlagCountManager::decrementFlagCounts(), skip flaggings marked to keep their counts, but still reset the counts cached in memory. - In
FlagCronService::runCronLogic(), set the marker when$flag->;getAnonCronPreserveCounts()isTRUE.
The marker must not be derived from timestamps. With a cron batch size, expired flaggings can outlive the timeout for several cron runs, and a real unflag by such a user still has to decrement the count.
Behavior to document
- With the option enabled,
flag_countsbecomes a total over all flaggings ever created, while theflaggingtable only contains flaggings that still exist.getFlagFlaggingCount(),getUserFlagFlaggingCount()and Views based on theflaggingtable will return lower numbers thanflag_counts. This is intended. - Kept counts cannot be rebuilt. Nothing in Flag recalculates
flag_counts, so unwanted anonymous flaggings (for example from bots) stay counted until the flag is reset. - Later unflags of remaining (authenticated or still active anonymous) flaggings keep working: the decrement subtracts only the flaggings actually deleted and deletes the row when the count reaches zero or less.
- Resetting a flag (
FlagResetForm) or uninstalling it still deletes the counts as before.
Remaining tasks
- Decide between
preservesCounts()and a more generalgetReason()onUnflaggingEvent. - Add the config key, schema, getter/setter on
Flag/FlagInterfaceand the form element. No post-update hook is needed: defaults live in the config entity's class properties (same ascron_batch_size). - Implement the runtime marker on
Flagging, the event context and the check inFlagCountManager. - Update the docblocks of
getFlagCounts()(reworded in #3376688: Create FlagCountManagerInterface::getFlagCounts()) andgetFlagFlaggingCount()to state which one returns the sum of stored counts and which one counts rows in theflaggingtable. - Update the setting description added in #3635771: Clarify anonymous flag removal via cron (MR !239, "treated like regular unflaggings") to cover the new option.
- Extend
FlagCronServiceTest: with the option enabled, expired flaggings (including field data, if the flag has fields) are deleted, whilegetEntityFlagCounts()andgetFlagEntityCount()stay unchanged. The kernel test from !239 remains the test for the default behavior.
User interface changes
New checkbox "Keep flag counts when deleting expired anonymous flaggings" in the "Settings for anonymous flag removal via cron" fieldset of the flag form, only visible (via #states) when anonymous flag removal is enabled.
Proposed description: "If checked, expired anonymous flaggings are deleted without lowering the flag counts. Counts then also include flaggings that no longer exist. Kept counts cannot be recalculated: unwanted anonymous flaggings (e.g. from bots) stay counted until the flag is reset."
Introduced terminology
None.
API changes
FlagInterface: new getter/setter for the setting.UnflaggingEvent: new optional context (preservesCounts()orgetReason()). Backwards compatible, the constructor argument is optional.Flagging: new runtime marker method (not stored in the database).
Data model changes
New boolean key in the flag.flag.* config schema. No database schema changes.
Release notes snippet
Flags with anonymous flag removal via cron can now keep their flag counts when expired anonymous flaggings are deleted. The option is off by default; existing behavior is unchanged.
Issue fork flag-3641763
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #2
anybodyComment #3
anybodyComment #4
anybodyComment #5
anybodyComment #7
anybodyThe implementation is ready for review on the issue fork branch
3641763-delete-flag-counts-keep-totals.Changes
Flag/FlagInterface, config schema: new keyanon_cron_preserve_counts(defaultFALSE) withgetAnonCronPreserveCounts()/setAnonCronPreserveCounts(). No post-update hook needed: the default lives in the class property, likecron_batch_size.FlagFormBase: new checkbox "Keep total flag counts when deleting expired anonymous flaggings", only visible (#states) when anonymous flag removal is enabled. The description of the "Enable" checkbox (from #3635771) now mentions the option.Flagging/FlaggingInterface: runtime markersetPreserveCounts()/preservesCounts(), not stored in the database.UnflaggingEvent: optional constructor argument andpreservesCounts(). It returnsTRUEonly if all deleted flaggings of the event keep their counts; subscribers can check each flagging withFlaggingInterface::preservesCounts(). Backwards compatible.FlagCountManager::decrementFlagCounts(): skips marked flaggings, but still resets the counts cached in memory.FlagCronService::runCronLogic(): marks the expired flaggings before deleting them if the option is enabled. Deletion still goes through the entity API (field data, cache tags, hooks and events).FlagCountManagerInterface: docblocks ofgetFlagCounts()(sum of the stored total counts) andgetFlagFlaggingCount()(rows in theflaggingtable) clarified.FlagCronServiceTest: new tests for the enabled option (flaggings and field data deleted, total counts kept, event context), for later unflags still lowering the counts, for deleting an expired flagging outside of cron, and for deleting flaggings where only some are marked. The existing test for the default behavior is kept.Decision on the remaining task
I chose
preservesCounts()over a generalgetReason(): it maps 1:1 to the marker on the flaggings and is the only informationFlagCountManagerneeds. A reason can still be added later if there is a use case.Out of scope
Passing a parameter through the deletion instead of the runtime marker on the flaggings was considered, but is not part of this MR. See the next comment for the pros and cons.
Manual testing
Setup: Flag on this branch, a node flag (personal scope), anonymous users have the permissions to flag and unflag with it. Under "Settings for anonymous flag removal via cron", check "Enable".
drush sqlq "SELECT * FROM flag_counts"shows the matching count.drush sqlq "UPDATE flagging SET created = created - 1000000 WHERE uid = 0", then rundrush cron. Expected: the anonymous rows are gone from theflaggingtable,flag_countsis unchanged, and the "Count" link type / Views flag count still show the old total.Comment #8
anybodyAlternative: a parameter instead of the runtime marker
For comparison, there is a draft implementation that passes a parameter instead of setting a runtime marker on the flaggings: draft MR !XXX, branch
3641763-delete-flag-counts-keep-totals-parameter. It is based on the main branch, so the setting, form, docs and tests are identical and the diff shows only the mechanism:Compare both approaches
Background: a plain parameter cannot reach
FlagCountManager. The deletion goes through the entity API:EntityStorageInterface::delete(array $entities)→ staticFlagging::preDelete($storage, $entities), which creates theUnflaggingEvent. Both signatures are defined by core, so the value has to be stored somewhere along the way.How the draft works
ExpiredCollectorInterface::deleteMultipleFlagging(array $flaggings, bool $preserveCounts = FALSE);FlagCronServicepasses$flag->getAnonCronPreserveCounts().FlaggingStorageInterface::delete(array $entities, bool $preserveCounts = FALSE):FlaggingStoragekeeps the value in a property during the deletion and resets it infinally.Flagging::preDelete()reads and resets it via the internalFlaggingStorageInterface::consumePreserveCounts()and passes it toUnflaggingEvent. Because it is reset when read, flaggings deleted by subscribers during that deletion lower the counts again (covered by a test).FlagCountManager::decrementFlagCounts()returns early if$event->preservesCounts(), after resetting the counts cached in memory.Flagging/FlaggingInterface.Runtime marker (main MR)
EntityStorageInterface::delete(), with any storage handler, and per flagging (mixed deletions are handled correctly).FlaggingInterface. Callers have to mark the entities before deleting them, which is less explicit than an argument.Parameter (draft MR)
deleteMultipleFlagging($flaggings, $flag->getAnonCronPreserveCounts()).Flaggingentity class orFlaggingInterface; the check inFlagCountManageris a single early return.try/finallyreset and the "reset when read" logic inpreDelete()to not leak into nested deletions, which is subtle and easy to break later.FlaggingStorageInterface::delete()is redeclared with an extra parameter and getsconsumePreserveCounts(), andExpiredCollectorInterface::deleteMultipleFlagging()gets a new parameter. Other implementations of these interfaces (probably rare) would break.EntityStorageInterface: callers need aninstanceof FlaggingStorageInterfacecheck (the collector throws aLogicExceptionif the storage does not support it).preservesCounts().Deleting directly with a
DELETEquery is not an option for either variant (see the issue summary: orphaned field data, stale cache tags, skipped hooks and events).Suggestion: keep the runtime marker (main MR), as agreed in #13 of #3635771. It has no shared state and no signature changes. The draft is only meant for comparison and should be closed once we decide. Opinions welcome.
Let's discuss this finally now!
Comment #10
anybodyI'm leaning towards the non-parameter implementation.
The huge benefit in my eyes with the parameter is visibility and clarity on the functionality. Both also have their worth!
Comment #12
ivnishThanks for the detailed comparison in #7, that made the decision easy. I tested both variants on Drupal 11.4 / PHP 8.4. The cron scenario and the nested deletion by a subscriber behave the same in both, so both work.
Decision: !251
We go with !251, for your reasons plus three more:
FlaggingStorageInterface::delete()andExpiredCollectorInterface::deleteMultipleFlagging()change their signature, and both interfaces are in released versions (ExpiredCollectorInterfacesince 5.2.0). Any other implementation or override with the old signature, like a decorator or an alternative storage, is a PHP fatal error when the class is loaded (checked on PHP 8.4).consumePreserveCounts()resets the value on the first read, but core callspreDelete()once per entity class. In onedelete()call with flaggings of two classes, only the first class keeps its counts. That needs bundle classes on flaggings, so it is an edge case, but it shows how easy the "reset when read" logic is to break.FlaggingStorageInterfaceand the option enabled, cron fails with theLogicExceptionas soon as there are expired flaggings.Please close !252 as draft.
Needs work: resetting the flag does not clear the kept counts
One gap in !251 that we should fix here, because the checkbox description says the counts "stay counted until the flag is reset". They do not:
unflagAllByFlag()): 0 flaggings, count 3.FlagResetFormgoes throughFlagService::unflagAllByFlag(), which deletes the flaggings the regular way.FlagCountManager::decrementFlagCounts()only deletes aflag_countsrow when the count is not higher than the number of deleted flaggings, so the kept ones stay. The same happens when the flag itself is deleted: theflag_countsrows of the deleted flag remain.Suggestion: in
unflagAllByFlag(), also delete theflag_countsrows of the flag, for example through a new method onFlagCountManager, and add the reset totestCronDeletionPreservesFlagCounts(). Could you add that?Comment #13
anybodyThanks @ivnish yes! Working on it!
Comment #14
anybody@ivnish thanks - hope I got you right?