Centralize rule feed/tag scoping in the engine and fix backlog re-apply (T5)

reapply_rules_for_user_backlog narrowed its *backlog* to the triggering
rule's feed/tag scope, but then loaded every enabled rule for the user
and ran all of them against that backlog with no per-rule scope check
— so re-applying one feed- or tag-scoped rule could also fire an
unrelated rule scoped to a different feed/tag, if it happened to match.

rule_in_scope() moves the feed/tag scope check into the engine itself
(apply_filter_rules_for_feed already computed this per-subscription via
query filters; it now just passes the tag ids and lets the engine
decide), so backlog re-apply and ingest-time dispatch can't drift into
scoping rules differently again.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
ksmithandClaude Sonnet 5 committed 2026-10-31 12:19:56 -06:00
1 parent f2ee793cf8
commit 91c0b1dd26
3 files changed
+117 -17

No files matched your search

+12 -12
View File
@@ -1,5 +1,4 @@
from celery import shared_task
from django.db.models import Q
from apps.feeds.models import Subscription
from apps.rules.engine import evaluate_rules_for_article
@@ -14,6 +13,10 @@ def apply_filter_rules_for_feed(feed_id: int, article_ids: list[int]):
FilterRules (scoped to this feed/tag or unscoped) against the given
articles. Dispatched by the fetch pipeline after new/updated articles
are committed for a feed.
Per-rule scoping is left to evaluate_rules_for_article/rule_in_scope
rather than filtered into this query, so this and the backlog
re-apply task (apps.rules.tasks) can't scope rules differently.
"""
if not article_ids:
return 0
@@ -26,24 +29,21 @@ def apply_filter_rules_for_feed(feed_id: int, article_ids: list[int]):
evaluated = 0
for subscription in subscriptions:
rules = FilterRule.objects.filter(user=subscription.user, is_enabled=True).filter(
Q(feed_id=feed_id) | Q(feed__isnull=True)
rules = list(
FilterRule.objects.filter(user=subscription.user, is_enabled=True).order_by(
"priority", "id"
)
)
subscription_tag_ids = list(
if not rules:
continue
subscription_tag_ids = set(
SubscriptionTag.objects.filter(
user=subscription.user, subscription=subscription
).values_list("tag_id", flat=True)
)
if subscription_tag_ids:
rules = rules.filter(Q(tag_id__in=subscription_tag_ids) | Q(tag__isnull=True))
else:
rules = rules.filter(tag__isnull=True)
rules = list(rules.order_by("priority", "id"))
if not rules:
continue
for article in articles:
evaluate_rules_for_article(subscription.user, article, rules)
evaluate_rules_for_article(subscription.user, article, rules, subscription_tag_ids)
evaluated += 1
return evaluated