Skip to content

Commit e8761b6

Browse files
authored
Merge pull request #350 from ThePumpingLemma/dgrochowski/notification-budget
Budget notification fan-out per person
2 parents b58042a + e4d1fb3 commit e8761b6

10 files changed

Lines changed: 448 additions & 19 deletions

File tree

‎docs/HOST_APP_GUIDE.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,8 @@ Coplan.configure do |config|
336336

337337
# Notifications (optional)
338338
config.notification_handler = ->(event, payload) { ... }
339+
config.notification_fanout_limit = 300 # nil disables the budget
340+
config.notification_fanout_window = 10.minutes # positive whole seconds or duration
339341

340342
# Analytics (optional)
341343
#
@@ -369,6 +371,36 @@ are not moved earlier when the delay shrinks; jobs that wake before the current
369371
quiet period ends reschedule for its end. Configure the same value in web and
370372
worker processes.
371373

374+
## Notification delivery budget
375+
376+
By default, one person's comments can enqueue 300 external delivery jobs per
377+
fixed ten-minute window. Each recipient costs one job per push subscription,
378+
plus one dispatch job if delivery adapters are installed. Agents share their
379+
person's budget across tokens and plans. Review notifications and events
380+
without a Coplan user bypass this budget.
381+
382+
Set `notification_fanout_limit` to a positive integer, or `nil` to disable it.
383+
Set `notification_fanout_window` to a positive whole number of seconds or a
384+
duration such as `5.minutes`. Use the same settings in web and worker processes.
385+
Changing the window starts a separate counter. The window is based on when
386+
notifications are processed, not when a comment was posted.
387+
388+
When a recipient's delivery jobs do not fit, their inbox entry is still saved,
389+
but their push and adapter delivery are skipped permanently. A warning names
390+
the person and the budget. Rejected work does not consume the remaining budget.
391+
The next window admits new work; it does not replay skipped deliveries. Jobs
392+
already queued, their retries, and the host's `notification_handler` hook are
393+
not limited. Multiple delivery adapters still count as one dispatch job.
394+
395+
The budget uses ordinary `Rails.cache` reads and writes, serialized with a lock
396+
on the person's existing database row. It does not require cache counter support.
397+
Use a shared, consistently readable cache such as Solid Cache or Redis across
398+
processes. MemoryStore budgets are process-local. NullStore bypasses the budget.
399+
Cache eviction, outages, and lock failures can relax this best-effort limit;
400+
reported failures log a warning and allow delivery rather than interrupt inbox
401+
creation. This is not a durable delivery quota or a replacement for queue capacity
402+
planning. No additional tables or migrations are required.
403+
372404
## Suggested reviewers
373405

374406
Hosts can suggest who should review a plan, for example the owners of the code

‎engine/app/models/coplan/notification.rb‎

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,11 @@ def review_notification?
2121
scope :read, -> { where.not(read_at: nil) }
2222
scope :newest_first, -> { order(created_at: :desc) }
2323

24-
after_commit :enqueue_web_push_deliveries, on: :create
25-
after_commit :enqueue_adapter_deliveries, on: :create
24+
# Who caused this notification, for Notifications::FanoutBudget. Not
25+
# stored: it only decides whether this row's deliveries go out.
26+
attr_accessor :fanout_actor_id
27+
28+
after_commit :enqueue_deliveries, on: :create
2629

2730
def read?
2831
read_at.present?
@@ -42,24 +45,21 @@ def self.ransackable_associations(auth_object = nil)
4245

4346
private
4447

45-
def enqueue_adapter_deliveries
46-
DispatchNotificationJob.perform_later(id) if Coplan.configuration.notification_delivery_handlers.any?
47-
end
48-
49-
# Fan-out to at most MAX_PER_USER most recently registered devices for
50-
# the recipient. Quietly skips when Web Push isn't configured (host hasn't
51-
# set VAPID keys) or the recipient hasn't subscribed any browsers yet.
52-
def enqueue_web_push_deliveries
53-
return unless Coplan.configuration.web_push_configured?
48+
# Web push goes to at most MAX_PER_USER most recently registered devices
49+
# for the recipient, including accounts already over the cap before it
50+
# was introduced. Quietly skips when Web Push isn't configured (host
51+
# hasn't set VAPID keys) or the recipient hasn't subscribed any browsers.
52+
def enqueue_deliveries
53+
subscriptions = Coplan.configuration.web_push_configured? ? user.web_push_subscriptions.for_delivery.to_a : []
54+
adapters = Coplan.configuration.notification_delivery_handlers.any?
55+
cost = subscriptions.size + (adapters ? 1 : 0)
56+
return if cost.zero?
57+
return unless Notifications::FanoutBudget.spend?(actor_id: fanout_actor_id, cost: cost)
5458

55-
# Bound fan-out immediately, including accounts already over the cap
56-
# before it was introduced and which haven't subscribed again yet.
57-
user.web_push_subscriptions.for_delivery.each do |subscription|
58-
WebPushDeliveryJob.perform_later(
59-
notification_id: id,
60-
subscription_id: subscription.id
61-
)
59+
subscriptions.each do |subscription|
60+
WebPushDeliveryJob.perform_later(notification_id: id, subscription_id: subscription.id)
6261
end
62+
DispatchNotificationJob.perform_later(id) if adapters
6363
end
6464
end
6565
end

‎engine/app/services/coplan/comments/process_mentions.rb‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ def call
3939
) do |n|
4040
n.plan_id = @comment.comment_thread.plan_id
4141
n.comment_thread_id = @comment.comment_thread_id
42+
n.fanout_actor_id = @comment.author_id.presence || @comment.api_token_id
4243
end
4344
notified_user_ids << user.id if notification.previously_new_record?
4445
end

‎engine/app/services/coplan/notifications/create.rb‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,21 @@ def insert_notifications
5757
plan_id: @comment_thread.plan_id,
5858
comment_thread_id: @comment_thread.id,
5959
comment_id: @comment&.id,
60-
reason: @reason
60+
reason: @reason,
61+
fanout_actor_id: fanout_actor_id
6162
)
6263
end
6364

6465
subscriber_ids
6566
end
6667

68+
# The person to charge for these deliveries. An agent's comment carries
69+
# its human in author_id; @actor_id is a token id for API writes, and
70+
# charging a token would let fresh session tokens reset the budget.
71+
def fanout_actor_id
72+
@comment&.author_id.presence || @actor_id
73+
end
74+
6775
# with_lock has reloaded the thread, so this reads committed state
6876
# rather than whatever the job loaded moments ago.
6977
def silenced?
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
module Coplan
2+
module Notifications
3+
# Best-effort admission budget for initial external delivery jobs. Inbox
4+
# rows are already committed. Cache loss or failure must not interrupt
5+
# their creation or the rest of the comment's after-commit callbacks.
6+
module FanoutBudget
7+
module_function
8+
9+
def spend?(actor_id:, cost:)
10+
limit = Coplan.configuration.notification_fanout_limit
11+
return true if limit.nil? || actor_id.blank? || cost <= 0
12+
13+
cache = Rails.cache
14+
return true if cache.is_a?(ActiveSupport::Cache::NullStore)
15+
16+
# Lock an existing row, not the cache entry: stores cannot all reserve
17+
# a missing counter atomically. Release before any delivery is enqueued.
18+
User.transaction do
19+
next true unless User.lock.where(id: actor_id).pick(:id)
20+
21+
# A request-local cache may retain a value from before another
22+
# worker's spend. Give every reservation a fresh local cache.
23+
if cache.respond_to?(:with_local_cache)
24+
cache.with_local_cache { reserve(cache, actor_id, cost, limit) }
25+
else
26+
reserve(cache, actor_id, cost, limit)
27+
end
28+
end
29+
rescue StandardError, NotImplementedError => error
30+
warn_safely("Notification fan-out budget unavailable (#{error.class}); allowing delivery")
31+
true
32+
end
33+
34+
def reserve(cache, actor_id, cost, limit)
35+
window = Coplan.configuration.notification_fanout_window
36+
slot = Time.current.to_i / window
37+
key = "coplan/notification_fanout/v2/#{actor_id}/#{window}/#{slot}"
38+
spent = cache.read(key) || 0
39+
if spent + cost > limit
40+
warn_safely("Notification fan-out budget spent for #{actor_id}: inbox only (#{spent} + #{cost} > #{limit} in #{window}s)")
41+
return false
42+
end
43+
44+
# Rejected work does not consume the remainder. A fixed expiry keeps
45+
# old windows collectible even when the person continues posting.
46+
unless cache.write(key, spent + cost, expires_at: Time.at((slot + 2) * window))
47+
warn_safely("Notification fan-out budget cache write failed; allowing delivery")
48+
end
49+
true
50+
end
51+
private_class_method :reserve
52+
53+
def warn_safely(message)
54+
Rails.logger.warn("[Coplan] #{message}")
55+
rescue StandardError
56+
# Logging must not turn an optional delivery budget into a failed comment.
57+
nil
58+
end
59+
private_class_method :warn_safely
60+
end
61+
end
62+
end

‎engine/app/views/coplan/agent_instructions/guides/comments.text.erb‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ Live-session events include an `authority` field (`principal` or `collaborator`)
5656
- Resolve requires that your principal wrote the plan or started the thread.
5757
- If you decide not to act on a comment, reply with the reason. Resolve the thread only when your principal agrees.
5858
- Each reply notifies the people in the thread. Keep replies short and useful. Do not post status updates that nobody needs.
59+
- Hosts may limit external notifications per person. Above that budget, inbox entries remain, but push and adapter notices are skipped without later catch-up. New agent tokens do not reset the person's budget.
5960

6061
## Start a thread
6162

‎engine/lib/coplan/configuration.rb‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ class Configuration
1414
attr_accessor :error_reporter
1515
attr_accessor :notification_handler
1616
attr_reader :notification_delivery_handlers
17+
# Initial external delivery jobs per person in a fixed time window.
18+
# nil disables the budget. Overflow remains in the inbox only.
19+
attr_reader :notification_fanout_limit, :notification_fanout_window
1720

1821
# Lambda invoked for every analytics event tracked via
1922
# `Coplan::Analytics.track`. Receives (event_name, payload_hash).
@@ -179,6 +182,8 @@ def initialize
179182
@error_reporter = ->(exception, context) { Rails.error.report(exception, context: context) }
180183
@notification_handler = nil
181184
@notification_delivery_handlers = []
185+
@notification_fanout_limit = 300
186+
@notification_fanout_window = 10.minutes.to_i
182187
@track_event = nil
183188
@onboarding_banner = 'Want to upload Agentic plans? Give your agent <a href="/agent-instructions">these instructions</a>.'
184189
@agent_curl_prefix = 'curl -s -H "Authorization: Bearer $TOKEN"'
@@ -206,6 +211,21 @@ def initialize
206211
MARKDOWN
207212
end
208213

214+
def notification_fanout_limit=(value)
215+
unless value.nil? || (value.is_a?(Integer) && value.positive?)
216+
raise ArgumentError, "notification_fanout_limit must be a positive integer or nil"
217+
end
218+
@notification_fanout_limit = value
219+
end
220+
221+
def notification_fanout_window=(value)
222+
unless ((value.is_a?(Numeric) && value.real?) || value.is_a?(ActiveSupport::Duration)) &&
223+
value.to_f.finite? && value.to_f >= 1 && value.to_f == value.to_i
224+
raise ArgumentError, "notification_fanout_window must be a positive whole number of seconds"
225+
end
226+
@notification_fanout_window = value.to_i
227+
end
228+
209229
def show_api_tokens?
210230
true
211231
end
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
require "rails_helper"
2+
3+
RSpec.describe Coplan::Configuration do
4+
subject(:config) { described_class.new }
5+
6+
it "defaults to 300 initial delivery jobs per ten minutes" do
7+
expect(config.notification_fanout_limit).to eq(300)
8+
expect(config.notification_fanout_window).to eq(600)
9+
end
10+
11+
it "accepts a host limit, a whole-second duration, and disabling with nil" do
12+
config.notification_fanout_limit = 50
13+
config.notification_fanout_window = 2.minutes
14+
expect(config.notification_fanout_limit).to eq(50)
15+
expect(config.notification_fanout_window).to eq(120)
16+
config.notification_fanout_limit = nil
17+
expect(config.notification_fanout_limit).to be_nil
18+
end
19+
20+
it "rejects invalid limits before the host starts serving requests" do
21+
[ 0, -1, 1.5, "300", false ].each do |value|
22+
expect { config.notification_fanout_limit = value }.to raise_error(ArgumentError)
23+
end
24+
expect(config.notification_fanout_limit).to eq(300)
25+
end
26+
27+
it "rejects invalid windows before the host starts serving requests" do
28+
[ nil, 0, -1, 0.5.seconds, Float::INFINITY, Float::NAN, Complex(1, 2), "600" ].each do |value|
29+
expect { config.notification_fanout_window = value }.to raise_error(ArgumentError)
30+
end
31+
expect(config.notification_fanout_window).to eq(600)
32+
end
33+
end
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
require "rails_helper"
2+
require "tmpdir"
3+
require "timeout"
4+
5+
RSpec.describe Coplan::Notifications::FanoutBudget, "concurrent accounting" do
6+
self.use_transactional_tests = false
7+
8+
let!(:actor) { create(:coplan_user) }
9+
10+
around do |example|
11+
previous_cache = Rails.cache
12+
previous_limit = Coplan.configuration.notification_fanout_limit
13+
Coplan.configuration.notification_fanout_limit = 6
14+
Dir.mktmpdir("coplan-fanout") do |directory|
15+
Rails.cache = ActiveSupport::Cache::FileStore.new(directory)
16+
freeze_time { example.run }
17+
end
18+
ensure
19+
Rails.cache = previous_cache
20+
Coplan.configuration.notification_fanout_limit = previous_limit
21+
end
22+
23+
after { actor.destroy! }
24+
25+
it "serializes the first spend before reading a missing cache entry" do
26+
entered = Queue.new
27+
release = Queue.new
28+
waiting = Queue.new
29+
cache = Rails.cache
30+
first_id = nil
31+
allow(cache).to receive(:read).and_wrap_original do |method, *args|
32+
if Thread.current.object_id == first_id
33+
entered << true
34+
Timeout.timeout(10) { release.pop }
35+
end
36+
method.call(*args)
37+
end
38+
39+
first = Thread.new do
40+
first_id = Thread.current.object_id
41+
ActiveRecord::Base.connection_pool.with_connection do
42+
described_class.spend?(actor_id: actor.id, cost: 4)
43+
end
44+
end
45+
Timeout.timeout(10) { entered.pop }
46+
# The second worker reaches its real SQL lock while the first still has
47+
# not written the new key. A read/write without the row lock would let
48+
# both workers spend four against a six-delivery budget.
49+
second = Thread.new do
50+
ActiveRecord::Base.connection_pool.with_connection do |connection|
51+
# Signal just before executing the lock query, not after it completes.
52+
allow(connection).to receive(:log).and_wrap_original do |method, sql, *args, **kwargs, &block|
53+
waiting << true if sql.match?(/coplan_users.*FOR UPDATE/i)
54+
method.call(sql, *args, **kwargs, &block)
55+
end
56+
described_class.spend?(actor_id: actor.id, cost: 4)
57+
end
58+
end
59+
Timeout.timeout(10) { waiting.pop }
60+
release << true
61+
62+
expect(first.join(20)).to eq(first)
63+
expect(second.join(20)).to eq(second)
64+
expect([ first.value, second.value ]).to eq([ true, false ])
65+
expect(described_class.spend?(actor_id: actor.id, cost: 2)).to be(true)
66+
expect(described_class.spend?(actor_id: actor.id, cost: 1)).to be(false)
67+
ensure
68+
release << true if release
69+
[ first, second ].compact.each do |worker|
70+
worker.kill unless worker.join(5)
71+
worker.join
72+
end
73+
end
74+
75+
it "ignores an outer request's stale local value" do
76+
# Use Rails' real local-cache strategy over a shared backing store.
77+
Rails.cache.singleton_class.prepend(ActiveSupport::Cache::Strategy::LocalCache)
78+
window = Coplan.configuration.notification_fanout_window
79+
slot = Time.current.to_i / window
80+
key = "coplan/notification_fanout/v2/#{actor.id}/#{window}/#{slot}"
81+
Rails.cache.with_local_cache do
82+
Rails.cache.write(key, 0)
83+
Rails.cache.with_local_cache { Rails.cache.write(key, 6) }
84+
expect(Rails.cache.read(key)).to eq(0)
85+
expect(described_class.spend?(actor_id: actor.id, cost: 1)).to be(false)
86+
end
87+
end
88+
end

0 commit comments

Comments
 (0)