Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions docs/HOST_APP_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,8 @@ Coplan.configure do |config|

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

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

## Notification delivery budget

By default, one person's comments can enqueue 300 external delivery jobs per
fixed ten-minute window. Each recipient costs one job per push subscription,
plus one dispatch job if delivery adapters are installed. Agents share their
person's budget across tokens and plans. Review notifications and events
without a Coplan user bypass this budget.

Set `notification_fanout_limit` to a positive integer, or `nil` to disable it.
Set `notification_fanout_window` to a positive whole number of seconds or a
duration such as `5.minutes`. Use the same settings in web and worker processes.
Changing the window starts a separate counter. The window is based on when
notifications are processed, not when a comment was posted.

When a recipient's delivery jobs do not fit, their inbox entry is still saved,
but their push and adapter delivery are skipped permanently. A warning names
the person and the budget. Rejected work does not consume the remaining budget.
The next window admits new work; it does not replay skipped deliveries. Jobs
already queued, their retries, and the host's `notification_handler` hook are
not limited. Multiple delivery adapters still count as one dispatch job.

The budget uses ordinary `Rails.cache` reads and writes, serialized with a lock
on the person's existing database row. It does not require cache counter support.
Use a shared, consistently readable cache such as Solid Cache or Redis across
processes. MemoryStore budgets are process-local. NullStore bypasses the budget.
Cache eviction, outages, and lock failures can relax this best-effort limit;
reported failures log a warning and allow delivery rather than interrupt inbox
creation. This is not a durable delivery quota or a replacement for queue capacity
planning. No additional tables or migrations are required.

## Suggested reviewers

Hosts can suggest who should review a plan, for example the owners of the code
Expand Down
36 changes: 18 additions & 18 deletions engine/app/models/coplan/notification.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,11 @@ def review_notification?
scope :read, -> { where.not(read_at: nil) }
scope :newest_first, -> { order(created_at: :desc) }

after_commit :enqueue_web_push_deliveries, on: :create
after_commit :enqueue_adapter_deliveries, on: :create
# Who caused this notification, for Notifications::FanoutBudget. Not
# stored: it only decides whether this row's deliveries go out.
attr_accessor :fanout_actor_id

after_commit :enqueue_deliveries, on: :create

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

private

def enqueue_adapter_deliveries
DispatchNotificationJob.perform_later(id) if Coplan.configuration.notification_delivery_handlers.any?
end

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

# Bound fan-out immediately, including accounts already over the cap
# before it was introduced and which haven't subscribed again yet.
user.web_push_subscriptions.for_delivery.each do |subscription|
WebPushDeliveryJob.perform_later(
notification_id: id,
subscription_id: subscription.id
)
subscriptions.each do |subscription|
WebPushDeliveryJob.perform_later(notification_id: id, subscription_id: subscription.id)
end
DispatchNotificationJob.perform_later(id) if adapters
end
end
end
1 change: 1 addition & 0 deletions engine/app/services/coplan/comments/process_mentions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def call
) do |n|
n.plan_id = @comment.comment_thread.plan_id
n.comment_thread_id = @comment.comment_thread_id
n.fanout_actor_id = @comment.author_id.presence || @comment.api_token_id
end
notified_user_ids << user.id if notification.previously_new_record?
end
Expand Down
10 changes: 9 additions & 1 deletion engine/app/services/coplan/notifications/create.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,21 @@ def insert_notifications
plan_id: @comment_thread.plan_id,
comment_thread_id: @comment_thread.id,
comment_id: @comment&.id,
reason: @reason
reason: @reason,
fanout_actor_id: fanout_actor_id
)
end

subscriber_ids
end

# The person to charge for these deliveries. An agent's comment carries
# its human in author_id; @actor_id is a token id for API writes, and
# charging a token would let fresh session tokens reset the budget.
def fanout_actor_id
@comment&.author_id.presence || @actor_id
end

# with_lock has reloaded the thread, so this reads committed state
# rather than whatever the job loaded moments ago.
def silenced?
Expand Down
62 changes: 62 additions & 0 deletions engine/app/services/coplan/notifications/fanout_budget.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
module Coplan
module Notifications
# Best-effort admission budget for initial external delivery jobs. Inbox
# rows are already committed. Cache loss or failure must not interrupt
# their creation or the rest of the comment's after-commit callbacks.
module FanoutBudget
module_function

def spend?(actor_id:, cost:)
limit = Coplan.configuration.notification_fanout_limit
return true if limit.nil? || actor_id.blank? || cost <= 0

cache = Rails.cache
return true if cache.is_a?(ActiveSupport::Cache::NullStore)

# Lock an existing row, not the cache entry: stores cannot all reserve
# a missing counter atomically. Release before any delivery is enqueued.
User.transaction do
next true unless User.lock.where(id: actor_id).pick(:id)

# A request-local cache may retain a value from before another
# worker's spend. Give every reservation a fresh local cache.
if cache.respond_to?(:with_local_cache)
cache.with_local_cache { reserve(cache, actor_id, cost, limit) }
else
reserve(cache, actor_id, cost, limit)
end
end
rescue StandardError, NotImplementedError => error
warn_safely("Notification fan-out budget unavailable (#{error.class}); allowing delivery")
true
end

def reserve(cache, actor_id, cost, limit)
window = Coplan.configuration.notification_fanout_window
slot = Time.current.to_i / window
key = "coplan/notification_fanout/v2/#{actor_id}/#{window}/#{slot}"
spent = cache.read(key) || 0
if spent + cost > limit
warn_safely("Notification fan-out budget spent for #{actor_id}: inbox only (#{spent} + #{cost} > #{limit} in #{window}s)")
return false
end

# Rejected work does not consume the remainder. A fixed expiry keeps
# old windows collectible even when the person continues posting.
unless cache.write(key, spent + cost, expires_at: Time.at((slot + 2) * window))
warn_safely("Notification fan-out budget cache write failed; allowing delivery")
end
true
end
private_class_method :reserve

def warn_safely(message)
Rails.logger.warn("[Coplan] #{message}")
rescue StandardError
# Logging must not turn an optional delivery budget into a failed comment.
nil
end
private_class_method :warn_safely
end
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ Live-session events include an `authority` field (`principal` or `collaborator`)
- Resolve requires that your principal wrote the plan or started the thread.
- If you decide not to act on a comment, reply with the reason. Resolve the thread only when your principal agrees.
- Each reply notifies the people in the thread. Keep replies short and useful. Do not post status updates that nobody needs.
- 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.

## Start a thread

Expand Down
20 changes: 20 additions & 0 deletions engine/lib/coplan/configuration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ class Configuration
attr_accessor :error_reporter
attr_accessor :notification_handler
attr_reader :notification_delivery_handlers
# Initial external delivery jobs per person in a fixed time window.
# nil disables the budget. Overflow remains in the inbox only.
attr_reader :notification_fanout_limit, :notification_fanout_window

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

def notification_fanout_limit=(value)
unless value.nil? || (value.is_a?(Integer) && value.positive?)
raise ArgumentError, "notification_fanout_limit must be a positive integer or nil"
end
@notification_fanout_limit = value
end

def notification_fanout_window=(value)
unless ((value.is_a?(Numeric) && value.real?) || value.is_a?(ActiveSupport::Duration)) &&
value.to_f.finite? && value.to_f >= 1 && value.to_f == value.to_i
raise ArgumentError, "notification_fanout_window must be a positive whole number of seconds"
end
@notification_fanout_window = value.to_i
end

def show_api_tokens?
true
end
Expand Down
33 changes: 33 additions & 0 deletions spec/lib/coplan/configuration_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
require "rails_helper"

RSpec.describe Coplan::Configuration do
subject(:config) { described_class.new }

it "defaults to 300 initial delivery jobs per ten minutes" do
expect(config.notification_fanout_limit).to eq(300)
expect(config.notification_fanout_window).to eq(600)
end

it "accepts a host limit, a whole-second duration, and disabling with nil" do
config.notification_fanout_limit = 50
config.notification_fanout_window = 2.minutes
expect(config.notification_fanout_limit).to eq(50)
expect(config.notification_fanout_window).to eq(120)
config.notification_fanout_limit = nil
expect(config.notification_fanout_limit).to be_nil
end

it "rejects invalid limits before the host starts serving requests" do
[ 0, -1, 1.5, "300", false ].each do |value|
expect { config.notification_fanout_limit = value }.to raise_error(ArgumentError)
end
expect(config.notification_fanout_limit).to eq(300)
end

it "rejects invalid windows before the host starts serving requests" do
[ nil, 0, -1, 0.5.seconds, Float::INFINITY, Float::NAN, Complex(1, 2), "600" ].each do |value|
expect { config.notification_fanout_window = value }.to raise_error(ArgumentError)
end
expect(config.notification_fanout_window).to eq(600)
end
end
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
require "rails_helper"
require "tmpdir"
require "timeout"

RSpec.describe Coplan::Notifications::FanoutBudget, "concurrent accounting" do
self.use_transactional_tests = false

let!(:actor) { create(:coplan_user) }

around do |example|
previous_cache = Rails.cache
previous_limit = Coplan.configuration.notification_fanout_limit
Coplan.configuration.notification_fanout_limit = 6
Dir.mktmpdir("coplan-fanout") do |directory|
Rails.cache = ActiveSupport::Cache::FileStore.new(directory)
freeze_time { example.run }
end
ensure
Rails.cache = previous_cache
Coplan.configuration.notification_fanout_limit = previous_limit
end

after { actor.destroy! }

it "serializes the first spend before reading a missing cache entry" do
entered = Queue.new
release = Queue.new
waiting = Queue.new
cache = Rails.cache
first_id = nil
allow(cache).to receive(:read).and_wrap_original do |method, *args|
if Thread.current.object_id == first_id
entered << true
Timeout.timeout(10) { release.pop }
end
method.call(*args)
end

first = Thread.new do
first_id = Thread.current.object_id
ActiveRecord::Base.connection_pool.with_connection do
described_class.spend?(actor_id: actor.id, cost: 4)
end
end
Timeout.timeout(10) { entered.pop }
# The second worker reaches its real SQL lock while the first still has
# not written the new key. A read/write without the row lock would let
# both workers spend four against a six-delivery budget.
second = Thread.new do
ActiveRecord::Base.connection_pool.with_connection do |connection|
# Signal just before executing the lock query, not after it completes.
allow(connection).to receive(:log).and_wrap_original do |method, sql, *args, **kwargs, &block|
waiting << true if sql.match?(/coplan_users.*FOR UPDATE/i)
method.call(sql, *args, **kwargs, &block)
end
described_class.spend?(actor_id: actor.id, cost: 4)
end
end
Timeout.timeout(10) { waiting.pop }
release << true

expect(first.join(20)).to eq(first)
expect(second.join(20)).to eq(second)
expect([ first.value, second.value ]).to eq([ true, false ])
expect(described_class.spend?(actor_id: actor.id, cost: 2)).to be(true)
expect(described_class.spend?(actor_id: actor.id, cost: 1)).to be(false)
ensure
release << true if release
[ first, second ].compact.each do |worker|
worker.kill unless worker.join(5)
worker.join
end
end

it "ignores an outer request's stale local value" do
# Use Rails' real local-cache strategy over a shared backing store.
Rails.cache.singleton_class.prepend(ActiveSupport::Cache::Strategy::LocalCache)
window = Coplan.configuration.notification_fanout_window
slot = Time.current.to_i / window
key = "coplan/notification_fanout/v2/#{actor.id}/#{window}/#{slot}"
Rails.cache.with_local_cache do
Rails.cache.write(key, 0)
Rails.cache.with_local_cache { Rails.cache.write(key, 6) }
expect(Rails.cache.read(key)).to eq(0)
expect(described_class.spend?(actor_id: actor.id, cost: 1)).to be(false)
end
end
end
Loading
Loading