Cut the spam filter's per-message cost for the perf floor

pipeline.publicIngest fell to 138 msg/s on CI (floor 2400). Its
benchmark sentences drew 7 words from one 36-word list, so 31% of pairs
shared enough trigrams for full comparisons; natural chat lines share
that much in 0.6% of pairs. The benchmark now uses made-up words, which
behave like chat between different people.

The filter itself also got cheaper, with identical verdicts:
- an inverted trigram index replaces 200 trigram merges per message
- the repeated-character check gives up on a shift once it can't reach
  the threshold
- the diagonal bound indexes the message once, lazily, not every stored
  text
- live, in-order messages reuse the bucket state after the newest entry
  instead of replaying the sender's timeline
- trigram hashing, sorting and the hot loops read buffers directly

Locally the ingest benchmark goes from 2580 to 8400 msg/s (13600 with
the filter off).
This commit is contained in:
callebtc 2026-10-26 00:15:18 +01:00
parent a797867e47
commit 0ae6905d1a
5 changed files with 218 additions and 30 deletions

View File

@ -86,6 +86,36 @@ enum RepetitionDetector {
return best
}
/// Whether `selfSimilarity(text) >= threshold`, giving up on each shift as
/// soon as its mismatches rule it out. Ordinary text fails within a few
/// characters per shift, where `selfSimilarity` scans every one.
static func selfSimilarity(_ text: [Int], reaches threshold: Double) -> Bool {
let n = text.count
guard n >= 2 else { return threshold <= 0 }
// Runs for every incoming message, so it reads the buffer directly.
return text.withUnsafeBufferPointer { text in
for lag in 1...(n / 2) {
let overlap = n - lag
var mismatches = 0
var possible = true
var i = 0
while i < overlap {
if text[i] != text[i + lag] {
mismatches += 1
// The best this shift can still score, compared as the score itself is.
if Double(overlap - mismatches) / Double(overlap) < threshold {
possible = false
break
}
}
i += 1
}
if possible { return true }
}
return false
}
}
/// One diagonal of the cross-correlation: `b[j]` lined up under `a[j + shift]`.
struct Peak: Equatable {
let shift: Int
@ -220,12 +250,44 @@ enum RepetitionDetector {
/// Distinct character trigrams as sorted hashes, for a cheap pre-check before `align`.
static func trigrams(_ text: [Int]) -> [Int] {
guard text.count >= 3 else { return [] }
var hashes = Set<Int>()
for i in 0..<(text.count - 2) {
let pair: Int = text[i] * 31 + text[i + 1]
hashes.insert(pair * 31 + text[i + 2])
let count = text.count - 2
var hashes = [Int](unsafeUninitializedCapacity: count) { hashes, initialized in
text.withUnsafeBufferPointer { text in
for i in 0..<count {
let pair: Int = text[i] &* 31 &+ text[i + 1]
hashes[i] = pair &* 31 &+ text[i + 2]
}
}
initialized = count
}
return hashes.sorted()
// Runs for every incoming message: an insertion sort over the buffer
// beats the generic sort on chat-length lists, above all in debug builds.
if count <= 64 {
hashes.withUnsafeMutableBufferPointer { hashes in
for i in 1..<max(1, hashes.count) {
let value = hashes[i]
var j = i - 1
while j >= 0 && hashes[j] > value {
hashes[j + 1] = hashes[j]
j -= 1
}
hashes[j + 1] = value
}
}
} else {
hashes.sort()
}
// Drop repeats in place; sorting brought them together.
let unique: Int = hashes.withUnsafeMutableBufferPointer { hashes in
var unique = 0
for i in 0..<hashes.count where unique == 0 || hashes[unique - 1] != hashes[i] {
hashes[unique] = hashes[i]
unique += 1
}
return unique
}
hashes.removeLast(hashes.count - unique)
return hashes
}
/// Shared trigrams over the larger trigram set. Near-copies share most of

View File

@ -50,7 +50,6 @@ final class SpamFilter: @unchecked Sendable {
let time: TimeInterval
let text: [Int]
let trigrams: [Int]
let positions: [Int: [Int]]
}
private struct SharedEntry {
@ -72,6 +71,11 @@ final class SpamFilter: @unchecked Sendable {
private var activity: UInt64 = 0
/// Recent texts from every sender, for the cross-user repeat check.
private var recentTexts: [SharedEntry] = []
/// Sequence number of `recentTexts[0]`; entries are numbered in arrival order.
private var recentTextsStart = 0
/// Trigram hash to the sequence numbers of the recent texts containing it,
/// oldest first, so a message only meets the texts it shares trigrams with.
private var recentTrigrams: [Int: [Int]] = [:]
private var verdicts: [String: SpamVerdict] = [:]
private var verdictOrder: [String] = []
private var verdictHead = 0
@ -146,7 +150,8 @@ final class SpamFilter: @unchecked Sendable {
let now = clock().timeIntervalSince1970
let oldestTrusted = now - config.maxBackdate
let time = min(max(timestamp.timeIntervalSince1970, oldestTrusted), now)
var state = senders[senderKey] ?? SenderState(
// Taken out while it changes, so its arrays aren't copied on write.
var state = senders.removeValue(forKey: senderKey) ?? SenderState(
rate: TokenBucketSchedule(buckets: [config.messageBucket, config.characterBucket, config.linkBucket]),
lastActive: 0
)
@ -175,10 +180,7 @@ final class SpamFilter: @unchecked Sendable {
state.history.removeFirst(state.history.count - repetition.historySize)
}
if text.count >= repetition.crossUserMinLength {
recentTexts.append(SharedEntry(senderKey: senderKey, fingerprint: fingerprint))
if recentTexts.count > repetition.crossUserHistorySize {
recentTexts.removeFirst(recentTexts.count - repetition.crossUserHistorySize)
}
rememberRecentText(SharedEntry(senderKey: senderKey, fingerprint: fingerprint), limit: repetition.crossUserHistorySize)
}
} else {
verdict = admitRate(&state, content: content, time: time, isText: isText)
@ -214,6 +216,8 @@ final class SpamFilter: @unchecked Sendable {
private func clearLocked() {
senders.removeAll()
recentTexts.removeAll()
recentTextsStart = 0
recentTrigrams.removeAll()
verdicts.removeAll()
verdictOrder.removeAll()
verdictHead = 0
@ -222,7 +226,7 @@ final class SpamFilter: @unchecked Sendable {
private func hasRepeatedCharacters(_ text: [Int], config: RepetitionConfig) -> Bool {
text.count >= config.minRepeatedCharactersLength &&
RepetitionDetector.selfSimilarity(text) >= config.repeatedCharactersThreshold
RepetitionDetector.selfSimilarity(text, reaches: config.repeatedCharactersThreshold)
}
private func makeFingerprint(_ text: [Int], time: TimeInterval, config: RepetitionConfig) -> Fingerprint {
@ -230,8 +234,7 @@ final class SpamFilter: @unchecked Sendable {
return Fingerprint(
time: time,
text: compared,
trigrams: RepetitionDetector.trigrams(compared),
positions: RepetitionDetector.positions(compared)
trigrams: RepetitionDetector.trigrams(compared)
)
}
@ -239,7 +242,10 @@ final class SpamFilter: @unchecked Sendable {
guard length >= config.minRepeatedMessageLength else { return false }
// At most `historySize` comparisons, so no budget is needed.
var budget = ComparisonBudget(comparisons: .max, alignments: .max)
let copies = state.history.filter { isNearCopy($0, message, config: config, budget: &budget) }.count
let copies = state.history.filter { earlier in
let overlap = RepetitionDetector.trigramOverlap(earlier.trigrams, message.trigrams)
return isNearCopy(earlier, message, sharedTrigrams: overlap, config: config, budget: &budget)
}.count
return copies > config.allowedRepeats
}
@ -252,42 +258,80 @@ final class SpamFilter: @unchecked Sendable {
comparisons: config.crossUserMaxComparisons,
alignments: config.crossUserMaxAlignments
)
for entry in recentTexts.reversed() where entry.senderKey != senderKey {
// Shared distinct trigrams per recent text (by position), from the
// index: the same counts `trigramOverlap` would find, without visiting
// unrelated texts.
var shared = [Int](repeating: 0, count: recentTexts.count)
shared.withUnsafeMutableBufferPointer { shared in
for trigram in message.trigrams {
guard let sequences = recentTrigrams[trigram] else { continue }
for sequence in sequences { shared[sequence - recentTextsStart] += 1 }
}
}
// Newest first. A zero threshold admits texts that share nothing.
for index in shared.indices.reversed() where shared[index] > 0 || config.minSharedTrigrams <= 0 {
let entry = recentTexts[index]
guard entry.senderKey != senderKey else { continue }
guard !budget.isSpent else { break }
guard isNearCopy(entry.fingerprint, message, config: config, budget: &budget) else { continue }
let larger = max(entry.fingerprint.trigrams.count, message.trigrams.count)
let overlap = larger == 0 ? 1 : Double(shared[index]) / Double(larger)
guard isNearCopy(entry.fingerprint, message, sharedTrigrams: overlap, config: config, budget: &budget) else { continue }
copies += 1
if copies > config.crossUserAllowedRepeats { return true }
}
return false
}
private func rememberRecentText(_ entry: SharedEntry, limit: Int) {
let sequence = recentTextsStart + recentTexts.count
recentTexts.append(entry)
for trigram in entry.fingerprint.trigrams { recentTrigrams[trigram, default: []].append(sequence) }
while recentTexts.count > limit {
let oldest = recentTexts.removeFirst()
// The oldest text holds the smallest sequence number in each of its lists.
for trigram in oldest.fingerprint.trigrams {
guard var sequences = recentTrigrams[trigram] else { continue }
sequences.removeFirst()
recentTrigrams[trigram] = sequences.isEmpty ? nil : sequences
}
recentTextsStart += 1
}
}
/// Work left for comparing one message: pairs that get past the trigram
/// check, and of those, pairs that need the full alignment.
private struct ComparisonBudget {
var comparisons: Int
var alignments: Int
/// The message's character positions, built when a bound first needs them.
var positions: [Int: [Int]]?
var isSpent: Bool { comparisons <= 0 || alignments <= 0 }
}
/// The cheap checks (time, length, shared trigrams) cost nothing from
/// `budget`; the diagonal bound spends a comparison and `align` an alignment.
/// The cheap checks (time, length, `sharedTrigrams`, their
/// `trigramOverlap`) cost nothing from `budget`; the diagonal bound spends
/// a comparison and `align` an alignment.
private func isNearCopy(
_ earlier: Fingerprint,
_ message: Fingerprint,
sharedTrigrams: Double,
config: RepetitionConfig,
budget: inout ComparisonBudget
) -> Bool {
let longer = max(earlier.text.count, message.text.count)
guard abs(earlier.time - message.time) <= config.historyWindow,
lengthsCanMatch(earlier.text.count, message.text.count, config: config),
RepetitionDetector.trigramOverlap(earlier.trigrams, message.trigrams) >= config.minSharedTrigrams
sharedTrigrams >= config.minSharedTrigrams
else { return false }
budget.comparisons -= 1
let positions = budget.positions ?? RepetitionDetector.positions(message.text)
budget.positions = positions
// The bound is symmetric, so it indexes the message, not each earlier text.
guard Double(RepetitionDetector.alignmentUpperBound(
message.text,
earlier.text,
positionsInB: earlier.positions,
message.text,
positionsInB: positions,
maxPeaks: config.maxAlignmentPeaks
)) / Double(longer) >= config.repeatedMessageSimilarity
else { return false }

View File

@ -33,10 +33,15 @@ struct TokenBucketSchedule {
private var entries: [Entry] = []
private var checkpoint: TimeInterval?
private var checkpointTokens: [Double]
/// Tokens left after the newest entry, as a replay would compute them, so
/// an in-order message (live traffic) is checked without a replay.
private var tailTokens: [Double]
private var tailTime: TimeInterval?
init(buckets: [TokenBucketConfig]) {
self.buckets = buckets
self.checkpointTokens = buckets.map(\.capacity)
self.tailTokens = checkpointTokens
}
/// Admits and records the message when every bucket can pay `costs` at `time`.
@ -48,6 +53,19 @@ struct TokenBucketSchedule {
while insertAt > 0 && entries[insertAt - 1].time > time { insertAt -= 1 }
let candidate = Entry(time: time, costs: costs)
if insertAt == entries.count {
var tokens = tailTokens
refill(&tokens, from: tailTime, to: time)
for b in buckets.indices {
tokens[b] -= costs[b]
if tokens[b] < -Self.epsilon { return b }
}
entries.append(candidate)
tailTokens = tokens
tailTime = time
return nil
}
var tokens = checkpointTokens
var last = checkpoint
for i in 0...entries.count {
@ -67,6 +85,10 @@ struct TokenBucketSchedule {
}
}
entries.insert(candidate, at: insertAt)
// The replay ran through the newest entry; folding old entries into the
// checkpoint later repeats the same steps, so this stays exact.
tailTokens = tokens
tailTime = last
return nil
}

View File

@ -469,17 +469,23 @@ final class PerformanceBaselineTests: XCTestCase {
reportThroughput("pipeline.publicIngest", samples: samples, operations: messageCount, unit: "messages")
}
/// A deterministic sentence of unrelated words, different for every `seed`.
/// A deterministic sentence of made-up words, different for every `seed`.
/// Like real chat between different people, two of them rarely share
/// enough trigrams to need the spam filter's full comparison; words drawn
/// from one small list would, which measures the filter's worst case
/// rather than ordinary ingest.
private static func perfSentence(_ seed: Int) -> String {
let words = ["market", "river", "lantern", "bicycle", "orange", "window", "garden", "quiet", "station",
"morning", "paper", "copper", "valley", "thunder", "pocket", "silver", "harbor", "candle",
"meadow", "button", "ladder", "violet", "engine", "basket", "cloud", "pepper", "forest",
"mirror", "saddle", "tunnel", "anchor", "biscuit", "canyon", "dragon", "ember", "falcon"]
var state = UInt64(seed) &* 0x9E37_79B9_7F4A_7C15 &+ 1
return (0..<7).map { _ in
func next(_ bound: Int) -> Int {
state = state &* 6364136223846793005 &+ 1442695040888963407
return words[Int((state >> 33) % UInt64(words.count))]
}.joined(separator: " ")
return Int((state >> 33) % UInt64(bound))
}
let words: [String] = (0..<7).map { _ in
let length = 2 + next(6)
let letters: [Character] = (0..<length).map { _ in Character(Unicode.Scalar(UInt8(97 + next(26)))) }
return String(letters)
}
return words.joined(separator: " ")
}
// MARK: - 7. ConversationStore append (to-be architecture)

View File

@ -449,6 +449,60 @@ import Testing
}
}
@Test func bucketShortcutForInOrderMessagesMatchesAFullReplay() {
// Reference: replay every admitted message from full buckets each time.
let configs = [TokenBucketConfig(capacity: 3, refillPerSecond: 0.2), TokenBucketConfig(capacity: 50, refillPerSecond: 2)]
func replayAdmits(_ admitted: [(TimeInterval, [Double])], _ time: TimeInterval, _ costs: [Double]) -> Int? {
let timeline = (admitted + [(time, costs)]).enumerated().sorted { a, b in
a.element.0 != b.element.0 ? a.element.0 < b.element.0 : a.offset < b.offset
}.map(\.element)
var tokens = configs.map(\.capacity)
var last: TimeInterval?
for (t, c) in timeline {
if let last, t > last {
for b in configs.indices { tokens[b] = min(configs[b].capacity, tokens[b] + (t - last) * configs[b].refillPerSecond) }
}
last = t
for b in configs.indices {
tokens[b] -= c[b]
if tokens[b] < -1e-9 { return b }
}
}
return nil
}
var rng = SplitMix64(seed: 9)
for _ in 0..<40 {
var schedule = TokenBucketSchedule(buckets: configs)
var admitted: [(TimeInterval, [Double])] = []
var clock: TimeInterval = 0
for _ in 0..<40 {
clock += Double(Int.random(in: 0...6, using: &rng))
// Mostly live traffic, sometimes a backfilled message from earlier.
let time = Bool.random(using: &rng) && Int.random(in: 0..<4, using: &rng) == 0
? max(0, clock - Double(Int.random(in: 1...20, using: &rng)))
: clock
let costs: [Double] = [1, Double(Int.random(in: 1...30, using: &rng))]
let expected = replayAdmits(admitted, time, costs)
#expect(schedule.tryAdmit(at: time, costs: costs) == expected)
if expected == nil { admitted.append((time, costs)) }
}
}
}
@Test func earlyExitSelfSimilarityAgreesWithTheFullScore() {
var rng = SplitMix64(seed: 5)
for alphabet in [1, 2, 3, 26] {
for _ in 0..<80 {
let length: Int = Int.random(in: 0...90, using: &rng)
let text: [Int] = (0..<length).map { _ -> Int in 97 + Int.random(in: 0..<alphabet, using: &rng) }
for threshold in [0.5, 0.85, 1.0] {
let full = RepetitionDetector.selfSimilarity(text) >= threshold
#expect(RepetitionDetector.selfSimilarity(text, reaches: threshold) == full)
}
}
}
}
@Test func recentCopiesAreCaughtBehindAFloodOfLookAlikes() {
let now = Date(timeIntervalSince1970: 1_000_000)
var config = SpamFilterConfig()