chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,287 @@
|
||||
// Package backgroundtest holds contract tests shared by every implementation of
|
||||
// the background-work interfaces.
|
||||
package backgroundtest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Advance moves the implementation's notion of "now" forward by d.
|
||||
type Advance func(d time.Duration)
|
||||
|
||||
var (
|
||||
sessA = interfaces.SessionRef{TenantID: 1, SessionID: "sess-a"}
|
||||
sessB = interfaces.SessionRef{TenantID: 1, SessionID: "sess-b"}
|
||||
)
|
||||
|
||||
func activity(id, kind string) interfaces.BackgroundActivity {
|
||||
return interfaces.BackgroundActivity{
|
||||
ID: id, Kind: kind, Title: "title " + id,
|
||||
StartedAt: time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC),
|
||||
}
|
||||
}
|
||||
|
||||
func listIDs(t *testing.T, r interfaces.ActivityRegistry, s interfaces.SessionRef) []string {
|
||||
t.Helper()
|
||||
items, err := r.List(context.Background(), s)
|
||||
require.NoError(t, err)
|
||||
ids := make([]string, 0, len(items))
|
||||
for _, it := range items {
|
||||
ids = append(ids, it.ID)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
return ids
|
||||
}
|
||||
|
||||
// RunActivityRegistryContract runs the shared ActivityRegistry cases. newRegistry
|
||||
// must return an empty registry and a function that advances its clock.
|
||||
func RunActivityRegistryContract(
|
||||
t *testing.T,
|
||||
newRegistry func(t *testing.T) (interfaces.ActivityRegistry, Advance),
|
||||
) {
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("AddThenList", func(t *testing.T) {
|
||||
r, _ := newRegistry(t)
|
||||
require.NoError(t, r.Add(ctx, sessA, activity("sj_1", "shell_job"), time.Minute, 0))
|
||||
items, err := r.List(ctx, sessA)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, 1)
|
||||
require.Equal(t, "sj_1", items[0].ID)
|
||||
require.Equal(t, "shell_job", items[0].Kind)
|
||||
require.Equal(t, "title sj_1", items[0].Title)
|
||||
require.True(t, items[0].StartedAt.Equal(activity("sj_1", "").StartedAt))
|
||||
})
|
||||
|
||||
t.Run("SessionsAreIsolated", func(t *testing.T) {
|
||||
r, _ := newRegistry(t)
|
||||
require.NoError(t, r.Add(ctx, sessA, activity("sj_1", "shell_job"), time.Minute, 0))
|
||||
require.Empty(t, listIDs(t, r, sessB))
|
||||
})
|
||||
|
||||
t.Run("CapIsPerKind", func(t *testing.T) {
|
||||
r, _ := newRegistry(t)
|
||||
require.NoError(t, r.Add(ctx, sessA, activity("a1", "k1"), time.Minute, 2))
|
||||
require.NoError(t, r.Add(ctx, sessA, activity("a2", "k1"), time.Minute, 2))
|
||||
err := r.Add(ctx, sessA, activity("a3", "k1"), time.Minute, 2)
|
||||
require.ErrorIs(t, err, interfaces.ErrActivityLimit)
|
||||
require.NoError(t, r.Add(ctx, sessA, activity("b1", "k2"), time.Minute, 2))
|
||||
require.Equal(t, []string{"a1", "a2", "b1"}, listIDs(t, r, sessA))
|
||||
})
|
||||
|
||||
t.Run("NonPositiveCapMeansUnlimited", func(t *testing.T) {
|
||||
r, _ := newRegistry(t)
|
||||
for i := 0; i < 10; i++ {
|
||||
require.NoError(t, r.Add(ctx, sessA, activity(fmt.Sprintf("a%d", i), "k"), time.Minute, 0))
|
||||
}
|
||||
require.NoError(t, r.Add(ctx, sessA, activity("neg", "k"), time.Minute, -1))
|
||||
require.Len(t, listIDs(t, r, sessA), 11)
|
||||
})
|
||||
|
||||
t.Run("ReAddExtendsWithoutCountingAgainstCap", func(t *testing.T) {
|
||||
r, advance := newRegistry(t)
|
||||
require.NoError(t, r.Add(ctx, sessA, activity("a1", "k"), 10*time.Second, 1))
|
||||
advance(8 * time.Second)
|
||||
require.NoError(t, r.Add(ctx, sessA, activity("a1", "k"), 10*time.Second, 1))
|
||||
advance(8 * time.Second) // 16s after the first Add, 8s after the second
|
||||
require.Equal(t, []string{"a1"}, listIDs(t, r, sessA))
|
||||
})
|
||||
|
||||
t.Run("ConcurrentAddRespectsCap", func(t *testing.T) {
|
||||
r, _ := newRegistry(t)
|
||||
const workers = 20
|
||||
var wg sync.WaitGroup
|
||||
errs := make([]error, workers)
|
||||
for i := 0; i < workers; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
errs[i] = r.Add(ctx, sessA, activity(fmt.Sprintf("c%d", i), "k"), time.Minute, 3)
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
ok := 0
|
||||
for _, err := range errs {
|
||||
if err == nil {
|
||||
ok++
|
||||
continue
|
||||
}
|
||||
require.ErrorIs(t, err, interfaces.ErrActivityLimit)
|
||||
}
|
||||
require.Equal(t, 3, ok)
|
||||
require.Len(t, listIDs(t, r, sessA), 3)
|
||||
})
|
||||
|
||||
t.Run("ExpiredItemsDisappearAndFreeTheCap", func(t *testing.T) {
|
||||
r, advance := newRegistry(t)
|
||||
require.NoError(t, r.Add(ctx, sessA, activity("a1", "k"), 10*time.Second, 1))
|
||||
advance(11 * time.Second)
|
||||
require.Empty(t, listIDs(t, r, sessA))
|
||||
require.NoError(t, r.Add(ctx, sessA, activity("a2", "k"), 10*time.Second, 1))
|
||||
require.Equal(t, []string{"a2"}, listIDs(t, r, sessA))
|
||||
})
|
||||
|
||||
t.Run("RenewExtends", func(t *testing.T) {
|
||||
r, advance := newRegistry(t)
|
||||
require.NoError(t, r.Add(ctx, sessA, activity("a1", "k"), 10*time.Second, 0))
|
||||
advance(8 * time.Second)
|
||||
found, err := r.Renew(ctx, sessA, "a1", 10*time.Second)
|
||||
require.NoError(t, err)
|
||||
require.True(t, found)
|
||||
advance(8 * time.Second)
|
||||
require.Equal(t, []string{"a1"}, listIDs(t, r, sessA))
|
||||
})
|
||||
|
||||
t.Run("RenewDoesNotRecreateRemoved", func(t *testing.T) {
|
||||
r, _ := newRegistry(t)
|
||||
require.NoError(t, r.Add(ctx, sessA, activity("a1", "k"), time.Minute, 0))
|
||||
require.NoError(t, r.Remove(ctx, sessA, "a1"))
|
||||
found, err := r.Renew(ctx, sessA, "a1", time.Minute)
|
||||
require.NoError(t, err)
|
||||
require.False(t, found)
|
||||
require.Empty(t, listIDs(t, r, sessA))
|
||||
})
|
||||
|
||||
t.Run("RenewDoesNotRecreateExpired", func(t *testing.T) {
|
||||
r, advance := newRegistry(t)
|
||||
require.NoError(t, r.Add(ctx, sessA, activity("a1", "k"), 10*time.Second, 0))
|
||||
advance(11 * time.Second)
|
||||
found, err := r.Renew(ctx, sessA, "a1", time.Minute)
|
||||
require.NoError(t, err)
|
||||
require.False(t, found)
|
||||
require.Empty(t, listIDs(t, r, sessA))
|
||||
})
|
||||
|
||||
t.Run("RenewUnknownIsNotFound", func(t *testing.T) {
|
||||
r, _ := newRegistry(t)
|
||||
found, err := r.Renew(ctx, sessA, "missing", time.Minute)
|
||||
require.NoError(t, err)
|
||||
require.False(t, found)
|
||||
})
|
||||
|
||||
t.Run("RemoveMissingIsNotAnError", func(t *testing.T) {
|
||||
r, _ := newRegistry(t)
|
||||
require.NoError(t, r.Remove(ctx, sessA, "missing"))
|
||||
})
|
||||
}
|
||||
|
||||
func notice(id string, finishedAt time.Time) interfaces.BackgroundNotice {
|
||||
return interfaces.BackgroundNotice{ID: id, Kind: "shell_job", Text: "done " + id, FinishedAt: finishedAt}
|
||||
}
|
||||
|
||||
func pendingIDs(t *testing.T, in interfaces.NoticeInbox, s interfaces.SessionRef) []string {
|
||||
t.Helper()
|
||||
items, err := in.Pending(context.Background(), s)
|
||||
require.NoError(t, err)
|
||||
ids := make([]string, 0, len(items))
|
||||
for _, it := range items {
|
||||
ids = append(ids, it.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// RunNoticeInboxContract runs the shared NoticeInbox cases. newInbox must return
|
||||
// an empty inbox whose clock starts at 2026-10-14T10:00:00Z, and a function that
|
||||
// advances that clock.
|
||||
func RunNoticeInboxContract(
|
||||
t *testing.T,
|
||||
newInbox func(t *testing.T) (interfaces.NoticeInbox, Advance),
|
||||
) {
|
||||
ctx := context.Background()
|
||||
start := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC)
|
||||
|
||||
t.Run("FirstPushWins", func(t *testing.T) {
|
||||
in, _ := newInbox(t)
|
||||
first, err := in.Push(ctx, sessA, notice("n1", start))
|
||||
require.NoError(t, err)
|
||||
require.True(t, first)
|
||||
second := notice("n1", start)
|
||||
second.Text = "overwritten"
|
||||
first, err = in.Push(ctx, sessA, second)
|
||||
require.NoError(t, err)
|
||||
require.False(t, first)
|
||||
items, err := in.Pending(ctx, sessA)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, 1)
|
||||
require.Equal(t, "done n1", items[0].Text)
|
||||
})
|
||||
|
||||
t.Run("PendingIsOldestFirst", func(t *testing.T) {
|
||||
in, _ := newInbox(t)
|
||||
_, err := in.Push(ctx, sessA, notice("late", start.Add(2*time.Minute)))
|
||||
require.NoError(t, err)
|
||||
_, err = in.Push(ctx, sessA, notice("early", start))
|
||||
require.NoError(t, err)
|
||||
_, err = in.Push(ctx, sessA, notice("mid", start.Add(time.Minute)))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"early", "mid", "late"}, pendingIDs(t, in, sessA))
|
||||
})
|
||||
|
||||
t.Run("AckRemoves", func(t *testing.T) {
|
||||
in, _ := newInbox(t)
|
||||
_, err := in.Push(ctx, sessA, notice("n1", start))
|
||||
require.NoError(t, err)
|
||||
_, err = in.Push(ctx, sessA, notice("n2", start))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, in.Ack(ctx, sessA, []string{"n1", "unknown"}))
|
||||
require.Equal(t, []string{"n2"}, pendingIDs(t, in, sessA))
|
||||
})
|
||||
|
||||
t.Run("AckEmptyIsNoop", func(t *testing.T) {
|
||||
in, _ := newInbox(t)
|
||||
require.NoError(t, in.Ack(ctx, sessA, nil))
|
||||
})
|
||||
|
||||
t.Run("AckedIDCanBePushedAgain", func(t *testing.T) {
|
||||
in, _ := newInbox(t)
|
||||
_, err := in.Push(ctx, sessA, notice("n1", start))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, in.Ack(ctx, sessA, []string{"n1"}))
|
||||
first, err := in.Push(ctx, sessA, notice("n1", start))
|
||||
require.NoError(t, err)
|
||||
require.True(t, first)
|
||||
})
|
||||
|
||||
t.Run("RetentionHidesOldNotices", func(t *testing.T) {
|
||||
in, advance := newInbox(t)
|
||||
_, err := in.Push(ctx, sessA, notice("n1", start))
|
||||
require.NoError(t, err)
|
||||
advance(interfaces.NoticeRetention - time.Minute)
|
||||
require.Equal(t, []string{"n1"}, pendingIDs(t, in, sessA))
|
||||
advance(2 * time.Minute)
|
||||
require.Empty(t, pendingIDs(t, in, sessA))
|
||||
})
|
||||
|
||||
t.Run("ClearRemovesSessionOnly", func(t *testing.T) {
|
||||
in, _ := newInbox(t)
|
||||
_, err := in.Push(ctx, sessA, notice("n1", start))
|
||||
require.NoError(t, err)
|
||||
_, err = in.Push(ctx, sessB, notice("n2", start))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, in.Clear(ctx, sessA))
|
||||
require.Empty(t, pendingIDs(t, in, sessA))
|
||||
require.Equal(t, []string{"n2"}, pendingIDs(t, in, sessB))
|
||||
})
|
||||
|
||||
t.Run("PreservesFields", func(t *testing.T) {
|
||||
in, _ := newInbox(t)
|
||||
n := notice("n1", start)
|
||||
_, err := in.Push(ctx, sessA, n)
|
||||
require.NoError(t, err)
|
||||
items, err := in.Pending(ctx, sessA)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, 1)
|
||||
require.Equal(t, n.ID, items[0].ID)
|
||||
require.Equal(t, n.Kind, items[0].Kind)
|
||||
require.Equal(t, n.Text, items[0].Text)
|
||||
require.True(t, n.FinishedAt.Equal(items[0].FinishedAt))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package background
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// Lifecycle combines the shared parts in the only orders that are safe.
|
||||
// Features call these four methods and never the underlying interfaces.
|
||||
type Lifecycle struct {
|
||||
Registry interfaces.ActivityRegistry
|
||||
Inbox interfaces.NoticeInbox
|
||||
KeepAlive interfaces.SessionKeepAliver // optional
|
||||
Events interfaces.WorkEventEmitter // optional
|
||||
Logf func(ctx context.Context, format string, args ...any)
|
||||
}
|
||||
|
||||
func (l *Lifecycle) logf(ctx context.Context, format string, args ...any) {
|
||||
if l.Logf != nil {
|
||||
l.Logf(ctx, format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Lifecycle) keepAlive(ctx context.Context, s interfaces.SessionRef) {
|
||||
if l.KeepAlive == nil {
|
||||
return
|
||||
}
|
||||
if err := l.KeepAlive.KeepAlive(ctx, s); err != nil {
|
||||
l.logf(ctx, "[Background] keep-alive failed session=%s: %v", s.SessionID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Begin registers a, then runs start. Registering first means lifecycle
|
||||
// protection is in force the moment the work exists. If start fails the
|
||||
// registration is removed. On success the sandbox is kept alive once at once,
|
||||
// because nothing renewed it before the work began.
|
||||
func (l *Lifecycle) Begin(
|
||||
ctx context.Context, s interfaces.SessionRef, a interfaces.BackgroundActivity,
|
||||
lease time.Duration, kindCap int, start func(context.Context) error,
|
||||
) error {
|
||||
if err := l.Registry.Add(ctx, s, a, lease, kindCap); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := start(ctx); err != nil {
|
||||
if rmErr := l.Registry.Remove(context.WithoutCancel(ctx), s, a.ID); rmErr != nil {
|
||||
l.logf(ctx, "[Background] remove after failed start session=%s id=%s: %v", s.SessionID, a.ID, rmErr)
|
||||
}
|
||||
return err
|
||||
}
|
||||
l.keepAlive(ctx, s)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Alive renews the registration and, when it still exists, keeps the sandbox
|
||||
// alive. found=false means the item was removed or expired; the caller decides
|
||||
// whether to re-register.
|
||||
func (l *Lifecycle) Alive(
|
||||
ctx context.Context, s interfaces.SessionRef, id string, lease time.Duration,
|
||||
) (bool, error) {
|
||||
found, err := l.Registry.Renew(ctx, s, id, lease)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if found {
|
||||
l.keepAlive(ctx, s)
|
||||
}
|
||||
return found, nil
|
||||
}
|
||||
|
||||
// Finish records the completion notice, emits work_finished only if this call
|
||||
// wrote the notice first, then removes the registration. Push comes first: in
|
||||
// the other order there is a window where neither the registry nor the inbox
|
||||
// knows the item. If Push fails the registration is kept so the item stays
|
||||
// queryable and a later Finish can retry.
|
||||
func (l *Lifecycle) Finish(
|
||||
ctx context.Context, s interfaces.SessionRef, n interfaces.BackgroundNotice,
|
||||
r interfaces.WorkResult, parentMessageID string,
|
||||
) error {
|
||||
first, err := l.Inbox.Push(ctx, s, n)
|
||||
if err != nil {
|
||||
return fmt.Errorf("push background notice: %w", err)
|
||||
}
|
||||
if first && l.Events != nil {
|
||||
if err := l.Events.EmitWorkFinished(ctx, s, parentMessageID, r); err != nil {
|
||||
l.logf(ctx, "[Background] emit work_finished failed session=%s id=%s: %v", s.SessionID, n.ID, err)
|
||||
}
|
||||
}
|
||||
return l.Registry.Remove(ctx, s, n.ID)
|
||||
}
|
||||
|
||||
// Discard removes the registration without a notice or event. Use it only when
|
||||
// the result was already handed to the model directly.
|
||||
func (l *Lifecycle) Discard(ctx context.Context, s interfaces.SessionRef, id string) error {
|
||||
return l.Registry.Remove(ctx, s, id)
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package background
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type countingKeepAliver struct{ calls int }
|
||||
|
||||
func (k *countingKeepAliver) KeepAlive(context.Context, interfaces.SessionRef) error {
|
||||
k.calls++
|
||||
return nil
|
||||
}
|
||||
|
||||
type recordingEmitter struct{ finished []interfaces.WorkResult }
|
||||
|
||||
func (e *recordingEmitter) EmitWorkFinished(
|
||||
_ context.Context, _ interfaces.SessionRef, _ string, r interfaces.WorkResult,
|
||||
) error {
|
||||
e.finished = append(e.finished, r)
|
||||
return nil
|
||||
}
|
||||
|
||||
type lifecycleFixture struct {
|
||||
l *Lifecycle
|
||||
registry *MemoryActivityRegistry
|
||||
inbox *MemoryNoticeInbox
|
||||
keep *countingKeepAliver
|
||||
events *recordingEmitter
|
||||
}
|
||||
|
||||
func newLifecycleFixture() lifecycleFixture {
|
||||
f := lifecycleFixture{
|
||||
registry: NewMemoryActivityRegistry(nil),
|
||||
inbox: NewMemoryNoticeInbox(nil),
|
||||
keep: &countingKeepAliver{},
|
||||
events: &recordingEmitter{},
|
||||
}
|
||||
f.l = &Lifecycle{Registry: f.registry, Inbox: f.inbox, KeepAlive: f.keep, Events: f.events}
|
||||
return f
|
||||
}
|
||||
|
||||
var lcSess = interfaces.SessionRef{TenantID: 1, SessionID: "s"}
|
||||
|
||||
func lcActivity(id string) interfaces.BackgroundActivity {
|
||||
return interfaces.BackgroundActivity{ID: id, Kind: "shell_job", Title: "make build", StartedAt: time.Now()}
|
||||
}
|
||||
|
||||
func liveIDs(t *testing.T, r interfaces.ActivityRegistry) []string {
|
||||
t.Helper()
|
||||
items, err := r.List(context.Background(), lcSess)
|
||||
require.NoError(t, err)
|
||||
ids := make([]string, 0, len(items))
|
||||
for _, it := range items {
|
||||
ids = append(ids, it.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func TestBeginRegistersBeforeStartAndKeepsAlive(t *testing.T) {
|
||||
f := newLifecycleFixture()
|
||||
var registeredAtStart []string
|
||||
err := f.l.Begin(context.Background(), lcSess, lcActivity("sj_1"), time.Minute, 0,
|
||||
func(context.Context) error {
|
||||
registeredAtStart = liveIDs(t, f.registry)
|
||||
return nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"sj_1"}, registeredAtStart)
|
||||
require.Equal(t, []string{"sj_1"}, liveIDs(t, f.registry))
|
||||
require.Equal(t, 1, f.keep.calls)
|
||||
}
|
||||
|
||||
func TestBeginRemovesRegistrationWhenStartFails(t *testing.T) {
|
||||
f := newLifecycleFixture()
|
||||
boom := errors.New("start failed")
|
||||
err := f.l.Begin(context.Background(), lcSess, lcActivity("sj_1"), time.Minute, 0,
|
||||
func(context.Context) error { return boom })
|
||||
require.ErrorIs(t, err, boom)
|
||||
require.Empty(t, liveIDs(t, f.registry))
|
||||
require.Zero(t, f.keep.calls)
|
||||
}
|
||||
|
||||
func TestBeginReturnsLimitWithoutStarting(t *testing.T) {
|
||||
f := newLifecycleFixture()
|
||||
require.NoError(t, f.l.Begin(context.Background(), lcSess, lcActivity("sj_1"), time.Minute, 1,
|
||||
func(context.Context) error { return nil }))
|
||||
started := false
|
||||
err := f.l.Begin(context.Background(), lcSess, lcActivity("sj_2"), time.Minute, 1,
|
||||
func(context.Context) error { started = true; return nil })
|
||||
require.ErrorIs(t, err, interfaces.ErrActivityLimit)
|
||||
require.False(t, started)
|
||||
}
|
||||
|
||||
func TestAliveRenewsAndKeepsAliveOnlyWhenFound(t *testing.T) {
|
||||
f := newLifecycleFixture()
|
||||
require.NoError(t, f.registry.Add(context.Background(), lcSess, lcActivity("sj_1"), time.Minute, 0))
|
||||
|
||||
found, err := f.l.Alive(context.Background(), lcSess, "sj_1", time.Minute)
|
||||
require.NoError(t, err)
|
||||
require.True(t, found)
|
||||
require.Equal(t, 1, f.keep.calls)
|
||||
|
||||
found, err = f.l.Alive(context.Background(), lcSess, "missing", time.Minute)
|
||||
require.NoError(t, err)
|
||||
require.False(t, found)
|
||||
require.Equal(t, 1, f.keep.calls)
|
||||
}
|
||||
|
||||
func TestFinishPushesEmitsOnceAndRemoves(t *testing.T) {
|
||||
f := newLifecycleFixture()
|
||||
ctx := context.Background()
|
||||
require.NoError(t, f.registry.Add(ctx, lcSess, lcActivity("sj_1"), time.Minute, 0))
|
||||
n := interfaces.BackgroundNotice{ID: "sj_1", Kind: "shell_job", Text: "done", FinishedAt: time.Now()}
|
||||
r := interfaces.WorkResult{ID: "sj_1", State: interfaces.WorkStateSucceeded, Terminal: true}
|
||||
|
||||
require.NoError(t, f.l.Finish(ctx, lcSess, n, r, "msg-1"))
|
||||
require.NoError(t, f.l.Finish(ctx, lcSess, n, r, "msg-1")) // second reporter
|
||||
|
||||
require.Len(t, f.events.finished, 1)
|
||||
require.Empty(t, liveIDs(t, f.registry))
|
||||
pending, err := f.inbox.Pending(ctx, lcSess)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, pending, 1)
|
||||
}
|
||||
|
||||
func TestFinishKeepsRegistrationWhenPushFails(t *testing.T) {
|
||||
f := newLifecycleFixture()
|
||||
ctx := context.Background()
|
||||
require.NoError(t, f.registry.Add(ctx, lcSess, lcActivity("sj_1"), time.Minute, 0))
|
||||
f.l.Inbox = failingInbox{}
|
||||
|
||||
err := f.l.Finish(ctx, lcSess, interfaces.BackgroundNotice{ID: "sj_1"}, interfaces.WorkResult{ID: "sj_1"}, "")
|
||||
require.Error(t, err)
|
||||
require.Equal(t, []string{"sj_1"}, liveIDs(t, f.registry),
|
||||
"without a notice the item must stay visible, or queries would find it nowhere")
|
||||
require.Empty(t, f.events.finished)
|
||||
}
|
||||
|
||||
func TestDiscardRemovesWithoutNoticeOrEvent(t *testing.T) {
|
||||
f := newLifecycleFixture()
|
||||
ctx := context.Background()
|
||||
require.NoError(t, f.registry.Add(ctx, lcSess, lcActivity("sj_1"), time.Minute, 0))
|
||||
|
||||
require.NoError(t, f.l.Discard(ctx, lcSess, "sj_1"))
|
||||
|
||||
require.Empty(t, liveIDs(t, f.registry))
|
||||
pending, err := f.inbox.Pending(ctx, lcSess)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, pending)
|
||||
require.Empty(t, f.events.finished)
|
||||
}
|
||||
|
||||
func TestLifecycleToleratesNilOptionalParts(t *testing.T) {
|
||||
l := &Lifecycle{Registry: NewMemoryActivityRegistry(nil), Inbox: NewMemoryNoticeInbox(nil)}
|
||||
ctx := context.Background()
|
||||
require.NoError(t, l.Begin(ctx, lcSess, lcActivity("sj_1"), time.Minute, 0,
|
||||
func(context.Context) error { return nil }))
|
||||
_, err := l.Alive(ctx, lcSess, "sj_1", time.Minute)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, l.Finish(ctx, lcSess, interfaces.BackgroundNotice{ID: "sj_1", FinishedAt: time.Now()},
|
||||
interfaces.WorkResult{ID: "sj_1"}, ""))
|
||||
}
|
||||
|
||||
type failingInbox struct{}
|
||||
|
||||
func (failingInbox) Push(context.Context, interfaces.SessionRef, interfaces.BackgroundNotice) (bool, error) {
|
||||
return false, errors.New("redis down")
|
||||
}
|
||||
|
||||
func (failingInbox) Pending(context.Context, interfaces.SessionRef) ([]interfaces.BackgroundNotice, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (failingInbox) Ack(context.Context, interfaces.SessionRef, []string) error { return nil }
|
||||
|
||||
func (failingInbox) Clear(context.Context, interfaces.SessionRef) error { return nil }
|
||||
@@ -0,0 +1,103 @@
|
||||
package background
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// Listeners is the ordered set of session lifecycle listeners. Feature
|
||||
// listeners run in registration order; on delete the shared activity
|
||||
// registry and inbox are cleared after all of them have run.
|
||||
type Listeners struct {
|
||||
registry interfaces.ActivityRegistry
|
||||
inbox interfaces.NoticeInbox
|
||||
logf func(ctx context.Context, format string, args ...any)
|
||||
|
||||
mu sync.RWMutex
|
||||
listeners []interfaces.SessionLifecycleListener
|
||||
}
|
||||
|
||||
// NewListeners returns an empty listener set. A nil logf discards warnings.
|
||||
func NewListeners(
|
||||
registry interfaces.ActivityRegistry,
|
||||
inbox interfaces.NoticeInbox,
|
||||
logf func(ctx context.Context, format string, args ...any),
|
||||
) *Listeners {
|
||||
if logf == nil {
|
||||
logf = func(context.Context, string, ...any) {}
|
||||
}
|
||||
return &Listeners{registry: registry, inbox: inbox, logf: logf}
|
||||
}
|
||||
|
||||
// Register appends a listener.
|
||||
func (l *Listeners) Register(listener interfaces.SessionLifecycleListener) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.listeners = append(l.listeners, listener)
|
||||
}
|
||||
|
||||
func (l *Listeners) snapshot() []interfaces.SessionLifecycleListener {
|
||||
l.mu.RLock()
|
||||
defer l.mu.RUnlock()
|
||||
return append([]interfaces.SessionLifecycleListener(nil), l.listeners...)
|
||||
}
|
||||
|
||||
// NotifyStop calls OnStop on every listener. Errors are logged, never returned.
|
||||
func (l *Listeners) NotifyStop(ctx context.Context, s interfaces.SessionRef) {
|
||||
for _, listener := range l.snapshot() {
|
||||
if err := listener.OnStop(ctx, s); err != nil {
|
||||
l.logf(ctx, "[Background] OnStop listener failed session=%s: %v", s.SessionID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NotifyDelete calls OnDelete on every listener, then clears the session's
|
||||
// activity items and notices. A failed stop preserves shared state and keeps
|
||||
// the session available for a retry, especially on a retained shared machine.
|
||||
func (l *Listeners) NotifyDelete(ctx context.Context, s interfaces.SessionRef) error {
|
||||
var failures []error
|
||||
for _, listener := range l.snapshot() {
|
||||
if err := listener.OnDelete(ctx, s); err != nil {
|
||||
l.logf(ctx, "[Background] OnDelete listener failed session=%s: %v", s.SessionID, err)
|
||||
failures = append(failures, err)
|
||||
}
|
||||
}
|
||||
if err := errors.Join(failures...); err != nil {
|
||||
return err
|
||||
}
|
||||
if l.registry != nil {
|
||||
items, err := l.registry.List(ctx, s)
|
||||
if err != nil {
|
||||
l.logf(ctx, "[Background] list activity on delete failed session=%s: %v", s.SessionID, err)
|
||||
}
|
||||
for _, it := range items {
|
||||
if err := l.registry.Remove(ctx, s, it.ID); err != nil {
|
||||
l.logf(ctx, "[Background] remove activity on delete failed session=%s id=%s: %v",
|
||||
s.SessionID, it.ID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if l.inbox != nil {
|
||||
if err := l.inbox.Clear(ctx, s); err != nil {
|
||||
l.logf(ctx, "[Background] clear inbox on delete failed session=%s: %v", s.SessionID, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// NotifyDeleteAborted reopens submission gates when a listener or the session
|
||||
// repository rejected deletion. Already stopped jobs remain stopped.
|
||||
func (l *Listeners) NotifyDeleteAborted(ctx context.Context, s interfaces.SessionRef) {
|
||||
for _, listener := range l.snapshot() {
|
||||
if rollback, ok := listener.(interface {
|
||||
OnDeleteAborted(context.Context, interfaces.SessionRef) error
|
||||
}); ok {
|
||||
if err := rollback.OnDeleteAborted(ctx, s); err != nil {
|
||||
l.logf(ctx, "[Background] reopen session after failed deletion session=%s: %v", s.SessionID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package background
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type recordingListener struct {
|
||||
name string
|
||||
log *[]string
|
||||
err error
|
||||
}
|
||||
|
||||
func (l recordingListener) OnStop(context.Context, interfaces.SessionRef) error {
|
||||
*l.log = append(*l.log, l.name+":stop")
|
||||
return l.err
|
||||
}
|
||||
|
||||
func (l recordingListener) OnDelete(context.Context, interfaces.SessionRef) error {
|
||||
*l.log = append(*l.log, l.name+":delete")
|
||||
return l.err
|
||||
}
|
||||
|
||||
func TestListenersRunInOrderAndSurviveErrors(t *testing.T) {
|
||||
var log []string
|
||||
var warnings []string
|
||||
logf := func(_ context.Context, format string, args ...any) {
|
||||
warnings = append(warnings, fmt.Sprintf(format, args...))
|
||||
}
|
||||
l := NewListeners(NewMemoryActivityRegistry(nil), NewMemoryNoticeInbox(nil), logf)
|
||||
l.Register(recordingListener{name: "a", log: &log, err: errors.New("a failed")})
|
||||
l.Register(recordingListener{name: "b", log: &log})
|
||||
|
||||
s := interfaces.SessionRef{TenantID: 1, SessionID: "s"}
|
||||
l.NotifyStop(context.Background(), s)
|
||||
require.ErrorContains(t, l.NotifyDelete(context.Background(), s), "a failed")
|
||||
|
||||
require.Equal(t, []string{"a:stop", "b:stop", "a:delete", "b:delete"}, log)
|
||||
require.Len(t, warnings, 2)
|
||||
}
|
||||
|
||||
func TestNotifyDeleteClearsSharedStateLast(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s := interfaces.SessionRef{TenantID: 1, SessionID: "s"}
|
||||
registry := NewMemoryActivityRegistry(nil)
|
||||
inbox := NewMemoryNoticeInbox(nil)
|
||||
require.NoError(t, registry.Add(ctx, s, interfaces.BackgroundActivity{ID: "sj_1", Kind: "k"}, time.Hour, 0))
|
||||
_, err := inbox.Push(ctx, s, interfaces.BackgroundNotice{ID: "sj_0", FinishedAt: time.Now()})
|
||||
require.NoError(t, err)
|
||||
|
||||
var sawDuringListener int
|
||||
l := NewListeners(registry, inbox, nil)
|
||||
l.Register(listenerFunc(func(ctx context.Context, s interfaces.SessionRef) {
|
||||
items, _ := registry.List(ctx, s)
|
||||
sawDuringListener = len(items)
|
||||
}))
|
||||
|
||||
require.NoError(t, l.NotifyDelete(ctx, s))
|
||||
|
||||
require.Equal(t, 1, sawDuringListener, "feature listeners must run before shared state is cleared")
|
||||
items, err := registry.List(ctx, s)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, items)
|
||||
pending, err := inbox.Pending(ctx, s)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, pending)
|
||||
}
|
||||
|
||||
func TestNotifyStopKeepsSharedState(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s := interfaces.SessionRef{TenantID: 1, SessionID: "s"}
|
||||
registry := NewMemoryActivityRegistry(nil)
|
||||
require.NoError(t, registry.Add(ctx, s, interfaces.BackgroundActivity{ID: "sj_1", Kind: "k"}, time.Hour, 0))
|
||||
|
||||
NewListeners(registry, NewMemoryNoticeInbox(nil), nil).NotifyStop(ctx, s)
|
||||
|
||||
items, err := registry.List(ctx, s)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, 1)
|
||||
}
|
||||
|
||||
type listenerFunc func(ctx context.Context, s interfaces.SessionRef)
|
||||
|
||||
func (f listenerFunc) OnStop(context.Context, interfaces.SessionRef) error { return nil }
|
||||
|
||||
func (f listenerFunc) OnDelete(ctx context.Context, s interfaces.SessionRef) error {
|
||||
f(ctx, s)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package background
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// MemoryNoticeInbox is the single-process NoticeInbox used by Lite.
|
||||
type MemoryNoticeInbox struct {
|
||||
clock Clock
|
||||
mu sync.Mutex
|
||||
notices map[interfaces.SessionRef]map[string]interfaces.BackgroundNotice
|
||||
}
|
||||
|
||||
var _ interfaces.NoticeInbox = (*MemoryNoticeInbox)(nil)
|
||||
|
||||
// NewMemoryNoticeInbox returns an empty inbox. A nil clock means SystemClock.
|
||||
func NewMemoryNoticeInbox(clock Clock) *MemoryNoticeInbox {
|
||||
if clock == nil {
|
||||
clock = SystemClock{}
|
||||
}
|
||||
return &MemoryNoticeInbox{
|
||||
clock: clock,
|
||||
notices: make(map[interfaces.SessionRef]map[string]interfaces.BackgroundNotice),
|
||||
}
|
||||
}
|
||||
|
||||
// Push implements interfaces.NoticeInbox.
|
||||
func (b *MemoryNoticeInbox) Push(
|
||||
_ context.Context, s interfaces.SessionRef, n interfaces.BackgroundNotice,
|
||||
) (bool, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
m := b.notices[s]
|
||||
if _, ok := m[n.ID]; ok {
|
||||
return false, nil
|
||||
}
|
||||
if m == nil {
|
||||
m = make(map[string]interfaces.BackgroundNotice)
|
||||
b.notices[s] = m
|
||||
}
|
||||
m[n.ID] = n
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Pending implements interfaces.NoticeInbox.
|
||||
func (b *MemoryNoticeInbox) Pending(
|
||||
_ context.Context, s interfaces.SessionRef,
|
||||
) ([]interfaces.BackgroundNotice, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
cutoff := b.clock.Now().Add(-interfaces.NoticeRetention)
|
||||
m := b.notices[s]
|
||||
out := make([]interfaces.BackgroundNotice, 0, len(m))
|
||||
for id, n := range m {
|
||||
if n.FinishedAt.Before(cutoff) {
|
||||
delete(m, id)
|
||||
continue
|
||||
}
|
||||
out = append(out, n)
|
||||
}
|
||||
if len(m) == 0 {
|
||||
delete(b.notices, s)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].FinishedAt.Equal(out[j].FinishedAt) {
|
||||
return out[i].ID < out[j].ID
|
||||
}
|
||||
return out[i].FinishedAt.Before(out[j].FinishedAt)
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Ack implements interfaces.NoticeInbox.
|
||||
func (b *MemoryNoticeInbox) Ack(_ context.Context, s interfaces.SessionRef, ids []string) error {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
m := b.notices[s]
|
||||
for _, id := range ids {
|
||||
delete(m, id)
|
||||
}
|
||||
if len(m) == 0 {
|
||||
delete(b.notices, s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Clear implements interfaces.NoticeInbox.
|
||||
func (b *MemoryNoticeInbox) Clear(_ context.Context, s interfaces.SessionRef) error {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
delete(b.notices, s)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// Package background holds the shared background-work parts: in-memory
|
||||
// implementations, the lifecycle-listener registry and the lifecycle helpers.
|
||||
// It must not branch on activity kind.
|
||||
package background
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// Clock abstracts time so tests can move it.
|
||||
type Clock interface {
|
||||
Now() time.Time
|
||||
}
|
||||
|
||||
// SystemClock is the real wall clock.
|
||||
type SystemClock struct{}
|
||||
|
||||
// Now returns time.Now().
|
||||
func (SystemClock) Now() time.Time { return time.Now() }
|
||||
|
||||
type memoryActivity struct {
|
||||
item interfaces.BackgroundActivity
|
||||
deadline time.Time
|
||||
}
|
||||
|
||||
// MemoryActivityRegistry is the single-process ActivityRegistry used by Lite.
|
||||
type MemoryActivityRegistry struct {
|
||||
clock Clock
|
||||
mu sync.Mutex
|
||||
items map[interfaces.SessionRef]map[string]memoryActivity
|
||||
}
|
||||
|
||||
var _ interfaces.ActivityRegistry = (*MemoryActivityRegistry)(nil)
|
||||
|
||||
// NewMemoryActivityRegistry returns an empty registry. A nil clock means SystemClock.
|
||||
func NewMemoryActivityRegistry(clock Clock) *MemoryActivityRegistry {
|
||||
if clock == nil {
|
||||
clock = SystemClock{}
|
||||
}
|
||||
return &MemoryActivityRegistry{
|
||||
clock: clock,
|
||||
items: make(map[interfaces.SessionRef]map[string]memoryActivity),
|
||||
}
|
||||
}
|
||||
|
||||
// liveLocked drops expired items of s and returns what remains. Caller holds mu.
|
||||
func (r *MemoryActivityRegistry) liveLocked(s interfaces.SessionRef, now time.Time) map[string]memoryActivity {
|
||||
m := r.items[s]
|
||||
for id, it := range m {
|
||||
if !now.Before(it.deadline) {
|
||||
delete(m, id)
|
||||
}
|
||||
}
|
||||
if len(m) == 0 {
|
||||
delete(r.items, s)
|
||||
return nil
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// Add implements interfaces.ActivityRegistry.
|
||||
func (r *MemoryActivityRegistry) Add(
|
||||
_ context.Context, s interfaces.SessionRef, a interfaces.BackgroundActivity, lease time.Duration, kindCap int,
|
||||
) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
now := r.clock.Now()
|
||||
m := r.liveLocked(s, now)
|
||||
if existing, ok := m[a.ID]; ok {
|
||||
existing.deadline = now.Add(lease)
|
||||
m[a.ID] = existing
|
||||
return nil
|
||||
}
|
||||
if kindCap > 0 {
|
||||
count := 0
|
||||
for _, it := range m {
|
||||
if it.item.Kind == a.Kind {
|
||||
count++
|
||||
}
|
||||
}
|
||||
if count >= kindCap {
|
||||
return interfaces.ErrActivityLimit
|
||||
}
|
||||
}
|
||||
if m == nil {
|
||||
m = make(map[string]memoryActivity)
|
||||
r.items[s] = m
|
||||
}
|
||||
m[a.ID] = memoryActivity{item: a, deadline: now.Add(lease)}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Renew implements interfaces.ActivityRegistry.
|
||||
func (r *MemoryActivityRegistry) Renew(
|
||||
_ context.Context, s interfaces.SessionRef, id string, lease time.Duration,
|
||||
) (bool, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
now := r.clock.Now()
|
||||
m := r.liveLocked(s, now)
|
||||
it, ok := m[id]
|
||||
if !ok {
|
||||
return false, nil
|
||||
}
|
||||
it.deadline = now.Add(lease)
|
||||
m[id] = it
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Remove implements interfaces.ActivityRegistry.
|
||||
func (r *MemoryActivityRegistry) Remove(_ context.Context, s interfaces.SessionRef, id string) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if m := r.items[s]; m != nil {
|
||||
delete(m, id)
|
||||
if len(m) == 0 {
|
||||
delete(r.items, s)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// List implements interfaces.ActivityRegistry.
|
||||
func (r *MemoryActivityRegistry) List(
|
||||
_ context.Context, s interfaces.SessionRef,
|
||||
) ([]interfaces.BackgroundActivity, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
m := r.liveLocked(s, r.clock.Now())
|
||||
out := make([]interfaces.BackgroundActivity, 0, len(m))
|
||||
for _, it := range m {
|
||||
out = append(out, it.item)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package background
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/background/backgroundtest"
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
type fakeClock struct {
|
||||
mu sync.Mutex
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func newFakeClock() *fakeClock {
|
||||
return &fakeClock{now: time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC)}
|
||||
}
|
||||
|
||||
func (c *fakeClock) Now() time.Time {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.now
|
||||
}
|
||||
|
||||
func (c *fakeClock) Advance(d time.Duration) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.now = c.now.Add(d)
|
||||
}
|
||||
|
||||
func TestMemoryActivityRegistryContract(t *testing.T) {
|
||||
backgroundtest.RunActivityRegistryContract(t,
|
||||
func(*testing.T) (interfaces.ActivityRegistry, backgroundtest.Advance) {
|
||||
clock := newFakeClock()
|
||||
return NewMemoryActivityRegistry(clock), clock.Advance
|
||||
})
|
||||
}
|
||||
|
||||
func TestMemoryNoticeInboxContract(t *testing.T) {
|
||||
backgroundtest.RunNoticeInboxContract(t,
|
||||
func(*testing.T) (interfaces.NoticeInbox, backgroundtest.Advance) {
|
||||
clock := newFakeClock()
|
||||
return NewMemoryNoticeInbox(clock), clock.Advance
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package background
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"academy/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// Delivery is background-work context for the model at one round boundary.
|
||||
type Delivery struct {
|
||||
// Text is the model-facing body, one line per entry, without a wrapper.
|
||||
Text string
|
||||
// AckIDs are the completion notices Text delivers. They are acknowledged
|
||||
// once the assistant message carrying them is persisted.
|
||||
AckIDs []string
|
||||
}
|
||||
|
||||
// RunNotices decides, for one agent run, what the model is told about
|
||||
// background work and when. A run executes in one process, so its sets live in
|
||||
// memory; the shared registry and inbox are only read here.
|
||||
type RunNotices struct {
|
||||
session interfaces.SessionRef
|
||||
registry interfaces.ActivityRegistry
|
||||
inbox interfaces.NoticeInbox
|
||||
|
||||
mu sync.Mutex
|
||||
listed bool
|
||||
seen map[string]bool
|
||||
started map[string]bool
|
||||
reminded map[string]bool
|
||||
newSeen []string
|
||||
}
|
||||
|
||||
// NewRunNotices returns a tracker for one run of session s.
|
||||
func NewRunNotices(
|
||||
s interfaces.SessionRef, registry interfaces.ActivityRegistry, inbox interfaces.NoticeInbox,
|
||||
) *RunNotices {
|
||||
return &RunNotices{
|
||||
session: s,
|
||||
registry: registry,
|
||||
inbox: inbox,
|
||||
seen: make(map[string]bool),
|
||||
started: make(map[string]bool),
|
||||
reminded: make(map[string]bool),
|
||||
}
|
||||
}
|
||||
|
||||
// MarkStarted records work this run submitted and got back as still running.
|
||||
// Only such work is reminded about before the final answer.
|
||||
func (r *RunNotices) MarkStarted(id string) {
|
||||
if id == "" {
|
||||
return
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.started[id] = true
|
||||
}
|
||||
|
||||
// MarkSeen records finished IDs a tool already showed the model, so their
|
||||
// notices are not injected again and are acknowledged with the turn.
|
||||
func (r *RunNotices) MarkSeen(ids ...string) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for _, id := range ids {
|
||||
if id == "" || r.seen[id] {
|
||||
continue
|
||||
}
|
||||
r.seen[id] = true
|
||||
r.newSeen = append(r.newSeen, id)
|
||||
}
|
||||
}
|
||||
|
||||
// TakeSeen returns the IDs MarkSeen recorded since the previous call.
|
||||
func (r *RunNotices) TakeSeen() []string {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
out := r.newSeen
|
||||
r.newSeen = nil
|
||||
return out
|
||||
}
|
||||
|
||||
// RoundStart returns what to tell the model before a round's LLM call: on the
|
||||
// run's first boundary, the work still running; on every boundary, completion
|
||||
// notices this run has not seen.
|
||||
func (r *RunNotices) RoundStart(ctx context.Context) (Delivery, error) {
|
||||
r.mu.Lock()
|
||||
first := !r.listed
|
||||
r.mu.Unlock()
|
||||
|
||||
var lines []string
|
||||
if first {
|
||||
live, err := r.registry.List(ctx, r.session)
|
||||
if err != nil {
|
||||
return Delivery{}, fmt.Errorf("list background work: %w", err)
|
||||
}
|
||||
if len(live) > 0 {
|
||||
lines = append(lines, "Background work still running in this session: "+describeActivities(live)+".")
|
||||
}
|
||||
}
|
||||
notices, err := r.inbox.Pending(ctx, r.session)
|
||||
if err != nil {
|
||||
return Delivery{}, fmt.Errorf("read background notices: %w", err)
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.listed = true
|
||||
return r.deliverLocked(notices, lines), nil
|
||||
}
|
||||
|
||||
// BeforeFinal returns what to tell the model before it may finish: unseen
|
||||
// completion notices, and one reminder for each item this run started that is
|
||||
// still running and has not been reminded about.
|
||||
func (r *RunNotices) BeforeFinal(ctx context.Context) (Delivery, error) {
|
||||
notices, err := r.inbox.Pending(ctx, r.session)
|
||||
if err != nil {
|
||||
return Delivery{}, fmt.Errorf("read background notices: %w", err)
|
||||
}
|
||||
live, err := r.registry.List(ctx, r.session)
|
||||
if err != nil {
|
||||
return Delivery{}, fmt.Errorf("list background work: %w", err)
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
var remind []interfaces.BackgroundActivity
|
||||
for _, item := range live {
|
||||
if r.started[item.ID] && !r.reminded[item.ID] {
|
||||
remind = append(remind, item)
|
||||
}
|
||||
}
|
||||
var lines []string
|
||||
if len(remind) > 0 {
|
||||
for _, item := range remind {
|
||||
r.reminded[item.ID] = true
|
||||
}
|
||||
lines = append(lines, "Background work you started in this turn is still running: "+
|
||||
describeActivities(remind)+
|
||||
". Finish your answer. Its result will arrive when it completes. "+
|
||||
"Call work_wait only if you cannot answer without that output.")
|
||||
}
|
||||
return r.deliverLocked(notices, lines), nil
|
||||
}
|
||||
|
||||
// deliverLocked puts unseen notices first, then lines, and marks the notices
|
||||
// seen. Caller holds mu.
|
||||
func (r *RunNotices) deliverLocked(notices []interfaces.BackgroundNotice, lines []string) Delivery {
|
||||
var d Delivery
|
||||
text := make([]string, 0, len(notices)+len(lines))
|
||||
for _, n := range notices {
|
||||
if r.seen[n.ID] || strings.TrimSpace(n.Text) == "" {
|
||||
continue
|
||||
}
|
||||
r.seen[n.ID] = true
|
||||
text = append(text, n.Text)
|
||||
d.AckIDs = append(d.AckIDs, n.ID)
|
||||
}
|
||||
text = append(text, lines...)
|
||||
d.Text = strings.Join(text, "\n")
|
||||
return d
|
||||
}
|
||||
|
||||
// describeActivities renders items as "title (id)" in start order.
|
||||
func describeActivities(items []interfaces.BackgroundActivity) string {
|
||||
sorted := append([]interfaces.BackgroundActivity(nil), items...)
|
||||
sort.Slice(sorted, func(i, j int) bool {
|
||||
if sorted[i].StartedAt.Equal(sorted[j].StartedAt) {
|
||||
return sorted[i].ID < sorted[j].ID
|
||||
}
|
||||
return sorted[i].StartedAt.Before(sorted[j].StartedAt)
|
||||
})
|
||||
parts := make([]string, 0, len(sorted))
|
||||
for _, item := range sorted {
|
||||
if item.Title == "" {
|
||||
parts = append(parts, item.ID)
|
||||
continue
|
||||
}
|
||||
parts = append(parts, fmt.Sprintf("%s (%s)", item.Title, item.ID))
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package background
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types/interfaces"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
var noticeSession = interfaces.SessionRef{TenantID: 1, SessionID: "s"}
|
||||
|
||||
func newNoticeFixture(t *testing.T) (*RunNotices, *MemoryActivityRegistry, *MemoryNoticeInbox) {
|
||||
t.Helper()
|
||||
reg := NewMemoryActivityRegistry(nil)
|
||||
inbox := NewMemoryNoticeInbox(nil)
|
||||
return NewRunNotices(noticeSession, reg, inbox), reg, inbox
|
||||
}
|
||||
|
||||
func addRunning(t *testing.T, reg *MemoryActivityRegistry, id, title string, started time.Time) {
|
||||
t.Helper()
|
||||
require.NoError(t, reg.Add(context.Background(), noticeSession, interfaces.BackgroundActivity{
|
||||
ID: id, Kind: "shell_job", Title: title, StartedAt: started,
|
||||
}, time.Hour, 0))
|
||||
}
|
||||
|
||||
func pushNotice(t *testing.T, inbox *MemoryNoticeInbox, id, text string) {
|
||||
t.Helper()
|
||||
_, err := inbox.Push(context.Background(), noticeSession, interfaces.BackgroundNotice{
|
||||
ID: id, Kind: "shell_job", Text: text, FinishedAt: time.Now(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestRunNoticesListsRunningWorkOnFirstRoundOnly(t *testing.T) {
|
||||
r, reg, _ := newNoticeFixture(t)
|
||||
base := time.Now()
|
||||
addRunning(t, reg, "sj_b", "tests", base.Add(time.Second))
|
||||
addRunning(t, reg, "sj_a", "build", base)
|
||||
|
||||
first, err := r.RoundStart(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "Background work still running in this session: build (sj_a), tests (sj_b).", first.Text)
|
||||
require.Empty(t, first.AckIDs)
|
||||
|
||||
second, err := r.RoundStart(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, second.Text)
|
||||
}
|
||||
|
||||
func TestRunNoticesDeliversEachNoticeOnce(t *testing.T) {
|
||||
r, _, inbox := newNoticeFixture(t)
|
||||
pushNotice(t, inbox, "sj_1", "build (sj_1) succeeded.")
|
||||
|
||||
got, err := r.RoundStart(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "build (sj_1) succeeded.", got.Text)
|
||||
require.Equal(t, []string{"sj_1"}, got.AckIDs)
|
||||
|
||||
pushNotice(t, inbox, "sj_2", "tests (sj_2) failed.")
|
||||
got, err = r.BeforeFinal(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "tests (sj_2) failed.", got.Text, "sj_1 was already delivered this run")
|
||||
require.Equal(t, []string{"sj_2"}, got.AckIDs)
|
||||
}
|
||||
|
||||
func TestRunNoticesSkipsNoticesAToolAlreadyShowed(t *testing.T) {
|
||||
r, _, inbox := newNoticeFixture(t)
|
||||
pushNotice(t, inbox, "sj_1", "build (sj_1) succeeded.")
|
||||
|
||||
r.MarkSeen("sj_1", "sj_1", "")
|
||||
require.Equal(t, []string{"sj_1"}, r.TakeSeen())
|
||||
require.Empty(t, r.TakeSeen())
|
||||
|
||||
got, err := r.RoundStart(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, got.Text)
|
||||
require.Empty(t, got.AckIDs)
|
||||
}
|
||||
|
||||
func TestRunNoticesRemindsOnlyWorkThisRunStarted(t *testing.T) {
|
||||
r, reg, _ := newNoticeFixture(t)
|
||||
base := time.Now()
|
||||
addRunning(t, reg, "sj_old", "dev server", base)
|
||||
addRunning(t, reg, "sj_new", "build", base.Add(time.Second))
|
||||
r.MarkStarted("sj_new")
|
||||
|
||||
got, err := r.BeforeFinal(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "Background work you started in this turn is still running: build (sj_new). "+
|
||||
"Finish your answer. Its result will arrive when it completes. "+
|
||||
"Call work_wait only if you cannot answer without that output.", got.Text)
|
||||
|
||||
again, err := r.BeforeFinal(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, again.Text, "each item is reminded once")
|
||||
}
|
||||
|
||||
func TestRunNoticesPutsNoticesBeforeOtherLines(t *testing.T) {
|
||||
r, reg, inbox := newNoticeFixture(t)
|
||||
addRunning(t, reg, "sj_a", "build", time.Now())
|
||||
pushNotice(t, inbox, "sj_0", "lint (sj_0) succeeded.")
|
||||
|
||||
got, err := r.RoundStart(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "lint (sj_0) succeeded.\nBackground work still running in this session: build (sj_a).", got.Text)
|
||||
}
|
||||
|
||||
type failingRegistry struct {
|
||||
interfaces.ActivityRegistry
|
||||
err error
|
||||
}
|
||||
|
||||
func (f failingRegistry) List(context.Context, interfaces.SessionRef) ([]interfaces.BackgroundActivity, error) {
|
||||
return nil, f.err
|
||||
}
|
||||
|
||||
func TestRunNoticesRetriesTheListingAfterAnError(t *testing.T) {
|
||||
reg := NewMemoryActivityRegistry(nil)
|
||||
r := NewRunNotices(noticeSession, failingRegistry{ActivityRegistry: reg, err: errors.New("redis down")},
|
||||
NewMemoryNoticeInbox(nil))
|
||||
addRunning(t, reg, "sj_a", "build", time.Now())
|
||||
|
||||
_, err := r.RoundStart(context.Background())
|
||||
require.Error(t, err)
|
||||
|
||||
r.registry = reg // the store recovers
|
||||
got, err := r.RoundStart(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, got.Text, "build (sj_a)", "a failed first boundary must not use up the listing")
|
||||
}
|
||||
Reference in new issue
Block a user