Skip to content

Commit b58042a

Browse files
authored
Merge pull request #351 from ThePumpingLemma/dgrochowski/wake-after-commit
Wake agent sessions after their inbox events commit
2 parents 0608dee + 880fbc2 commit b58042a

3 files changed

Lines changed: 137 additions & 1 deletion

File tree

‎engine/app/services/coplan/agent_events/publish.rb‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,25 @@ def deliver(token, session)
7575
# that further to sessions with a real path for the wake — a
7676
# parked connection or a wake URL. Without one, flipping to
7777
# pending would start a 30-second countdown nothing can answer.
78-
session.wake! if session&.live? && session.wakeable?
78+
# After commit: waking broadcasts the session pill, and a Cable
79+
# failure there must not roll back inbox rows already written.
80+
if session&.live? && session.wakeable?
81+
activity_at = session.last_activity_at
82+
ActiveRecord.after_all_transactions_commit do
83+
# A polling agent can acknowledge the committed event before
84+
# this callback runs. Reload under the lock so its latest
85+
# response is not overwritten by the old watching snapshot.
86+
session.with_lock do
87+
next if session.state.in?(AgentSession::PROOF_STATES) && session.last_activity_at != activity_at
88+
89+
session.wake! if session.live? && session.wakeable?
90+
end
91+
rescue StandardError => error
92+
# A pill failure must not skip other recipients, their wake
93+
# webhooks, inbox signals, or the caller's notifications.
94+
Rails.error.report(error)
95+
end
96+
end
7997

8098
# A wake URL is a standing subscription: it fires even when the
8199
# session looks finished (`complete`), because a hosted agent

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ Or stream with Server-Sent Events. The server sends a heartbeat every 15 seconds
9393
- The response has `events` and a `cursor` (the last event ID).
9494
- If the response has `"throttled": true`, the server has too many open connections. Wait a few seconds, then poll again.
9595
- Without a cursor, you get all events that you did not acknowledge. Coplan never sends you your own comments or edits.
96+
- Inbox events commit before Coplan attempts a session wake. A failed session wake does not remove the events or stop webhook and inbox signals for other agents. If a wake is missed, poll your inbox.
9697

9798
## Events
9899

‎spec/services/coplan/agent_events/publish_spec.rb‎

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,123 @@ def publish_comment(loaded)
3333

3434
expect { publish_comment(loaded) }.not_to change(Coplan::AgentEvent, :count)
3535
end
36+
37+
it "keeps every queued event when waking a session fails" do
38+
second = create(:api_token, user: user, agent_name: "Claude")
39+
[ watcher_token, second ].each do |token|
40+
Coplan::AgentSession.find_or_create_by!(plan: plan, api_token: token) { |s| s.state = "watching"; s.agent_name = token.agent_name }
41+
.update!(wake_url: "https://agents.example.com/hooks/wake", wake_secret: "s3cret")
42+
end
43+
allow(Coplan::WakeWebhookJob).to receive(:perform_later)
44+
allow(Coplan::AgentEventBus).to receive(:signal)
45+
allow(Rails.error).to receive(:report)
46+
allow_any_instance_of(Coplan::AgentSession).to receive(:broadcast_pill).and_raise(RuntimeError, "cable down")
47+
48+
expect { publish_comment(comment) }.not_to raise_error
49+
events = Coplan::AgentEvent.where(comment_id: comment.id)
50+
expect(events.pluck(:api_token_id)).to contain_exactly(watcher_token.id, second.id)
51+
events.each do |event|
52+
session = Coplan::AgentSession.find_by!(plan: plan, api_token_id: event.api_token_id)
53+
expect(Coplan::WakeWebhookJob).to have_received(:perform_later)
54+
.with(agent_session_id: session.id, agent_event_id: event.id).once
55+
expect(Coplan::AgentEventBus).to have_received(:signal).with(event.api_token_id).once
56+
end
57+
expect(Rails.error).to have_received(:report).with(instance_of(RuntimeError)).twice
58+
end
59+
end
60+
61+
describe "committed delivery" do
62+
self.use_transactional_tests = false
63+
after { truncate_tables(*(ActiveRecord::Base.connection.tables - %w[schema_migrations ar_internal_metadata])) }
64+
65+
let(:session) { Coplan::AgentSession.find_by!(plan: plan, api_token: watcher_token) }
66+
67+
before do
68+
session.update!(wake_url: "https://agents.example.com/hooks/wake", wake_secret: "secret")
69+
allow(Coplan::WakeWebhookJob).to receive(:perform_later)
70+
allow(Coplan::AgentEventBus).to receive(:signal)
71+
end
72+
73+
it "defers all wake effects until the outer transaction commits" do
74+
Coplan::AgentEvent.transaction do
75+
Coplan::AgentEvent.transaction(requires_new: true) { publish }
76+
expect(session.reload.state).to eq("watching")
77+
expect(Coplan::WakeWebhookJob).not_to have_received(:perform_later)
78+
expect(Coplan::AgentEventBus).not_to have_received(:signal)
79+
expect(Thread.new { ActiveRecord::Base.connection_pool.with_connection { Coplan::AgentEvent.count } }.value).to eq(0)
80+
end
81+
82+
expect(Thread.new { ActiveRecord::Base.connection_pool.with_connection { Coplan::AgentEvent.count } }.value).to eq(1)
83+
expect(session.reload.state).to eq("pending")
84+
expect(Coplan::WakeWebhookJob).to have_received(:perform_later).once
85+
expect(Coplan::AgentEventBus).to have_received(:signal).with(watcher_token.id).once
86+
end
87+
88+
it "discards all wake effects when the outer transaction rolls back" do
89+
Coplan::AgentEvent.transaction do
90+
Coplan::AgentEvent.transaction(requires_new: true) { publish }
91+
raise ActiveRecord::Rollback
92+
end
93+
94+
expect(Coplan::AgentEvent.count).to eq(0)
95+
expect(session.reload.state).to eq("watching")
96+
expect(Coplan::WakeWebhookJob).not_to have_received(:perform_later)
97+
expect(Coplan::AgentEventBus).not_to have_received(:signal)
98+
end
99+
100+
it "keeps every recipient committed and signaled when a wake fails" do
101+
second = create(:api_token, user: user, agent_name: "Claude")
102+
Coplan::AgentSession.create!(plan: plan, api_token: second, state: "watching", agent_name: "Claude",
103+
wake_url: "https://agents.example.com/hooks/wake", wake_secret: "secret")
104+
thread = create(:comment_thread, plan: plan, created_by_user: user)
105+
comment = create(:comment, comment_thread: thread, author_type: "human", author_id: user.id)
106+
allow(Rails.error).to receive(:report)
107+
visible_counts = []
108+
allow_any_instance_of(Coplan::AgentSession).to receive(:broadcast_pill) do
109+
visible_counts << Thread.new {
110+
ActiveRecord::Base.connection_pool.with_connection { Coplan::AgentEvent.count }
111+
}.value
112+
raise "cable down"
113+
end
114+
115+
expect {
116+
described_class.call(plan: plan, event_type: "comment.created", comment_thread: thread, comment: comment)
117+
}.not_to raise_error
118+
119+
expect(visible_counts).to eq([ 2, 2 ])
120+
expect(Coplan::AgentEvent.pluck(:api_token_id)).to contain_exactly(watcher_token.id, second.id)
121+
expect(Coplan::WakeWebhookJob).to have_received(:perform_later).twice
122+
[ watcher_token, second ].each do |token|
123+
expect(Coplan::AgentEventBus).to have_received(:signal).with(token.id).once
124+
end
125+
end
126+
127+
%w[active awaiting_input].each do |state|
128+
it "preserves an #{state} response committed before the deferred wake" do
129+
Coplan::AgentEvent.transaction do
130+
ActiveRecord.after_all_transactions_commit do
131+
# A polling agent can see the event as soon as the commit completes.
132+
session.transition!(state, detail: "reviewing")
133+
end
134+
publish
135+
end
136+
137+
expect(session.reload).to have_attributes(state: state, state_detail: "reviewing")
138+
expect(Coplan::AgentEvent.count).to eq(1)
139+
expect(Coplan::WakeWebhookJob).to have_received(:perform_later).once
140+
expect(Coplan::AgentEventBus).to have_received(:signal).with(watcher_token.id).once
141+
end
142+
end
143+
144+
it "still wakes an agent whose question predates the event" do
145+
session.transition!("awaiting_input", detail: "Which option?")
146+
147+
publish
148+
149+
expect(session.reload).to have_attributes(state: "pending", state_detail: nil)
150+
expect(Coplan::WakeWebhookJob).to have_received(:perform_later).once
151+
expect(Coplan::AgentEventBus).to have_received(:signal).with(watcher_token.id).once
152+
end
36153
end
37154

38155
describe "with recipient_token_id" do

0 commit comments

Comments
 (0)