Address message filter review findings
False positives
- Same-sender repeats need at least 3 words and 10 characters, so short
replies ("ok", "test") repeated within 10 minutes stay visible.
- Repeated characters needs a run of 20+ of one non-digit character;
"Noooooooo!", separators, a row of emoji and long numbers are chat.
Correctness
- Rules apply to stored messages: adding a rule hides matching messages
already in the chat, and removing or disabling one shows again what only
it was hiding. Other filter reasons are left alone. Also applied when
history is loaded.
- The filter runs after mesh dedup, inside _addChannelMessage, so each
message is evaluated and counted by the duplicate tracker once.
- Channels excluded from filtering no longer feed implicit clean examples
to the classifier.
- Unread counting and the unread anchor treat filtered messages as normal
when filtering is off for the channel.
Performance
- Classifier training runs in a background isolate (injectable trainer for
widget tests); app start-up no longer waits for it.
- Reply previews look up the quoted message through an id index instead
of scanning the channel per bubble.
- The latest-messages channel sort computes each channel's latest visible
message once.
Cleanup
- Use MessageFilterText.isStructuredPayload instead of a screen copy.
Docs: message-filter.md explains how each check works, including the
learned classifier, and drops the outdated "new messages only" limit.
This commit is contained in:
1 parent
4862966e47
commit
a9d369f42f
50 files changed
+703
-181
No files matched your search
@@ -28,6 +28,11 @@ class _SeenMessage {
|
||||
/// so a sender whose clock is far off cannot push everyone else's entries
|
||||
/// out early or keep its own around forever.
|
||||
///
|
||||
/// The same-sender rule only applies to texts of at least
|
||||
/// [sameSenderMinWords] words and [sameSenderMinLength] characters: people
|
||||
/// naturally repeat short replies ("ok", "yes", "test" when checking reach),
|
||||
/// while spam that gets re-posted is a whole sentence.
|
||||
///
|
||||
/// The cross-sender rule only applies to sentence-length texts (at least
|
||||
/// [crossSenderMinWords] words): short greetings like "Happy New Year!" or
|
||||
/// "Good morning everyone" are naturally sent by many people at once, while
|
||||
@@ -35,6 +40,8 @@ class _SeenMessage {
|
||||
class DuplicateTracker {
|
||||
DuplicateTracker({
|
||||
this.sameSenderWindow = const Duration(minutes: 10),
|
||||
this.sameSenderMinLength = 10,
|
||||
this.sameSenderMinWords = 3,
|
||||
this.crossSenderWindow = const Duration(minutes: 30),
|
||||
this.crossSenderMinSenders = 3,
|
||||
this.crossSenderMinLength = 10,
|
||||
@@ -43,6 +50,10 @@ class DuplicateTracker {
|
||||
});
|
||||
|
||||
final Duration sameSenderWindow;
|
||||
|
||||
/// Minimum length / word count for the same-sender rule (see class docs).
|
||||
final int sameSenderMinLength;
|
||||
final int sameSenderMinWords;
|
||||
final Duration crossSenderWindow;
|
||||
final int crossSenderMinSenders;
|
||||
final int crossSenderMinLength;
|
||||
@@ -106,7 +117,9 @@ class DuplicateTracker {
|
||||
senders.add(entry.sender);
|
||||
}
|
||||
}
|
||||
if (sameSender) {
|
||||
if (sameSender &&
|
||||
key.length >= sameSenderMinLength &&
|
||||
_wordCount(key) >= sameSenderMinWords) {
|
||||
result = FilterReason.duplicate;
|
||||
} else if (key.length >= crossSenderMinLength &&
|
||||
_wordCount(key) >= crossSenderMinWords &&
|
||||
|
||||
@@ -8,6 +8,9 @@ import 'duplicate_tracker.dart';
|
||||
import 'message_filter_text.dart';
|
||||
import 'ngram_spam_classifier.dart';
|
||||
|
||||
/// Trains a spam model from a job (see [MessageFilterService.new]).
|
||||
typedef SpamTrainer = Future<SpamModel?> Function(SpamTrainingJob job);
|
||||
|
||||
/// Decides whether incoming channel messages should be filtered, and owns the
|
||||
/// filter's settings, user rules and the learned classifier.
|
||||
///
|
||||
@@ -19,7 +22,9 @@ class MessageFilterService extends ChangeNotifier {
|
||||
DateTime Function()? clock,
|
||||
DuplicateTracker? duplicateTracker,
|
||||
NgramSpamClassifier? classifier,
|
||||
}) : _store = store ?? MessageFilterStore(),
|
||||
SpamTrainer? trainer,
|
||||
}) : _trainer = trainer ?? _trainInBackground,
|
||||
_store = store ?? MessageFilterStore(),
|
||||
_clock = clock ?? DateTime.now,
|
||||
_tracker = duplicateTracker ?? DuplicateTracker(),
|
||||
_classifier = classifier ?? NgramSpamClassifier();
|
||||
@@ -40,6 +45,19 @@ class MessageFilterService extends ChangeNotifier {
|
||||
/// Recent-clean entries buffered before they are written to storage.
|
||||
static const int _recentCleanSaveEvery = 10;
|
||||
|
||||
/// Runs classifier training; a background isolate by default. Widget tests
|
||||
/// pass [trainInline], since an isolate's result is never delivered under
|
||||
/// the fake clock `testWidgets` runs on.
|
||||
final SpamTrainer _trainer;
|
||||
|
||||
static Future<SpamModel?> _trainInBackground(SpamTrainingJob job) =>
|
||||
compute(NgramSpamClassifier.fitInBackground, job);
|
||||
|
||||
/// Trains on the calling isolate. For tests.
|
||||
@visibleForTesting
|
||||
static Future<SpamModel?> trainInline(SpamTrainingJob job) async =>
|
||||
NgramSpamClassifier.fitInBackground(job);
|
||||
|
||||
final MessageFilterStore _store;
|
||||
final DateTime Function() _clock;
|
||||
final DuplicateTracker _tracker;
|
||||
@@ -56,6 +74,13 @@ class MessageFilterService extends ChangeNotifier {
|
||||
/// A retrain is queued (see [_scheduleRetrainIfInactive]).
|
||||
bool _retrainPending = false;
|
||||
|
||||
/// Bumped on each retrain; a background result for an older generation is
|
||||
/// discarded because newer examples have arrived since.
|
||||
int _trainGeneration = 0;
|
||||
Future<void> _training = Future<void>.value();
|
||||
|
||||
int _rulesRevision = 0;
|
||||
|
||||
static int _idCounter = 0;
|
||||
|
||||
/// Unique-enough rule id: microsecond timestamp plus a process counter.
|
||||
@@ -66,6 +91,14 @@ class MessageFilterService extends ChangeNotifier {
|
||||
}
|
||||
|
||||
MessageFilterSettings get settings => _settings;
|
||||
|
||||
/// Changes whenever rules are added, edited or removed, so listeners can
|
||||
/// re-apply rules to messages already stored.
|
||||
int get rulesRevision => _rulesRevision;
|
||||
|
||||
/// Completes when the most recently started classifier training has been
|
||||
/// applied (or discarded).
|
||||
Future<void> get trainingSettled => _training;
|
||||
List<FilterRule> get rules => List.unmodifiable(_rules);
|
||||
int get spamExampleCount => _spamExamples.length;
|
||||
int get notSpamExampleCount => _hamExamples.length;
|
||||
@@ -89,7 +122,8 @@ class MessageFilterService extends ChangeNotifier {
|
||||
_trimToCap(_hamExamples, maxNotSpamExamples);
|
||||
_trimToCap(_recentClean, maxRecentClean);
|
||||
_unsavedCleanCount = 0;
|
||||
_retrain();
|
||||
// Training runs in the background so app start-up does not wait for it.
|
||||
unawaited(_retrain());
|
||||
_notify();
|
||||
}
|
||||
|
||||
@@ -127,24 +161,8 @@ class MessageFilterService extends ChangeNotifier {
|
||||
receivedAt: _clock(),
|
||||
);
|
||||
|
||||
for (final rule in _rules) {
|
||||
if (!rule.enabled || rule.field == FilterRuleField.text) continue;
|
||||
if (MessageFilterText.matchesSender(rule, sender)) {
|
||||
return FilterVerdict(
|
||||
reason: FilterReason.senderRule,
|
||||
detail: rule.pattern,
|
||||
);
|
||||
}
|
||||
}
|
||||
for (final rule in _rules) {
|
||||
if (!rule.enabled || rule.field == FilterRuleField.sender) continue;
|
||||
if (MessageFilterText.matchesText(rule, text)) {
|
||||
return FilterVerdict(
|
||||
reason: FilterReason.textRule,
|
||||
detail: rule.pattern,
|
||||
);
|
||||
}
|
||||
}
|
||||
final byRule = _matchRules(sender, text);
|
||||
if (byRule != null) return byRule;
|
||||
|
||||
if (_settings.repeatedCharacters &&
|
||||
MessageFilterText.hasRepeatedCharacters(text)) {
|
||||
@@ -167,10 +185,56 @@ class MessageFilterService extends ChangeNotifier {
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Remembers an unfiltered incoming message as an implicit "not spam"
|
||||
/// training example (rolling buffer of [maxRecentClean]).
|
||||
void recordClean({required String sender, required String text}) {
|
||||
if (!_settings.enabled || !_settings.learning) return;
|
||||
/// The user-rule verdict for a message already stored, or null when no
|
||||
/// enabled rule matches or [channelId] is not filtered. Unlike [evaluate]
|
||||
/// it does not record anything, so it can be re-run over stored history
|
||||
/// when the rules change.
|
||||
FilterVerdict? ruleVerdict({
|
||||
required String channelId,
|
||||
required String sender,
|
||||
required String text,
|
||||
}) {
|
||||
if (!isChannelFiltered(channelId)) return null;
|
||||
if (text.trim().isEmpty || MessageFilterText.isStructuredPayload(text)) {
|
||||
return null;
|
||||
}
|
||||
return _matchRules(sender, text);
|
||||
}
|
||||
|
||||
FilterVerdict? _matchRules(String sender, String text) {
|
||||
for (final rule in _rules) {
|
||||
if (!rule.enabled || rule.field == FilterRuleField.text) continue;
|
||||
if (MessageFilterText.matchesSender(rule, sender)) {
|
||||
return FilterVerdict(
|
||||
reason: FilterReason.senderRule,
|
||||
detail: rule.pattern,
|
||||
);
|
||||
}
|
||||
}
|
||||
for (final rule in _rules) {
|
||||
if (!rule.enabled || rule.field == FilterRuleField.sender) continue;
|
||||
if (MessageFilterText.matchesText(rule, text)) {
|
||||
return FilterVerdict(
|
||||
reason: FilterReason.textRule,
|
||||
detail: rule.pattern,
|
||||
);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Remembers an unfiltered incoming message in [channelId] as an implicit
|
||||
/// "not spam" training example (rolling buffer of [maxRecentClean]).
|
||||
///
|
||||
/// Channels excluded from filtering are skipped: the user has stopped
|
||||
/// judging them, so their unfiltered messages (spam included) say nothing
|
||||
/// about what is clean.
|
||||
void recordClean({
|
||||
required String channelId,
|
||||
required String sender,
|
||||
required String text,
|
||||
}) {
|
||||
if (!isChannelFiltered(channelId) || !_settings.learning) return;
|
||||
if (text.trim().isEmpty || MessageFilterText.isStructuredPayload(text)) {
|
||||
return;
|
||||
}
|
||||
@@ -199,9 +263,11 @@ class MessageFilterService extends ChangeNotifier {
|
||||
if (_spamExamples.length < minSpamExamplesForLearning) return;
|
||||
_retrainPending = true;
|
||||
scheduleMicrotask(() {
|
||||
_retrainPending = false;
|
||||
if (_disposed || _classifier.isTrained) return;
|
||||
_retrain();
|
||||
if (_disposed || _classifier.isTrained) {
|
||||
_retrainPending = false;
|
||||
return;
|
||||
}
|
||||
_retrain().whenComplete(() => _retrainPending = false);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -212,13 +278,14 @@ class MessageFilterService extends ChangeNotifier {
|
||||
_recentClean.removeWhere((e) => MessageFilterText.normalize(e.text) == key);
|
||||
_hamExamples.removeWhere((e) => MessageFilterText.normalize(e.text) == key);
|
||||
_addExample(_spamExamples, _example(sender, text), maxSpamExamples);
|
||||
_retrain();
|
||||
final training = _retrain();
|
||||
_notify();
|
||||
await _guardSave(() async {
|
||||
await _store.saveSpamExamples(_spamExamples);
|
||||
await _store.saveHamExamples(_hamExamples);
|
||||
await _flushRecentClean();
|
||||
});
|
||||
await training;
|
||||
}
|
||||
|
||||
/// User tapped "Not spam": store the example, exempt this text in this
|
||||
@@ -238,20 +305,22 @@ class MessageFilterService extends ChangeNotifier {
|
||||
(e) => MessageFilterText.normalize(e.text) == key,
|
||||
);
|
||||
_addExample(_hamExamples, _example(sender, text), maxNotSpamExamples);
|
||||
_retrain();
|
||||
final training = _retrain();
|
||||
_notify();
|
||||
await _guardSave(() async {
|
||||
await _store.saveSpamExamples(_spamExamples);
|
||||
await _store.saveHamExamples(_hamExamples);
|
||||
});
|
||||
await training;
|
||||
}
|
||||
|
||||
Future<void> updateSettings(MessageFilterSettings settings) async {
|
||||
final learningTurnedOn = settings.learning && !_settings.learning;
|
||||
_settings = settings;
|
||||
if (learningTurnedOn) _retrain();
|
||||
final training = learningTurnedOn ? _retrain() : null;
|
||||
_notify();
|
||||
await _guardSave(() => _store.saveSettings(_settings));
|
||||
if (training != null) await training;
|
||||
}
|
||||
|
||||
Future<void> setChannelExcluded(String channelId, bool excluded) async {
|
||||
@@ -276,6 +345,7 @@ class MessageFilterService extends ChangeNotifier {
|
||||
others.insert(index.clamp(0, others.length), rule);
|
||||
}
|
||||
_rules = others;
|
||||
_rulesRevision++;
|
||||
_notify();
|
||||
await _guardSave(() => _store.saveRules(_rules));
|
||||
}
|
||||
@@ -287,6 +357,7 @@ class MessageFilterService extends ChangeNotifier {
|
||||
return;
|
||||
}
|
||||
_rules = List.of(_rules)..[index] = rule;
|
||||
_rulesRevision++;
|
||||
_notify();
|
||||
await _guardSave(() => _store.saveRules(_rules));
|
||||
}
|
||||
@@ -295,6 +366,7 @@ class MessageFilterService extends ChangeNotifier {
|
||||
final before = _rules.length;
|
||||
_rules = _rules.where((r) => r.id != id).toList();
|
||||
if (_rules.length == before) return;
|
||||
_rulesRevision++;
|
||||
_notify();
|
||||
await _guardSave(() => _store.saveRules(_rules));
|
||||
}
|
||||
@@ -305,6 +377,7 @@ class MessageFilterService extends ChangeNotifier {
|
||||
_hamExamples = <FilterExample>[];
|
||||
_recentClean = <FilterExample>[];
|
||||
_unsavedCleanCount = 0;
|
||||
_trainGeneration++; // drop any training still running
|
||||
_classifier.reset();
|
||||
_notify();
|
||||
await _guardSave(() async {
|
||||
@@ -355,20 +428,41 @@ class MessageFilterService extends ChangeNotifier {
|
||||
if (list.length > cap) list.removeRange(0, list.length - cap);
|
||||
}
|
||||
|
||||
void _retrain() {
|
||||
/// Retrains from the current examples in a background isolate (training
|
||||
/// is up to ~700 documents x 200 SGD epochs, too slow for the UI thread).
|
||||
/// The previous model keeps scoring until the new one is ready. Completes
|
||||
/// once the result is applied, or discarded because a newer retrain or a
|
||||
/// reset started meanwhile.
|
||||
Future<void> _retrain() {
|
||||
final generation = ++_trainGeneration;
|
||||
if (_spamExamples.isEmpty) {
|
||||
_classifier.reset();
|
||||
return;
|
||||
return _training = Future<void>.value();
|
||||
}
|
||||
final job = _classifier.trainingJob(List.of(_spamExamples), [
|
||||
..._hamExamples,
|
||||
..._recentClean,
|
||||
]);
|
||||
final stopwatch = Stopwatch()..start();
|
||||
_classifier.train(_spamExamples, [..._hamExamples, ..._recentClean]);
|
||||
stopwatch.stop();
|
||||
if (stopwatch.elapsedMilliseconds > 200) {
|
||||
debugPrint(
|
||||
'MessageFilterService: classifier training took '
|
||||
'${stopwatch.elapsedMilliseconds} ms',
|
||||
);
|
||||
}
|
||||
return _training = _trainer(job)
|
||||
.then((model) {
|
||||
if (_disposed || generation != _trainGeneration) return;
|
||||
if (stopwatch.elapsedMilliseconds > 1000) {
|
||||
debugPrint(
|
||||
'MessageFilterService: classifier training took '
|
||||
'${stopwatch.elapsedMilliseconds} ms',
|
||||
);
|
||||
}
|
||||
if (model == null) {
|
||||
_classifier.reset();
|
||||
} else {
|
||||
_classifier.use(model);
|
||||
}
|
||||
_notify();
|
||||
})
|
||||
.catchError((Object e) {
|
||||
debugPrint('MessageFilterService: training failed: $e');
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _flushRecentClean() async {
|
||||
|
||||
@@ -13,7 +13,17 @@ class MessageFilterText {
|
||||
r'[^\p{L}\p{N}\s]+',
|
||||
unicode: true,
|
||||
);
|
||||
static final RegExp _repeatedChars = RegExp(r'(\S)\1{7,}', unicode: true);
|
||||
|
||||
/// Shortest run of one character that counts as repeated characters.
|
||||
static const int repeatedCharacterRun = 20;
|
||||
|
||||
// Digits are left out: long numbers (frequencies, coordinates, ids) are
|
||||
// legitimate. Shorter runs are too: "Noooooooo!", "--------" separators
|
||||
// and a row of emoji are ordinary chat.
|
||||
static final RegExp _repeatedChars = RegExp(
|
||||
'([^\\s\\p{N}])\\1{${repeatedCharacterRun - 1},}',
|
||||
unicode: true,
|
||||
);
|
||||
|
||||
static final Map<int, String> _foldMap = _buildFoldMap();
|
||||
|
||||
@@ -143,11 +153,12 @@ class MessageFilterText {
|
||||
.trim();
|
||||
}
|
||||
|
||||
/// True when the same visible character appears 8 or more times in a row.
|
||||
/// True when the same visible character appears [repeatedCharacterRun] or
|
||||
/// more times in a row (keyboard-mash floods such as "aaaaaaaaaaaaaaaaaaaa").
|
||||
///
|
||||
/// Whitespace runs are ignored (they are layout, not content).
|
||||
/// Whitespace and digit runs are ignored.
|
||||
static bool hasRepeatedCharacters(String text) {
|
||||
if (text.length < 8) return false;
|
||||
if (text.length < repeatedCharacterRun) return false;
|
||||
return _repeatedChars.hasMatch(_fold(text));
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,24 @@ import 'dart:typed_data';
|
||||
import '../../models/message_filter.dart';
|
||||
import 'message_filter_text.dart';
|
||||
|
||||
/// Weights and bias of a trained [NgramSpamClassifier]. Plain data, so
|
||||
/// training can run in a background isolate and hand the result back.
|
||||
class SpamModel {
|
||||
final Map<int, double> weights;
|
||||
final double bias;
|
||||
const SpamModel(this.weights, this.bias);
|
||||
}
|
||||
|
||||
/// Inputs for [NgramSpamClassifier.fitInBackground].
|
||||
typedef SpamTrainingJob = ({
|
||||
int epochs,
|
||||
double learningRate,
|
||||
double lambda,
|
||||
int seed,
|
||||
List<FilterExample> spam,
|
||||
List<FilterExample> ham,
|
||||
});
|
||||
|
||||
/// A sparse, L2-normalised feature vector (hashed bucket ids and values).
|
||||
class _SparseVector {
|
||||
final Int32List indices;
|
||||
@@ -143,8 +161,63 @@ class NgramSpamClassifier {
|
||||
/// Trains from scratch. Needs at least one example of each class; otherwise
|
||||
/// the classifier is left untrained (and [probability] returns 0).
|
||||
void train(List<FilterExample> spam, List<FilterExample> ham) {
|
||||
reset();
|
||||
if (spam.isEmpty || ham.isEmpty) return;
|
||||
final model = fit(
|
||||
spam,
|
||||
ham,
|
||||
epochs: epochs,
|
||||
learningRate: learningRate,
|
||||
lambda: lambda,
|
||||
seed: seed,
|
||||
);
|
||||
if (model == null) {
|
||||
reset();
|
||||
} else {
|
||||
use(model);
|
||||
}
|
||||
}
|
||||
|
||||
/// The job [fitInBackground] runs for this classifier's settings.
|
||||
SpamTrainingJob trainingJob(
|
||||
List<FilterExample> spam,
|
||||
List<FilterExample> ham,
|
||||
) => (
|
||||
epochs: epochs,
|
||||
learningRate: learningRate,
|
||||
lambda: lambda,
|
||||
seed: seed,
|
||||
spam: spam,
|
||||
ham: ham,
|
||||
);
|
||||
|
||||
/// Entry point for `compute`: trains on [job] and returns the model, or
|
||||
/// null when either class has no usable examples.
|
||||
static SpamModel? fitInBackground(SpamTrainingJob job) => fit(
|
||||
job.spam,
|
||||
job.ham,
|
||||
epochs: job.epochs,
|
||||
learningRate: job.learningRate,
|
||||
lambda: job.lambda,
|
||||
seed: job.seed,
|
||||
);
|
||||
|
||||
/// Switches to [model] (from [fit] or [fitInBackground]).
|
||||
void use(SpamModel model) {
|
||||
_weights = model.weights;
|
||||
_bias = model.bias;
|
||||
_trained = true;
|
||||
}
|
||||
|
||||
/// Pure training step: same inputs, same model. Null when either class has
|
||||
/// no usable examples.
|
||||
static SpamModel? fit(
|
||||
List<FilterExample> spam,
|
||||
List<FilterExample> ham, {
|
||||
required int epochs,
|
||||
required double learningRate,
|
||||
required double lambda,
|
||||
required int seed,
|
||||
}) {
|
||||
if (spam.isEmpty || ham.isEmpty) return null;
|
||||
|
||||
// Vectorize and remap hashed buckets to a compact local index space.
|
||||
final localIndex = <int, int>{};
|
||||
@@ -174,7 +247,7 @@ class NgramSpamClassifier {
|
||||
final n = docs.length;
|
||||
final nPos = labels.where((y) => y == 1).length;
|
||||
final nNeg = n - nPos;
|
||||
if (nPos == 0 || nNeg == 0) return;
|
||||
if (nPos == 0 || nNeg == 0) return null;
|
||||
final wPos = n / (2 * nPos);
|
||||
final wNeg = n / (2 * nNeg);
|
||||
|
||||
@@ -210,9 +283,7 @@ class NgramSpamClassifier {
|
||||
final weight = weights[local];
|
||||
if (weight != 0) compact[bucket] = weight;
|
||||
});
|
||||
_weights = compact;
|
||||
_bias = bias;
|
||||
_trained = true;
|
||||
return SpamModel(compact, bias);
|
||||
}
|
||||
|
||||
/// Probability (0..1) that the message is spam; 0 when untrained.
|
||||
|
||||
Reference in new issue
Block a user