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)

  1. Create a flag that anonymous users can use and enable anonymous flag removal via cron on it.
  2. Flag a node as several anonymous users. flag_counts.count for the node increases accordingly.
  3. Wait longer than session.gc_maxlifetime (or backdate flagging.created), then run cron.
  4. The flaggings are deleted and flag_counts.count for 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 other ENTITY_UNFLAGGED subscribers (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.

  1. Add a runtime (non-stored) marker on Flagging, e.g. $flagging->setPreserveCounts(TRUE), which preDelete() reads when building the event. The decision stays tied to the deleted entities and is visible to all subscribers.
  2. Add an optional context to UnflaggingEvent (optional constructor argument plus preservesCounts(): bool, or a more general getReason() returning e.g. 'expired_anonymous'), so other subscribers can tell cleanup deletions from user unflags.
  3. In FlagCountManager::decrementFlagCounts(), skip flaggings marked to keep their counts, but still reset the counts cached in memory.
  4. In FlagCronService::runCronLogic(), set the marker when $flag->;getAnonCronPreserveCounts() is TRUE.

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_counts becomes a total over all flaggings ever created, while the flagging table only contains flaggings that still exist. getFlagFlaggingCount(), getUserFlagFlaggingCount() and Views based on the flagging table will return lower numbers than flag_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 general getReason() on UnflaggingEvent.
  • Add the config key, schema, getter/setter on Flag/FlagInterface and the form element. No post-update hook is needed: defaults live in the config entity's class properties (same as cron_batch_size).
  • Implement the runtime marker on Flagging, the event context and the check in FlagCountManager.
  • Update the docblocks of getFlagCounts() (reworded in #3376688: Create FlagCountManagerInterface::getFlagCounts()) and getFlagFlaggingCount() to state which one returns the sum of stored counts and which one counts rows in the flagging table.
  • 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, while getEntityFlagCounts() and getFlagEntityCount() 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() or getReason()). 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

Command icon 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

anybody created an issue. See original summary.

anybody’s picture

Issue summary: View changes
anybody’s picture

Issue summary: View changes
anybody’s picture

Issue summary: View changes
anybody’s picture

Status: Active » Needs review

anybody’s picture

AI disclosure: These changes and this comment were drafted with the help of an AI assistant (Claude Code) and still need a human review.

The implementation is ready for review on the issue fork branch 3641763-delete-flag-counts-keep-totals.

Changes

  • Flag / FlagInterface, config schema: new key anon_cron_preserve_counts (default FALSE) with getAnonCronPreserveCounts() / setAnonCronPreserveCounts(). No post-update hook needed: the default lives in the class property, like cron_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 marker setPreserveCounts() / preservesCounts(), not stored in the database.
  • UnflaggingEvent: optional constructor argument and preservesCounts(). It returns TRUE only if all deleted flaggings of the event keep their counts; subscribers can check each flagging with FlaggingInterface::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 of getFlagCounts() (sum of the stored total counts) and getFlagFlaggingCount() (rows in the flagging table) 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 general getReason(): it maps 1:1 to the marker on the flaggings and is the only information FlagCountManager needs. 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".

  1. Edit the flag: "Keep total flag counts when deleting expired anonymous flaggings" is only visible while "Enable" is checked. Check it and save, then reopen the form. Expected: the checkbox is still checked.
  2. Flag a node as anonymous user in 2-3 different browser sessions. Expected: drush sqlq "SELECT * FROM flag_counts" shows the matching count.
  3. Make the anonymous flaggings expire: drush sqlq "UPDATE flagging SET created = created - 1000000 WHERE uid = 0", then run drush cron. Expected: the anonymous rows are gone from the flagging table, flag_counts is unchanged, and the "Count" link type / Views flag count still show the old total.
  4. Flag and unflag the node as an authenticated user. Expected: the total count goes up by 1 and back down by 1.
  5. Regression: uncheck the new option, then repeat steps 2 and 3. Expected: the total counts are reduced like before (row deleted if it reaches 0).
anybody’s picture

AI disclosure: This comment and the draft implementation were drafted with the help of an AI assistant (Claude Code) and still need a human review.

Alternative: 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) → static Flagging::preDelete($storage, $entities), which creates the UnflaggingEvent. 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); FlagCronService passes $flag->getAnonCronPreserveCounts().
  • FlaggingStorageInterface::delete(array $entities, bool $preserveCounts = FALSE): FlaggingStorage keeps the value in a property during the deletion and resets it in finally.
  • Flagging::preDelete() reads and resets it via the internal FlaggingStorageInterface::consumePreserveCounts() and passes it to UnflaggingEvent. 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.
  • No marker methods on Flagging / FlaggingInterface.

Runtime marker (main MR)

  • Pro: the decision is tied to exactly the deleted entity objects and gone with them. A user unflag always loads a new object without the marker. No shared state, nothing to reset.
  • Pro: works through the plain EntityStorageInterface::delete(), with any storage handler, and per flagging (mixed deletions are handled correctly).
  • Pro: no signature changes of existing methods.
  • Contra: adds two methods to FlaggingInterface. Callers have to mark the entities before deleting them, which is less explicit than an argument.

Parameter (draft MR)

  • Pro: explicit at the call site: deleteMultipleFlagging($flaggings, $flag->getAnonCronPreserveCounts()).
  • Pro: no changes to the Flagging entity class or FlaggingInterface; the check in FlagCountManager is a single early return.
  • Contra: the value is still state, now on the shared storage service. It needs the try/finally reset and the "reset when read" logic in preDelete() to not leak into nested deletions, which is subtle and easy to break later.
  • Contra: API changes on existing interfaces: FlaggingStorageInterface::delete() is redeclared with an extra parameter and gets consumePreserveCounts(), and ExpiredCollectorInterface::deleteMultipleFlagging() gets a new parameter. Other implementations of these interfaces (probably rare) would break.
  • Contra: not available through EntityStorageInterface: callers need an instanceof FlaggingStorageInterface check (the collector throws a LogicException if the storage does not support it).
  • Contra: all or nothing per call, no per-flagging decision; subscribers only get the event-level preservesCounts().

Deleting directly with a DELETE query 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!

anybody’s picture

I'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!

ivnish made their first commit to this issue’s fork.

ivnish’s picture

Status: Needs review » Needs work

Thanks 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:

  1. FlaggingStorageInterface::delete() and ExpiredCollectorInterface::deleteMultipleFlagging() change their signature, and both interfaces are in released versions (ExpiredCollectorInterface since 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).
  2. consumePreserveCounts() resets the value on the first read, but core calls preDelete() once per entity class. In one delete() 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.
  3. With a storage that does not implement FlaggingStorageInterface and the option enabled, cron fails with the LogicException as 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:

  1. Option enabled: 4 flaggings, count 4.
  2. After cron: 1 flagging, count 4.
  3. After resetting the flag (unflagAllByFlag()): 0 flaggings, count 3.

FlagResetForm goes through FlagService::unflagAllByFlag(), which deletes the flaggings the regular way. FlagCountManager::decrementFlagCounts() only deletes a flag_counts row 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: the flag_counts rows of the deleted flag remain.

Suggestion: in unflagAllByFlag(), also delete the flag_counts rows of the flag, for example through a new method on FlagCountManager, and add the reset to testCronDeletionPreservesFlagCounts(). Could you add that?

AI disclosure: This review and this comment were drafted with the help of an AI assistant

anybody’s picture

Thanks @ivnish yes! Working on it!

anybody’s picture

Status: Needs work » Needs review

@ivnish thanks - hope I got you right?