diff --git a/docs/HOST_APP_GUIDE.md b/docs/HOST_APP_GUIDE.md index cdbab7fc..3e5b5dd0 100644 --- a/docs/HOST_APP_GUIDE.md +++ b/docs/HOST_APP_GUIDE.md @@ -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) # @@ -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 diff --git a/engine/app/models/coplan/notification.rb b/engine/app/models/coplan/notification.rb index 2f1b91aa..d33b77f9 100644 --- a/engine/app/models/coplan/notification.rb +++ b/engine/app/models/coplan/notification.rb @@ -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? @@ -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 diff --git a/engine/app/services/coplan/comments/process_mentions.rb b/engine/app/services/coplan/comments/process_mentions.rb index 7f3ba04e..973669e7 100644 --- a/engine/app/services/coplan/comments/process_mentions.rb +++ b/engine/app/services/coplan/comments/process_mentions.rb @@ -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 diff --git a/engine/app/services/coplan/notifications/create.rb b/engine/app/services/coplan/notifications/create.rb index c73fe7bf..d8002566 100644 --- a/engine/app/services/coplan/notifications/create.rb +++ b/engine/app/services/coplan/notifications/create.rb @@ -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? diff --git a/engine/app/services/coplan/notifications/fanout_budget.rb b/engine/app/services/coplan/notifications/fanout_budget.rb new file mode 100644 index 00000000..22f21180 --- /dev/null +++ b/engine/app/services/coplan/notifications/fanout_budget.rb @@ -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 diff --git a/engine/app/views/coplan/agent_instructions/guides/comments.text.erb b/engine/app/views/coplan/agent_instructions/guides/comments.text.erb index 55f930c3..565a80d7 100644 --- a/engine/app/views/coplan/agent_instructions/guides/comments.text.erb +++ b/engine/app/views/coplan/agent_instructions/guides/comments.text.erb @@ -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 diff --git a/engine/lib/coplan/configuration.rb b/engine/lib/coplan/configuration.rb index c1a676c3..2618c48a 100644 --- a/engine/lib/coplan/configuration.rb +++ b/engine/lib/coplan/configuration.rb @@ -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). @@ -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 these instructions.' @agent_curl_prefix = 'curl -s -H "Authorization: Bearer $TOKEN"' @@ -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 diff --git a/spec/lib/coplan/configuration_spec.rb b/spec/lib/coplan/configuration_spec.rb new file mode 100644 index 00000000..b2430b62 --- /dev/null +++ b/spec/lib/coplan/configuration_spec.rb @@ -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 diff --git a/spec/services/coplan/notifications/fanout_budget_concurrency_spec.rb b/spec/services/coplan/notifications/fanout_budget_concurrency_spec.rb new file mode 100644 index 00000000..4afbe0af --- /dev/null +++ b/spec/services/coplan/notifications/fanout_budget_concurrency_spec.rb @@ -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 diff --git a/spec/services/coplan/notifications/fanout_budget_spec.rb b/spec/services/coplan/notifications/fanout_budget_spec.rb new file mode 100644 index 00000000..25dddc65 --- /dev/null +++ b/spec/services/coplan/notifications/fanout_budget_spec.rb @@ -0,0 +1,184 @@ +require "rails_helper" + +RSpec.describe Coplan::Notifications::FanoutBudget do + include ActiveJob::TestHelper + + let(:author) { create(:coplan_user) } + let(:poster) { create(:coplan_user) } + let(:plan) { create(:plan, created_by_user: author) } + let(:thread) { create(:comment_thread, plan: plan, plan_version: plan.current_plan_version, created_by_user: author) } + + around do |example| + previous_cache = Rails.cache + Rails.cache = ActiveSupport::Cache::MemoryStore.new + config = Coplan.configuration + previous_keys = [ config.vapid_public_key, config.vapid_private_key, config.vapid_subject ] + previous_budget = [ config.notification_fanout_limit, config.notification_fanout_window ] + previous_handlers = config.notification_delivery_handlers.dup + config.notification_fanout_limit = 6 + config.vapid_public_key = "pub" + config.vapid_private_key = "priv" + config.vapid_subject = "mailto:test@example.com" + example.run + ensure + Rails.cache = previous_cache + config.vapid_public_key, config.vapid_private_key, config.vapid_subject = previous_keys + config.notification_fanout_limit, config.notification_fanout_window = previous_budget + config.notification_delivery_handlers.replace(previous_handlers) + end + + before do + # Windows are fixed slots; don't let a test straddle two. + freeze_time + create_list(:coplan_web_push_subscription, 3, user: author) + end + + def reply(body, by: poster) + comment = create(:comment, comment_thread: thread, author_type: "human", author_id: by.id, body_markdown: body) + Coplan::Notifications::Create.call(comment_thread: thread, actor_id: by.id, comment: comment, reason: "reply") + end + + def pushes + enqueued_jobs.count { |job| job["job_class"] == "Coplan::WebPushDeliveryJob" } + end + + it "stops pushing one person's notifications past the budget but keeps every inbox row" do + 3.times { |i| reply("Reply #{i}") } + + expect(Coplan::Notification.where(user: author).count).to eq(3) + expect(pushes).to eq(6) + end + + it "charges each person separately and starts again in the next window" do + 3.times { |i| reply("Reply #{i}") } + reply("Someone else", by: create(:coplan_user)) + expect(pushes).to eq(9) + + travel(Coplan.configuration.notification_fanout_window) { reply("Later") } + expect(pushes).to eq(12) + end + + it "charges an agent's comments to the person behind it, whichever token posts" do + 3.times do |i| + token = create(:api_token, user: poster) + comment = create(:comment, comment_thread: thread, author_type: "local_agent", author_id: poster.id, + api_token_id: token.id, agent_name: "Amp", body_markdown: "Agent reply #{i}") + Coplan::Notifications::Create.call(comment_thread: thread, actor_id: token.id, comment: comment, reason: "agent_response") + end + + expect(pushes).to eq(6) + end + + it "applies to mentions too" do + mentioned = create(:coplan_user, username: "bob") + create_list(:coplan_web_push_subscription, 3, user: mentioned) + 3.times do |i| + comment = create(:comment, comment_thread: thread, author_type: "human", author_id: poster.id, + body_markdown: "[@bob](mention:bob) look #{i}") + Coplan::Comments::ProcessMentions.call(comment) + end + + expect(Coplan::Notification.where(user: mentioned, reason: "mention").count).to eq(3) + expect(pushes).to eq(6) + end + + + it "counts the adapter dispatch alongside each push device" do + Coplan.configuration.notification_fanout_limit = 8 + Coplan.configuration.notification_delivery_handlers << ->(_) { } + 3.times { |i| reply("Reply #{i}") } + + expect(Coplan::Notification.where(user: author).count).to eq(3) + expect(pushes).to eq(6) + expect(enqueued_jobs.count { |job| job["job_class"] == "Coplan::DispatchNotificationJob" }).to eq(2) + end + + it "uses the host's window and does not catch up skipped deliveries" do + Coplan.configuration.notification_fanout_window = 30.seconds + 3.times { |i| reply("Reply #{i}") } + expect(pushes).to eq(6) + + travel(30.seconds) { reply("Later") } + expect(pushes).to eq(9) + expect(Coplan::Notification.where(user: author).count).to eq(4) + end + + it "lets hosts disable the budget without accessing the cache" do + Coplan.configuration.notification_fanout_limit = nil + expect(Rails.cache).not_to receive(:read) + 3.times { |i| reply("Reply #{i}") } + expect(pushes).to eq(9) + end + + it "does not charge rejected work against the remaining budget" do + expect(described_class.spend?(actor_id: poster.id, cost: 5)).to be(true) + expect(described_class.spend?(actor_id: poster.id, cost: 2)).to be(false) + expect(described_class.spend?(actor_id: poster.id, cost: 1)).to be(true) + expect(described_class.spend?(actor_id: poster.id, cost: 1)).to be(false) + end + + it "expires the old window without extending its lifetime on each spend" do + window = Coplan.configuration.notification_fanout_window + slot = Time.current.to_i / window + key = "coplan/notification_fanout/v2/#{poster.id}/#{window}/#{slot}" + travel_to(Time.at(slot * window)) + described_class.spend?(actor_id: poster.id, cost: 1) + travel 1.minute + described_class.spend?(actor_id: poster.id, cost: 1) + expect(Rails.cache.read(key)).to eq(2) + travel_to(Time.at((slot + 2) * window)) + expect(Rails.cache.read(key)).to be_nil + end + + it "bypasses a null store even when a request-local cache is active" do + Rails.cache = ActiveSupport::Cache::NullStore.new + expect(Coplan::User).not_to receive(:lock) + Rails.cache.with_local_cache do + expect(described_class.spend?(actor_id: poster.id, cost: 7)).to be(true) + end + end + + it "does not require cache increment support for mentions" do + allow(Rails.cache).to receive(:increment).and_raise(NotImplementedError) + mentioned = create(:coplan_user, username: "bob") + create(:coplan_web_push_subscription, user: mentioned) + comment = create(:comment, comment_thread: thread, author_type: "human", author_id: poster.id, + body_markdown: "[@bob](mention:bob) look") + expect(Coplan::Notification.where(comment: comment, user: mentioned).count).to eq(1) + expect(pushes).to eq(1) + end + + [ :read, :write ].each do |operation| + it "keeps all mention inbox rows and deliveries when cache #{operation} raises" do + mentioned = [ create(:coplan_user, username: "bob"), create(:coplan_user, username: "alice") ] + mentioned.each { |user| create(:coplan_web_push_subscription, user: user) } + thread # Finish fixture callbacks before simulating a cache outage. + allow(Rails.cache).to receive(operation).and_raise(NotImplementedError) + comment = create(:comment, comment_thread: thread, author_type: "human", author_id: poster.id, + body_markdown: "[@bob](mention:bob) [@alice](mention:alice) look") + expect(Coplan::Notification.where(comment: comment, reason: "mention").count).to eq(2) + expect(pushes).to eq(2) + end + end + + it "allows delivery when the store reports a failed write" do + allow(Rails.cache).to receive(:write).and_return(false) + reply("Still notify") + expect(Coplan::Notification.where(user: author).count).to eq(1) + expect(pushes).to eq(3) + end + + it "keeps all queued recipients and badges when accounting fails" do + coauthor = create(:coplan_user) + create(:plan_collaborator, plan: plan, user: coauthor, role: "author") + create(:coplan_web_push_subscription, user: coauthor) + comment = create(:comment, comment_thread: thread, author_type: "human", author_id: poster.id, body_markdown: "Reply") + allow(Rails.cache).to receive(:read).and_raise(IOError, "cache unavailable") + expect(Coplan::Notifications::BroadcastBadges).to receive(:call).with(user_ids: contain_exactly(author.id, coauthor.id)) + + Coplan::CreateNotificationsJob.perform_now(comment_thread_id: thread.id, actor_id: poster.id, + comment_id: comment.id, reason: "reply") + expect(Coplan::Notification.where(comment: comment).count).to eq(2) + expect(pushes).to eq(4) + end +end