Schedule chat prompts: send_at holds a queued prompt until its time
A chat_prompt with a future send_at (epoch ms) is always queued, durable in chat_prompt_queue (new send_at column, added to older databases on Open), listed with send_at in chat_queue frames, and delivered by the room's runner once the time passes, waking on a timer. The queue stays FIFO: prompts queued after a scheduled one wait behind it. A past or zero send_at behaves as before; chat_unqueue cancels as for any queued prompt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -21,6 +21,11 @@ import (
|
||||
// forwarded at once and the harness reads it at its next step. Otherwise it is
|
||||
// written to the durable chat_prompt_queue and delivered in order when the turn
|
||||
// ends, whether or not any client is still attached, and after a restart.
|
||||
//
|
||||
// A prompt with a future send_at is scheduled: it is always queued (never run
|
||||
// or steered at once) and the runner delivers it once that time has passed and
|
||||
// the session is free, waking on a timer rather than polling. The queue stays
|
||||
// strictly FIFO, so a prompt queued after a scheduled one waits behind it.
|
||||
|
||||
// chatQueueBusyPoll is how often a room holding queued prompts re-checks a
|
||||
// harness that reports its own turn in flight. TurnRunning performs no I/O.
|
||||
@@ -81,8 +86,10 @@ func (h *chatHub) admitPrompt(ctx context.Context, sessionID string, broker chat
|
||||
if room.broker == nil {
|
||||
room.broker = broker
|
||||
}
|
||||
busy := room.running || len(room.queue) > 0 || room.observedTurn
|
||||
queuedAhead := len(room.queue) > 0
|
||||
// A prompt scheduled for later is always queued: never run or steered now.
|
||||
scheduled := p.sendAt.After(h.clock())
|
||||
busy := scheduled || room.running || len(room.queue) > 0 || room.observedTurn
|
||||
queuedAhead := scheduled || len(room.queue) > 0
|
||||
h.mu.Unlock()
|
||||
if !busy {
|
||||
busy = brokerTurnRunning(broker, sessionID)
|
||||
@@ -166,6 +173,7 @@ func chatQueueRow(sessionID string, p *chatQueuedPrompt) pipeline.ChatQueuedProm
|
||||
FilesJSON: string(filesJSON),
|
||||
PartsJSON: string(partsJSON),
|
||||
CreatedAt: p.queuedAt,
|
||||
SendAt: p.sendAt,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,6 +190,7 @@ func promptFromRow(row pipeline.ChatQueuedPrompt) (*chatQueuedPrompt, error) {
|
||||
acked: true,
|
||||
durable: true,
|
||||
queuedAt: row.CreatedAt,
|
||||
sendAt: row.SendAt,
|
||||
}
|
||||
_ = json.Unmarshal([]byte(row.PartsJSON), &p.parts)
|
||||
var stored []chatStoredFile
|
||||
@@ -233,7 +242,7 @@ func (h *chatHub) queueFrame(sessionID string) protocol.ChatQueueFrame {
|
||||
return frame
|
||||
}
|
||||
for _, row := range rows {
|
||||
p := &chatQueuedPrompt{text: row.Text, operationID: row.OperationID, messageID: row.MessageID, nativeID: row.NativeID, client: row.Client, queuedAt: row.CreatedAt}
|
||||
p := &chatQueuedPrompt{text: row.Text, operationID: row.OperationID, messageID: row.MessageID, nativeID: row.NativeID, client: row.Client, queuedAt: row.CreatedAt, sendAt: row.SendAt}
|
||||
_ = json.Unmarshal([]byte(row.PartsJSON), &p.parts)
|
||||
frame.Prompts = append(frame.Prompts, p.wire())
|
||||
}
|
||||
@@ -252,6 +261,9 @@ func (p *chatQueuedPrompt) wire() protocol.ChatQueuedPrompt {
|
||||
if !p.queuedAt.IsZero() {
|
||||
out.QueuedAt = p.queuedAt.UnixMilli()
|
||||
}
|
||||
if !p.sendAt.IsZero() {
|
||||
out.SendAt = p.sendAt.UnixMilli()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func sendScheduled(t *testing.T, ctx context.Context, conn *websocket.Conn, id, text, operation string, at time.Time) protocol.Message {
|
||||
t.Helper()
|
||||
writeChat(t, ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: id, ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: text, OperationID: operation, Client: "Phone", SendAt: at.UnixMilli()}})
|
||||
return readUntil(t, ctx, conn, protocol.ChatPrompt)
|
||||
}
|
||||
|
||||
// A prompt scheduled for later is queued even on an idle session, listed with
|
||||
// its send_at, held until that time, and a prompt queued after it waits
|
||||
// behind it (FIFO).
|
||||
func TestChatScheduledPromptWaitsForItsTime(t *testing.T) {
|
||||
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
|
||||
broker := newChannelChat()
|
||||
server := startQueueServer(t, broker, store)
|
||||
conn := dialChatConn(t, server.ctx, server.srv)
|
||||
at := time.Now().Add(400 * time.Millisecond)
|
||||
if ack := sendScheduled(t, server.ctx, conn, "p1", "later", "op-1", at); !ack.ChatQueued {
|
||||
t.Fatalf("scheduled prompt not queued: %+v", ack)
|
||||
}
|
||||
if ack := sendPrompt(t, server.ctx, conn, "p2", "after", "op-2"); !ack.ChatQueued {
|
||||
t.Fatalf("prompt behind a scheduled one not queued: %+v", ack)
|
||||
}
|
||||
rows, err := store.ChatQueuedPrompts(context.Background(), "ses_1")
|
||||
if err != nil || len(rows) != 2 || rows[0].SendAt.UnixMilli() != at.UnixMilli() || !rows[1].SendAt.IsZero() {
|
||||
t.Fatalf("stored rows = %+v %v", rows, err)
|
||||
}
|
||||
writeChat(t, server.ctx, conn, protocol.Message{Type: protocol.ChatSubscribe, ID: "sub", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}})
|
||||
sub := readUntil(t, server.ctx, conn, protocol.ChatSubscribe)
|
||||
if sub.ChatQueue == nil || len(sub.ChatQueue.Prompts) != 2 || sub.ChatQueue.Prompts[0].SendAt != at.UnixMilli() || sub.ChatQueue.Prompts[1].SendAt != 0 {
|
||||
t.Fatalf("subscribe queue = %+v", sub.ChatQueue)
|
||||
}
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
if n := broker.promptCount(); n != 0 {
|
||||
t.Fatalf("scheduled prompt delivered early: %v", broker.promptTexts())
|
||||
}
|
||||
waitFor(t, "scheduled prompt delivered", func() bool { return broker.promptCount() == 1 })
|
||||
if time.Now().Before(at) {
|
||||
t.Fatalf("delivered before send_at")
|
||||
}
|
||||
if texts := broker.promptTexts(); !slices.Equal(texts, []string{"later"}) {
|
||||
t.Fatalf("delivered = %v", texts)
|
||||
}
|
||||
endTurn(broker)
|
||||
waitFor(t, "follow-up delivered", func() bool {
|
||||
return slices.Equal(broker.promptTexts(), []string{"later", "after"})
|
||||
})
|
||||
waitFor(t, "rows deleted", func() bool { return len(queuedOps(t, store)) == 0 })
|
||||
}
|
||||
|
||||
// A send_at already in the past sends exactly as an unscheduled prompt.
|
||||
func TestChatScheduledPromptInThePastSendsNow(t *testing.T) {
|
||||
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
|
||||
broker := newChannelChat()
|
||||
server := startQueueServer(t, broker, store)
|
||||
conn := dialChatConn(t, server.ctx, server.srv)
|
||||
if ack := sendScheduled(t, server.ctx, conn, "p1", "now", "op-1", time.Now().Add(-time.Minute)); ack.ChatQueued {
|
||||
t.Fatalf("past send_at was queued: %+v", ack)
|
||||
}
|
||||
waitFor(t, "prompt delivered", func() bool { return broker.promptCount() == 1 })
|
||||
if ops := queuedOps(t, store); len(ops) != 0 {
|
||||
t.Fatalf("past send_at stored: %v", ops)
|
||||
}
|
||||
}
|
||||
|
||||
// chat_unqueue cancels a scheduled prompt: it is never delivered.
|
||||
func TestChatScheduledPromptUnqueueCancels(t *testing.T) {
|
||||
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
|
||||
broker := newChannelChat()
|
||||
server := startQueueServer(t, broker, store)
|
||||
conn := dialChatConn(t, server.ctx, server.srv)
|
||||
at := time.Now().Add(300 * time.Millisecond)
|
||||
if ack := sendScheduled(t, server.ctx, conn, "p1", "later", "op-1", at); !ack.ChatQueued {
|
||||
t.Fatalf("scheduled prompt not queued: %+v", ack)
|
||||
}
|
||||
writeChat(t, server.ctx, conn, protocol.Message{Type: protocol.ChatUnqueue, ID: "rm", ChatUnqueue: &protocol.ChatUnqueueRequest{SessionID: "ses_1", OperationID: "op-1"}})
|
||||
removed := readUntil(t, server.ctx, conn, protocol.ChatUnqueue)
|
||||
if removed.ChatQueue == nil || removed.ChatQueue.Removed != "op-1" || len(removed.ChatQueue.Prompts) != 0 {
|
||||
t.Fatalf("unqueue reply = %+v", removed.ChatQueue)
|
||||
}
|
||||
time.Sleep(time.Until(at) + 200*time.Millisecond)
|
||||
if n := broker.promptCount(); n != 0 {
|
||||
t.Fatalf("cancelled scheduled prompt delivered: %v", broker.promptTexts())
|
||||
}
|
||||
if ops := queuedOps(t, store); len(ops) != 0 {
|
||||
t.Fatalf("cancelled row kept: %v", ops)
|
||||
}
|
||||
}
|
||||
|
||||
// A scheduled prompt survives a restart and is delivered at its time, not at
|
||||
// recovery.
|
||||
func TestChatScheduledPromptSurvivesRestart(t *testing.T) {
|
||||
previous := chatQueueRecoverySettle
|
||||
chatQueueRecoverySettle = 10 * time.Millisecond
|
||||
t.Cleanup(func() { chatQueueRecoverySettle = previous })
|
||||
path := filepath.Join(t.TempDir(), "queue.db")
|
||||
first := openQueueStore(t, path)
|
||||
broker := newChannelChat()
|
||||
server := startQueueServer(t, broker, first)
|
||||
conn := dialChatConn(t, server.ctx, server.srv)
|
||||
at := time.Now().Add(700 * time.Millisecond)
|
||||
if ack := sendScheduled(t, server.ctx, conn, "p1", "later", "op-1", at); !ack.ChatQueued {
|
||||
t.Fatalf("scheduled prompt not queued: %+v", ack)
|
||||
}
|
||||
server.stop()
|
||||
first.Close()
|
||||
|
||||
reopened := openQueueStore(t, path)
|
||||
rows, err := reopened.ChatQueuedPrompts(context.Background(), "ses_1")
|
||||
if err != nil || len(rows) != 1 || rows[0].SendAt.UnixMilli() != at.UnixMilli() {
|
||||
t.Fatalf("rows after restart = %+v %v", rows, err)
|
||||
}
|
||||
restarted := newChannelChat()
|
||||
startQueueServer(t, restarted, reopened)
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
if time.Now().Before(at) && restarted.promptCount() != 0 {
|
||||
t.Fatalf("recovered scheduled prompt delivered early")
|
||||
}
|
||||
waitFor(t, "recovered scheduled prompt delivered", func() bool {
|
||||
return slices.Equal(restarted.promptTexts(), []string{"later"})
|
||||
})
|
||||
if time.Now().Before(at) {
|
||||
t.Fatalf("delivered before send_at")
|
||||
}
|
||||
waitFor(t, "recovered row deleted", func() bool { return len(queuedOps(t, reopened)) == 0 })
|
||||
}
|
||||
@@ -120,6 +120,9 @@ type chatQueuedPrompt struct {
|
||||
acked bool
|
||||
durable bool
|
||||
queuedAt time.Time
|
||||
// sendAt schedules the prompt: the runner holds it (and, FIFO, everything
|
||||
// queued behind it) until this time. Zero means deliver when free.
|
||||
sendAt time.Time
|
||||
}
|
||||
|
||||
type chatObservation struct {
|
||||
@@ -777,7 +780,11 @@ func (h *chatHub) nextPrompt(room *chatRoom) (*chatQueuedPrompt, chan struct{},
|
||||
}
|
||||
var wait time.Duration
|
||||
if len(room.queue) > 0 {
|
||||
switch {
|
||||
switch now := h.clock(); {
|
||||
case room.queue[0].sendAt.After(now):
|
||||
// A scheduled head waits for its time; the queue is FIFO, so
|
||||
// later prompts wait behind it. A timer wakes the runner then.
|
||||
wait = room.queue[0].sendAt.Sub(now)
|
||||
case room.observedTurn:
|
||||
wait = chatQueueBusyPoll
|
||||
case time.Until(room.notBefore) > 0:
|
||||
@@ -789,7 +796,7 @@ func (h *chatHub) nextPrompt(room *chatRoom) (*chatQueuedPrompt, chan struct{},
|
||||
h.mu.Lock()
|
||||
if busy {
|
||||
wait = chatQueueBusyPoll
|
||||
} else if len(room.queue) > 0 && !room.observedTurn && room.ctx.Err() == nil {
|
||||
} else if len(room.queue) > 0 && !room.observedTurn && room.ctx.Err() == nil && !room.queue[0].sendAt.After(h.clock()) {
|
||||
p := room.queue[0]
|
||||
room.queue = room.queue[1:]
|
||||
room.running = true
|
||||
|
||||
@@ -123,6 +123,13 @@ func admitChatPrompt(ctx context.Context, request protocol.Message, broker chatB
|
||||
requestID: request.ID,
|
||||
write: write,
|
||||
}
|
||||
if prompt.SendAt > 0 {
|
||||
// Only a future time schedules; a past one sends exactly as an
|
||||
// unscheduled prompt.
|
||||
if at := time.UnixMilli(prompt.SendAt); at.After(hub.clock()) {
|
||||
queuedPrompt.sendAt = at
|
||||
}
|
||||
}
|
||||
// Claim the operation before admission so a concurrent retry of the same
|
||||
// prompt is acknowledged rather than delivered twice.
|
||||
hub.rememberOp(sessionID, operationID)
|
||||
|
||||
Reference in New Issue
Block a user