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
149 changes: 142 additions & 7 deletions internal/runstate/jetstream/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,18 @@ var _ = Describe("Integration: jetstream session", Label("integration"), func()
return newStore(runstate.RuntimeEnv{Nats: nc}, []byte(fmt.Sprintf(`{"stream":%q}`, stream)))
}

// newStoreWithHold binds a second store to the same stream with the hold the spec
// names, so a spec that needs Open to hand a live run over sets it to "0s" and one
// that needs a run to go quiet sets it to a millisecond.
newStoreWithHold := func(stream, hold string) runstate.Store {
GinkgoHelper()

s, err := newStore(runstate.RuntimeEnv{Nats: nc}, []byte(fmt.Sprintf(`{"stream":%q,"hold":%q}`, stream, hold)))
Expect(err).ToNot(HaveOccurred())

return s
}

createStream := func(cfg jetstream.StreamConfig) {
GinkgoHelper()
_, err := js.CreateStream(ctx, cfg)
Expand Down Expand Up @@ -244,6 +256,17 @@ var _ = Describe("Integration: jetstream session", Label("integration"), func()
Expect(s.(*store).prefix).To(Equal("runs"))
})

It("Should default the hold to ten minutes and read a configured one", func() {
createStream(goodStream("SESSIONS", "runs.>"))
s, err := newStoreFor("SESSIONS")
Expect(err).ToNot(HaveOccurred())
Expect(s.(*store).hold).To(Equal(defaultHold))
Expect(defaultHold).To(Equal(10 * time.Minute))

Expect(newStoreWithHold("SESSIONS", "0s").(*store).hold).To(BeZero())
Expect(newStoreWithHold("SESSIONS", "90s").(*store).hold).To(Equal(90 * time.Second))
})

It("Should report the backend and the bound stream, and not the subject prefix", func() {
createStream(goodStream("SESSIONS", "ops.audit", "runs.>"))
s, err := newStoreFor("SESSIONS")
Expand Down Expand Up @@ -351,23 +374,125 @@ var _ = Describe("Integration: jetstream session", Label("integration"), func()
Expect(err).To(MatchError(runstate.ErrNotFound))
})

// The hold is off: a meta record is not a terminal record, so under the default
// hold Open would refuse the run for ten minutes after its creation. This pins
// the takeover path, where Open seeds the fence from the tail and hands over.
It("Should open a meta-only run and continue its sequence", func() {
takeover := newStoreWithHold("SESSIONS", "0s")

id := newID()
j, err := store.Create(ctx, id, newMeta(id))
j, err := takeover.Create(ctx, id, newMeta(id))
Expect(err).ToNot(HaveOccurred())
Expect(j.Close()).To(Succeed())

j2, err := store.Open(ctx, id)
j2, err := takeover.Open(ctx, id)
Expect(err).ToNot(HaveOccurred())
Expect(j2.LastSeq()).To(Equal(uint64(1)))
Expect(j2.Append(ctx, 2, assistantRec(0))).To(Succeed())
Expect(j2.Close()).To(Succeed())

rs, err := store.Load(ctx, id)
rs, err := takeover.Load(ctx, id)
Expect(err).ToNot(HaveOccurred())
Expect(rs.Counters.LlmCalls).To(Equal(int64(1)))
})

It("Should refuse a second opener while a turn is in flight", func() {
id := newID()
j, err := store.Create(ctx, id, newMeta(id))
Expect(err).ToNot(HaveOccurred())
Expect(j.Append(ctx, 2, assistantRec(0))).To(Succeed())
Expect(j.Close()).To(Succeed())

_, err = store.Open(ctx, id)
Expect(err).To(MatchError(runstate.ErrLocked))
Expect(err).To(MatchError(ContainSubstring(id)))
})

It("Should open a run whose last turn ended", func() {
id := newID()
j, err := store.Create(ctx, id, newMeta(id))
Expect(err).ToNot(HaveOccurred())
Expect(j.Append(ctx, 2, assistantRec(0))).To(Succeed())
Expect(j.Append(ctx, 3, terminalRec(runstate.ReasonCompleted))).To(Succeed())
Expect(j.Close()).To(Succeed())

j2, err := store.Open(ctx, id)
Expect(err).ToNot(HaveOccurred())
Expect(j2.LastSeq()).To(Equal(uint64(3)))
Expect(j2.Close()).To(Succeed())
})

// A suspend on a deferred call ends on a terminal record, and every answer
// SupplyToolResult writes after it is a tool_result, so Open reads back over
// them to the terminal and the resume that follows a supply opens.
It("Should open a suspended run whose deferred calls were answered", func() {
id := newID()
j, err := store.Create(ctx, id, newMeta(id))
Expect(err).ToNot(HaveOccurred())
Expect(j.Append(ctx, 2, assistantRec(0, "tu_1", "tu_2"))).To(Succeed())
Expect(j.Append(ctx, 3, terminalRec(runstate.ReasonSuspended))).To(Succeed())
Expect(j.Append(ctx, 4, toolResultRec("tu_1"))).To(Succeed())
Expect(j.Append(ctx, 5, toolResultRec("tu_2"))).To(Succeed())
Expect(j.Close()).To(Succeed())

j2, err := store.Open(ctx, id)
Expect(err).ToNot(HaveOccurred())
Expect(j2.LastSeq()).To(Equal(uint64(5)))
Expect(j2.Close()).To(Succeed())
})

// The runner writes the same tool_result record after a tool call inside a
// turn, where the record before it is the assistant record that made the call,
// so the read back holds the run.
It("Should refuse a second opener while a turn waits on the model after a tool call", func() {
id := newID()
j, err := store.Create(ctx, id, newMeta(id))
Expect(err).ToNot(HaveOccurred())
Expect(j.Append(ctx, 2, assistantRec(0, "tu_1"))).To(Succeed())
Expect(j.Append(ctx, 3, toolResultRec("tu_1"))).To(Succeed())
Expect(j.Close()).To(Succeed())

_, err = store.Open(ctx, id)
Expect(err).To(MatchError(runstate.ErrLocked))
})

// The tail's age is the stream's store time against this clock, so a hold of a
// millisecond passes in the sleep and the run opens as a crashed holder's would.
It("Should open a run whose turn went quiet longer than the hold", func() {
quiet := newStoreWithHold("SESSIONS", "1ms")

id := newID()
j, err := quiet.Create(ctx, id, newMeta(id))
Expect(err).ToNot(HaveOccurred())
Expect(j.Append(ctx, 2, assistantRec(0))).To(Succeed())
Expect(j.Close()).To(Succeed())

time.Sleep(5 * time.Millisecond)

j2, err := quiet.Open(ctx, id)
Expect(err).ToNot(HaveOccurred())
Expect(j2.LastSeq()).To(Equal(uint64(2)))
Expect(j2.Close()).To(Succeed())
})

// A run holding only its meta record has a turn in flight: Create is the first
// write of a turn that has not ended. Under the default hold that refuses it, and
// under a hold of zero the takeover path opens it.
It("Should open a meta-only run under a hold of zero and refuse it under the default", func() {
id := newID()
j, err := store.Create(ctx, id, newMeta(id))
Expect(err).ToNot(HaveOccurred())
Expect(j.Close()).To(Succeed())

_, err = store.Open(ctx, id)
Expect(err).To(MatchError(runstate.ErrLocked))

j2, err := newStoreWithHold("SESSIONS", "0s").Open(ctx, id)
Expect(err).ToNot(HaveOccurred())
Expect(j2.LastSeq()).To(Equal(uint64(1)))
Expect(j2.Close()).To(Succeed())
})

It("Should treat a duplicate seq as an idempotent no-op and reject gaps", func() {
id := newID()
j, err := store.Create(ctx, id, newMeta(id))
Expand Down Expand Up @@ -414,13 +539,18 @@ var _ = Describe("Integration: jetstream session", Label("integration"), func()
Expect(recs).To(HaveLen(3))
})

// The hold is off: A's tail is a fresh assistant record, which the default hold
// would refuse B at Open. This pins the fence, which decides after Open has
// handed the run to both.
It("Should fence a second writer out with ErrLocked", func() {
takeover := newStoreWithHold("SESSIONS", "0s")

id := newID()
jA, err := store.Create(ctx, id, newMeta(id))
jA, err := takeover.Create(ctx, id, newMeta(id))
Expect(err).ToNot(HaveOccurred())
Expect(jA.Append(ctx, 2, assistantRec(0, "tu_1"))).To(Succeed())

jB, err := store.Open(ctx, id)
jB, err := takeover.Open(ctx, id)
Expect(err).ToNot(HaveOccurred())
Expect(jB.LastSeq()).To(Equal(uint64(2)))

Expand All @@ -432,15 +562,20 @@ var _ = Describe("Integration: jetstream session", Label("integration"), func()
Expect(err).To(MatchError(runstate.ErrLocked))
})

// The hold is off: B has to get past Open while A's turn is in flight for
// CheckHeld to have a takeover to report, and the default hold refuses that
// Open. This pins the takeover past the hold, which the fence still decides.
It("Should report a run as held until another writer takes it, then refuse it", func() {
takeover := newStoreWithHold("SESSIONS", "0s")

id := newID()
jA, err := store.Create(ctx, id, newMeta(id))
jA, err := takeover.Create(ctx, id, newMeta(id))
Expect(err).ToNot(HaveOccurred())
Expect(jA.Append(ctx, 2, assistantRec(0, "tu_1"))).To(Succeed())
Expect(jA.CheckHeld(ctx)).To(Succeed(), "nobody else has written, so A still holds it")

// B takes the run the way a resume does, by writing before it does anything.
jB, err := store.Open(ctx, id)
jB, err := takeover.Open(ctx, id)
Expect(err).ToNot(HaveOccurred())
Expect(jB.Append(ctx, 3, claimRec("worker-b"))).To(Succeed())

Expand Down
91 changes: 90 additions & 1 deletion internal/runstate/jetstream/jetstream.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@
// two writers of the same run cannot interleave. The record body is byte-identical to
// a file-backend journal line, so a run migrates between backends unchanged.
//
// There is no lock. Open refuses a run whose last turn has not ended on a terminal
// record for the hold window after its tail was written, since a turn is in flight or
// its holder crashed inside the window. Outside the window the fence at the append is
// the only exclusion, so a second process can take over a run whose holder crashed or
// stalled, and the holder fails at its next append.
//
// Importing this package registers the backend under runstate.BackendJetStream, so a
// program links it in by importing it (usually for its side effect). It holds no
// exported API beyond that registration. The operator owns the stream: this backend
Expand Down Expand Up @@ -80,6 +86,14 @@ const (
// unlimited one), which is the operator's call, so the floor only rejects a stream
// that cannot hold a session at all.
recordFloorBytes = 4096

// defaultHold is how long Open refuses a run with a turn in flight after its last
// append. It has to exceed the longest gap a live turn goes without appending, which
// is one model call or one tool call for a served run, since a server channel
// suspends on a gate rather than waiting in-process. An interactive chat waits at
// its prompt in-process with no terminal record written, so a chat idle longer than
// this is openable by a resume elsewhere and fails at its next append.
defaultHold = 10 * time.Minute
)

// options is the typed shape of the jetstream backend's session options.
Expand All @@ -89,6 +103,13 @@ type options struct {
// operator owns the stream's durability and retention policy. The run subject
// prefix is derived from the stream's own wildcard subject, not configured here.
Stream string `json:"stream"`

// Hold is how long a run with a turn in flight stays refused to a second opener
// after its last append, as a Go duration string. Empty is the default of ten
// minutes. "0s" turns the check off: Open then always succeeds and the fence at the
// append is the only exclusion, so a second opener takes the run over and the
// holder fails at its next append.
Hold string `json:"hold"`
}

// decodeOptions strictly decodes the backend options. A stdlib decoder with
Expand Down Expand Up @@ -123,6 +144,17 @@ func newStore(env runstate.RuntimeEnv, raw json.RawMessage) (runstate.Store, err
return nil, fmt.Errorf("jetstream session: options.stream is required (the JetStream stream name); the stream must already exist")
}

hold := defaultHold
if opts.Hold != "" {
hold, err = time.ParseDuration(opts.Hold)
if err != nil {
return nil, fmt.Errorf("jetstream session: options.hold %q is not a duration (for example 10m or 0s): %w", opts.Hold, err)
}
if hold < 0 {
return nil, fmt.Errorf("jetstream session: options.hold %q is negative; set 0s to turn the hold off", opts.Hold)
}
}

nc := env.Nats
if nc == nil {
return nil, fmt.Errorf("jetstream session: requires a NATS connection but none is configured; set nats_context in the config to a context created with `nats context add`")
Expand Down Expand Up @@ -158,7 +190,7 @@ func newStore(env runstate.RuntimeEnv, raw json.RawMessage) (runstate.Store, err
return nil, err
}

return &store{js: js, stream: stream, streamName: opts.Stream, prefix: prefix}, nil
return &store{js: js, stream: stream, streamName: opts.Stream, prefix: prefix, hold: hold}, nil
}

// derivePrefix resolves the run subject prefix from the stream's bound subjects.
Expand Down Expand Up @@ -271,6 +303,9 @@ type store struct {
stream jetstream.Stream
streamName string
prefix string
// hold is how long Open refuses a run whose tail is not a terminal record, measured
// from the tail's stream store time. Zero turns the check off.
hold time.Duration
}

// Info implements runstate.Store, reporting the backend and the stream it is bound to.
Expand Down Expand Up @@ -373,6 +408,17 @@ func (s *store) Create(ctx context.Context, id string, meta runstate.MetaRecord)
}

// Open implements runstate.Store.
//
// Every turn ends on a terminal record, so a run at rest ends on one, or on the
// tool_result records SupplyToolResult appends after it to answer deferred calls. A run
// whose tail is anything else has a turn in flight or a holder that crashed, and Open
// refuses it with ErrLocked while the tail is younger than the store's hold. Once the
// tail is older than the hold, Open hands the run over and the fence at the append is
// the only exclusion: a holder that was merely slow fails at its next append, after
// this opener has written.
//
// The age is the tail's stream store time against this process's clock. The server
// stamps the time, so an opener's own clock cannot favor it.
func (s *store) Open(ctx context.Context, id string) (runstate.Journal, error) {
err := runstate.ValidateID(id)
if err != nil {
Expand All @@ -399,6 +445,17 @@ func (s *store) Open(ctx context.Context, id string) (runstate.Journal, error) {
return nil, fmt.Errorf("jetstream session: run %q has an unparsable record subject %q: %w", id, last.Subject, err)
}

if s.hold > 0 && time.Since(last.Time) < s.hold {
rest, err := s.atRest(opCtx, id, seq, last.Data)
if err != nil {
return nil, fmt.Errorf("jetstream session: opening run %q: %w", id, err)
}
if !rest {
return nil, fmt.Errorf("%w: run %q on stream %q has a turn in flight, last written at %s; if its holder is gone it opens again at %s",
runstate.ErrLocked, id, s.streamName, last.Time.UTC().Format(time.RFC3339), last.Time.Add(s.hold).UTC().Format(time.RFC3339))
}
}

nonce, err := newNonce()
if err != nil {
return nil, err
Expand All @@ -407,6 +464,38 @@ func (s *store) Open(ctx context.Context, id string) (runstate.Journal, error) {
return &journal{store: s, id: id, nonce: nonce, lastSeq: seq, tailStreamSeq: last.Sequence}, nil
}

// atRest reports whether a run whose tail is the record at seq has no turn in flight.
//
// A terminal tail is at rest. For a tool_result tail, atRest reads the record before it
// until it reaches a record of another kind, and that record decides: the runner writes
// a tool_result after each tool call inside a turn, where the record before the run of
// them is the assistant record that made the calls, and SupplyToolResult writes one
// after the terminal record of a suspend to answer a deferred call. Any other record,
// and a body that does not decode, is a turn in flight. atRest reads one message per
// supplied answer, so a read back is as long as the deferred calls of one turn.
func (s *store) atRest(ctx context.Context, id string, seq uint64, data []byte) (bool, error) {
for {
var rec runstate.Record
err := json.Unmarshal(data, &rec)
if err != nil {
return false, nil
}
if rec.Terminal != nil {
return true, nil
}
if rec.ToolResult == nil || seq <= 1 {
return false, nil
}

seq--
msg, err := s.stream.GetLastMsgForSubject(ctx, s.subjectForSeq(id, seq))
if err != nil {
return false, fmt.Errorf("reading record %d: %w", seq, err)
}
data = msg.Data
}
}

// Load implements runstate.Store.
func (s *store) Load(ctx context.Context, id string) (*runstate.RunState, error) {
err := runstate.ValidateID(id)
Expand Down
12 changes: 12 additions & 0 deletions internal/runstate/jetstream/jetstream_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@ var _ = Describe("newStore construction", func() {
Expect(err).To(MatchError(ContainSubstring("invalid jetstream session options")))
})

// The hold is parsed before the connection is looked at, so a bad value is refused
// here without a server.
It("Should reject a hold option it cannot parse", func() {
_, err := newStore(runstate.RuntimeEnv{}, []byte(`{"stream":"sessions","hold":"soon"}`))
Expect(err).To(MatchError(ContainSubstring(`options.hold "soon" is not a duration`)))
})

It("Should reject a negative hold", func() {
_, err := newStore(runstate.RuntimeEnv{}, []byte(`{"stream":"sessions","hold":"-1m"}`))
Expect(err).To(MatchError(ContainSubstring(`options.hold "-1m" is negative`)))
})

It("Should be registered under the jetstream backend name", func() {
Expect(runstate.Backends()).To(ContainElement(runstate.BackendJetStream))
})
Expand Down
Loading