Skip to content
Draft
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
10 changes: 10 additions & 0 deletions pkg/bronzethread/bundle.go
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,9 @@ func (b Bundle) Validate() error {
if len(b.UserTurns) == 0 && b.Trigger == nil {
return fmt.Errorf("a bundle needs either userTurns or a trigger; nothing would start the run")
}
if len(b.UserTurns) > 0 && b.UserTurns[0].DeleteSessionFirst {
return fmt.Errorf("userTurns[0]: deleteSessionFirst needs a session to delete, and none exists before the first turn")
}
if b.Trigger != nil {
if b.Trigger.Channel == "" {
return fmt.Errorf("trigger needs a channel")
Expand Down Expand Up @@ -669,6 +672,13 @@ type Expect struct {
// denied nothing.
LastToolResultNotContains string `json:"lastToolResultNotContains,omitempty"`

// RequestNotContains asserts something appears in NO message of the
// request — no text, no tool input, no tool result, however far back.
// LastToolResultNotContains says one result was clean; this says a value
// is not in the model's context at all, which is the claim to make when the
// question is whether another session's conversation leaked into this one.
RequestNotContains string `json:"requestNotContains,omitempty"`

// LastToolResultIsError is a pointer so a bundle can assert "must NOT be an
// error" (false) distinctly from not caring (unset).
LastToolResultIsError *bool `json:"lastToolResultIsError,omitempty"`
Expand Down
17 changes: 17 additions & 0 deletions pkg/bronzethread/bundle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,23 @@ func TestBundle_Validate(t *testing.T) {
},
wantErr: "trigger needs a channelKey",
},
{
name: "deleteSessionFirst on a later turn validates",
doctor: func(b bt.Bundle) bt.Bundle {
b.UserTurns = append(b.UserTurns, bt.UserTurn{Text: "again", DeleteSessionFirst: true})
return b
},
},
{
// Before the first turn there is no session to delete; the driver
// would fail on a lookup minutes into a fixture boot instead.
name: "deleteSessionFirst on the first turn: refused",
doctor: func(b bt.Bundle) bt.Bundle {
b.UserTurns[0].DeleteSessionFirst = true
return b
},
wantErr: "userTurns[0]: deleteSessionFirst",
},
{
// Folded in rather than left as a separate call, so both consumers
// get it from the one method.
Expand Down
10 changes: 10 additions & 0 deletions pkg/bronzethread/userturn.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,16 @@ type BundleAttachment struct {
type UserTurn struct {
Text string `json:"text"`
Attachments []BundleAttachment `json:"attachments,omitempty"`

// DeleteSessionFirst deletes the conversation's session, and waits until
// it is gone, before this turn is sent. The turn then reaches a channel key
// whose session no longer exists while that session's transcript still
// does: turns are append-only audit evidence that outlives the CR, in a
// scope keyed by the session's NAME. That is the state a person returning
// to a deleted (or archived-then-collected) conversation is in, and no
// other step can produce it. Refused on the first turn, where there is
// nothing to delete.
DeleteSessionFirst bool `json:"deleteSessionFirst,omitempty"`
}

// UnmarshalJSON accepts the bare-string and object forms.
Expand Down
113 changes: 110 additions & 3 deletions pkg/channels/channelsd/pipeline/pipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -1398,8 +1398,6 @@ func (p *Pipeline) Deliver(ctx context.Context, ev channelkinds.InboundEvent) (c

// Fresh-session path (no terminal predecessor: archived == nil below).
caps := bindingCaps(p.Capabilities(ev.Channel.Spec.Kind))
sessName := makeSessionName(ev.Channel, ev.ChannelKey)
prefix := channelevents.SubjectPrefix(ev.Channel.Namespace, sessName)

// No InheritFrom on this path: a terminal predecessor is either forked
// (NewInheriting) or refused above, so nothing reaching here has one.
Expand Down Expand Up @@ -1436,6 +1434,21 @@ func (p *Pipeline) Deliver(ctx context.Context, ev channelkinds.InboundEvent) (c
}
}

// The name to mint under — never makeSessionName directly: its answer can
// name a scope a DELETED predecessor's transcript still occupies (see
// freshSessionName). AFTER the thread-ownership guard, so a message another
// agent's session owns keeps its silent refusal even while memory is
// unreadable. Fail CLOSED, like sweepBeforeMint below: the scope's contents
// could not be established, and minting anyway is exactly how a
// predecessor's transcript becomes this session's working context.
sessName, err := p.freshSessionName(ctx, ev.Channel, ev.ChannelKey)
if err != nil {
log.FromContext(ctx).Info("fresh session: could not establish an unoccupied name; refusing to mint",
"channel", channelRefForLog(ev.Channel), "channelKey", ev.ChannelKey, "err", err.Error())
return channelkinds.InboundDecision{Outcome: channelkinds.OutcomeInternalError}, err
}
prefix := channelevents.SubjectPrefix(ev.Channel.Namespace, sessName)

// Session-START gate (start_gate.go): on an org-membership-attributing
// channel, a non-member needs agentclass#start_session — or a platform
// admin's approval — before a session runs for them at all. AFTER the
Expand Down Expand Up @@ -2721,8 +2734,84 @@ func (p *Pipeline) sweepBeforeMint(ctx context.Context, ns, name string) error {
return nil
}

// maxSessionNameGenerations bounds freshSessionName's walk. Each step past the
// first is a session for this exact (channel, key) that was deleted after it
// had spoken: the archive sweep and session GC produce at most one a month for
// a conversation that goes quiet, so this is decades of them, and reaching it
// means something is wrong rather than busy — say so instead of looping. It
// also caps the name suffix at three digits, which the 63-byte name budget
// depends on (see sessionNameGeneration).
const maxSessionNameGenerations = 512

// freshSessionName picks the name a fresh session for (ch, key) is minted
// under: the first generation (see sessionNameGeneration) whose memory scope
// holds no turns.
//
// Why it cannot simply be makeSessionName. A memory scope is keyed by
// namespace/name, not by the CR's UID, and its transcript outlives the CR on
// purpose: the turns are append-only, signed audit evidence that session
// deletion and GC cannot remove. makeSessionName is deterministic, so once the
// session it names has been deleted — by hand, or by the archive sweep followed
// by session GC — the next message on the same key would mint a session INTO
// its predecessor's transcript. The runner then reads that as a resume: turn 0
// already exists, so the new message (spec.prompt, placed only when no turn 0
// exists) is never placed. What follows depends on how the old conversation
// ended — on the agent's reply, it parks without a word; on a tool result
// (agent_work_complete's, say), it runs the OLD conversation again. Either way
// the person's message is lost, and the predecessor's tool output — never
// re-authorized for whoever is asking now — is the new session's working
// context. sweepBeforeMint already clears what a reused
// name leaves in SpiceDB; this is the memory half, and since the memory cannot
// be cleared, the name moves instead.
//
// Deterministic across replicas, so the AlreadyExists race the base name relies
// on still collapses two replicas onto one session: every replica reads the
// same retained scopes and walks the same sequence. Follow-up messages never
// recompute the name — correlateSessions finds the session by its channel
// labels, which a successor carries exactly as the first generation did.
//
// The order of the two reads per step is what keeps the race safe. A scope
// holding turns is either a dead predecessor's or a LIVE session's — another
// replica that minted this same inbound a moment ago and has already written
// into it. Turns are read FIRST and the CR second, so a replica that sees
// another's turns is guaranteed to see that replica's CR too (it was created
// before anything was written under its name) and joins it rather than walking
// past it to mint a duplicate. p.K8s is the uncached client.
//
// Any read error is returned, never guessed past: the caller refuses to mint.
func (p *Pipeline) freshSessionName(ctx context.Context, ch *spiceboxv1alpha1.Channel, key string) (string, error) {
base := makeSessionName(ch, key)
for g := 1; g <= maxSessionNameGenerations; g++ {
name := sessionNameGeneration(base, g)
turns, err := p.Memory.ReadAll(ctx, ch.Namespace, name)
if err != nil {
return "", fmt.Errorf("read memory scope %s/%s before minting a session under it: %w", ch.Namespace, name, err)
}
if len(turns) == 0 {
return name, nil
}
var existing spiceboxv1alpha1.AgentSession
switch err := p.K8s.Get(ctx, types.NamespacedName{Namespace: ch.Namespace, Name: name}, &existing); {
case err == nil && existing.DeletionTimestamp == nil:
// Live: a concurrent mint of this conversation. The Create below
// meets AlreadyExists and joins it, exactly as for the base name.
return name, nil
case err != nil && !apierrors.IsNotFound(err):
return "", fmt.Errorf("check whether %s/%s exists: %w", ch.Namespace, name, err)
}
// Gone, or being deleted (its finalizer is running): a predecessor
// either way, and joining one about to vanish would strand the inbound.
log.FromContext(ctx).Info("fresh session: memory scope holds a deleted session's transcript; minting under the next name instead",
"occupied", ch.Namespace+"/"+name, "turns", len(turns),
"channel", channelRefForLog(ch), "channelKey", key)
}
return "", fmt.Errorf("every one of %d candidate names for %s key %q holds a deleted session's transcript",
maxSessionNameGenerations, channelRefForLog(ch), key)
}

// makeSessionName produces a deterministic-ish name based on the channel
// and key. Truncated + suffixed with a hash so k8s names stay valid.
// and key. Truncated + suffixed with a hash so k8s names stay valid. A fresh
// mint goes through freshSessionName, which starts here.
func makeSessionName(ch *spiceboxv1alpha1.Channel, key string) string {
h := sha256.Sum256([]byte(ch.Name + "/" + key))
suffix := hex.EncodeToString(h[:])[:8]
Expand All @@ -2733,6 +2822,24 @@ func makeSessionName(ch *spiceboxv1alpha1.Channel, key string) string {
return base + "-" + suffix
}

// sessionNameGeneration names the g-th session minted for one (channel, key):
// base itself (makeSessionName's answer) for the first, base-g<g> after it. A
// counter rather than a hash so the sequence is the same on every replica and
// readable in `kubectl get agentsessions`.
//
// The limit that binds is 63, not 253: a session's workspace Jobs are named
// "ws-apply-<session>" (agentsession rbac.go), and a Job name must fit a 63-byte
// label value. base is at most 49 bytes (40 of channel name, "-", 8 hex), and
// maxSessionNameGenerations keeps the suffix to at most "-g512", 5 bytes — so
// the longest name is 54 and its Job name exactly 63. A larger bound, or a
// longer suffix, must shorten base to match.
func sessionNameGeneration(base string, g int) string {
if g <= 1 {
return base
}
return base + "-g" + strconv.Itoa(g)
}

// renderMention returns the channel kind's clickable mention syntax for
// externalID (Slack: "<@U123>"), falling back to the bare externalID when
// the kind isn't registered or its RenderMention returns empty. Shared by
Expand Down
Loading
Loading