Skip to content

armgit / ax

Public Imported from GitHub
0

Agent Executor (AX) is Google's open agentic orchestration runtime

Go

Make controller2 use its own eventlog package (#153)

Jaana Dogana470ffb0ebba
diff --git a/cmd/ax/internal/cliutil/cliutil_harness.go b/cmd/ax/internal/cliutil/cliutil_harness.go
index 08a65ad..6a02e3f 100644
--- a/cmd/ax/internal/cliutil/cliutil_harness.go
+++ b/cmd/ax/internal/cliutil/cliutil_harness.go
@@ -22,7 +22,7 @@ import (
"os"
"github.com/google/ax/internal/config2"
- "github.com/google/ax/internal/controller/executor"
+ "github.com/google/ax/internal/controller2/eventlog"
"github.com/google/ax/internal/controller2"
"github.com/google/ax/internal/harness"
)
@@ -109,8 +109,8 @@ func NewControllerFromConfig(ctx context.Context, cfg *Config) (*controller2.Con
return controller2.New(ctx, controller2.Config{
Registry: reg,
- EventLogBuilder: func() (executor.EventLog, error) {
- return executor.OpenSQLiteEventLog(cfg.EventLog.SQLiteConfig.Filename)
+ EventLogBuilder: func() (eventlog.EventLog, error) {
+ return eventlog.OpenSQLiteEventLog(cfg.EventLog.SQLiteConfig.Filename)
},
})
}
diff --git a/cmd/e2e/main.go b/cmd/e2e/main.go
index b72cc94..fd0a3ce 100644
--- a/cmd/e2e/main.go
+++ b/cmd/e2e/main.go
@@ -33,8 +33,8 @@ import (
"os"
"time"
- "github.com/google/ax/internal/controller/executor"
- "github.com/google/ax/internal/controller/executor/executortest"
+ "github.com/google/ax/internal/controller2/eventlog"
+ "github.com/google/ax/internal/controller2/eventlog/eventlogtest"
"github.com/google/ax/internal/controller2"
"github.com/google/ax/internal/harness"
"github.com/google/ax/proto"
@@ -82,10 +82,10 @@ func runDemo(ctx context.Context, agentID string, setupRegistry func(reg *contro
reg := controller2.NewRegistry()
setupRegistry(reg)
- log := &executortest.MemoryEventLog{}
+ log := &eventlogtest.MemoryEventLog{}
c, err := controller2.New(ctx, controller2.Config{
Registry: reg,
- EventLogBuilder: func() (executor.EventLog, error) {
+ EventLogBuilder: func() (eventlog.EventLog, error) {
return log, nil
},
})
diff --git a/internal/controller2/controller.go b/internal/controller2/controller.go
index c40c299..d6fe508 100644
--- a/internal/controller2/controller.go
+++ b/internal/controller2/controller.go
@@ -21,7 +21,7 @@ import (
"fmt"
"log/slog"
- "github.com/google/ax/internal/controller/executor"
+ "github.com/google/ax/internal/controller2/eventlog"
"github.com/google/ax/proto"
)
@@ -31,13 +31,13 @@ type ExecHandler func(resp *proto.ExecResponse) error
// It acts as a single-writer system for managing agentic loops.
type Controller struct {
registry *Registry
- eventLog executor.EventLog
+ eventLog eventlog.EventLog
}
// Config configures the controller.
type Config struct {
Registry *Registry
- EventLogBuilder executor.EventLogBuilder
+ EventLogBuilder eventlog.EventLogBuilder
}
// New creates a new controller instance.
@@ -110,7 +110,7 @@ func (d *Controller) Exec(ctx context.Context, req *proto.ExecRequest, handler E
type harnessHandler struct {
conversationID string
- eventLog executor.EventLog
+ eventLog eventlog.EventLog
execHandler ExecHandler
}
@@ -160,7 +160,7 @@ func (d *Controller) Delete(ctx context.Context, conversationID string) error {
return fmt.Errorf("conversation_id is required")
}
- return d.eventLog.DeleteEvents(ctx, conversationID)
+ return d.eventLog.DeleteAll(ctx, conversationID)
}
// Registry returns the agent registry.
diff --git a/internal/controller2/controller_test.go b/internal/controller2/controller_test.go
index f51fd3d..faefced 100644
--- a/internal/controller2/controller_test.go
+++ b/internal/controller2/controller_test.go
@@ -18,8 +18,8 @@ import (
"context"
"testing"
- "github.com/google/ax/internal/controller/executor"
- "github.com/google/ax/internal/controller/executor/executortest"
+ "github.com/google/ax/internal/controller2/eventlog"
+ "github.com/google/ax/internal/controller2/eventlog/eventlogtest"
"github.com/google/ax/internal/harness"
"github.com/google/ax/proto"
)
@@ -69,7 +69,7 @@ func TestController2_ExecHelloWorld(t *testing.T) {
ctx := context.Background()
cid := "test-conversation-id"
- log := &executortest.MemoryEventLog{}
+ log := &eventlogtest.MemoryEventLog{}
reg := NewRegistry()
if err := reg.RegisterHarness("", &fakeHarness{}); err != nil {
t.Fatal(err)
@@ -77,7 +77,7 @@ func TestController2_ExecHelloWorld(t *testing.T) {
c, err := New(ctx, Config{
Registry: reg,
- EventLogBuilder: func() (executor.EventLog, error) {
+ EventLogBuilder: func() (eventlog.EventLog, error) {
return log, nil
},
})
@@ -174,7 +174,7 @@ func TestController2_ExecWithAgentID(t *testing.T) {
ctx := context.Background()
cid := "test-conversation-id"
- log := &executortest.MemoryEventLog{}
+ log := &eventlogtest.MemoryEventLog{}
reg := NewRegistry()
if err := reg.RegisterHarness("my-agent", &fakeHarness{}); err != nil {
t.Fatal(err)
@@ -182,7 +182,7 @@ func TestController2_ExecWithAgentID(t *testing.T) {
c, err := New(ctx, Config{
Registry: reg,
- EventLogBuilder: func() (executor.EventLog, error) {
+ EventLogBuilder: func() (eventlog.EventLog, error) {
return log, nil
},
})
@@ -231,12 +231,12 @@ func TestController2_ExecHarnessNotFound(t *testing.T) {
ctx := context.Background()
cid := "test-conversation-id"
- log := &executortest.MemoryEventLog{}
+ log := &eventlogtest.MemoryEventLog{}
reg := NewRegistry() // Empty registry, will force error for any requested agent
c, err := New(ctx, Config{
Registry: reg,
- EventLogBuilder: func() (executor.EventLog, error) {
+ EventLogBuilder: func() (eventlog.EventLog, error) {
return log, nil
},
})
diff --git a/internal/controller2/eventlog/eventlog.go b/internal/controller2/eventlog/eventlog.go
new file mode 100644
index 0000000..f07c55a
--- /dev/null
+++ b/internal/controller2/eventlog/eventlog.go
@@ -0,0 +1,52 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package eventlog contains an AX event log.
+package eventlog
+
+import (
+ "context"
+
+ "github.com/google/ax/proto"
+ "google.golang.org/protobuf/encoding/protojson"
+)
+
+// EventLogBuilder builds new event logs.
+type EventLogBuilder func() (EventLog, error)
+
+// EventLog is the persistent, append-only record of all actions taken in an
+// exec. Every entry is an atomic step: replaying the log in order brings
+// the executor back to a consistent state from which execution can resume.
+type EventLog interface {
+ // Append adds a conversation event to the end of the log.
+ Append(ctx context.Context, event *proto.ConversationEvent) (int32, error)
+
+ // AppendExec adds an execution event to the end of the log.
+ AppendExec(ctx context.Context, event *proto.ExecutionEvent) error
+
+ // Events returns all events for the conversation.
+ Events(ctx context.Context, conversationID string) ([]*proto.ConversationEvent, error)
+
+ // ExecEvents returns all events for a specific execution ID.
+ ExecEvents(ctx context.Context, execID string) ([]*proto.ExecutionEvent, error)
+
+ // DeleteAll deletes all events for a specific conversation ID.
+ DeleteAll(ctx context.Context, conversationID string) error
+
+ // Close releases the underlying resources and closes the log.
+ Close() error
+}
+
+var marshalOpts = protojson.MarshalOptions{UseProtoNames: true}
+var unmarshalOpts = protojson.UnmarshalOptions{DiscardUnknown: true}
diff --git a/internal/controller2/eventlog/eventlogtest/eventlog.go b/internal/controller2/eventlog/eventlogtest/eventlog.go
new file mode 100644
index 0000000..b917b7c
--- /dev/null
+++ b/internal/controller2/eventlog/eventlogtest/eventlog.go
@@ -0,0 +1,137 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package eventlogtest
+
+import (
+ "context"
+ "sync"
+
+ "github.com/google/ax/proto"
+)
+
+// MemoryEventLog is an in-memory EventLog useful for testing and short-lived
+// executions. It does not survive process restarts.
+type MemoryEventLog struct {
+ mu sync.Mutex
+ AllEvents []*proto.ConversationEvent
+ AllExecEvents []*proto.ExecutionEvent
+}
+
+func (m *MemoryEventLog) Append(_ context.Context, event *proto.ConversationEvent) (int32, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ seq := event.Seq
+ if seq == 0 {
+ maxSeq := int32(0)
+ for _, ev := range m.AllEvents {
+ if ev.ConversationId == event.ConversationId && ev.Seq > maxSeq {
+ maxSeq = ev.Seq
+ }
+ }
+ seq = maxSeq + 1
+ event.Seq = seq
+ }
+ m.AllEvents = append(m.AllEvents, event)
+ return seq, nil
+}
+
+func (m *MemoryEventLog) AppendExec(_ context.Context, event *proto.ExecutionEvent) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ m.AllExecEvents = append(m.AllExecEvents, event)
+ return nil
+}
+
+func (m *MemoryEventLog) Events(_ context.Context, conversationID string) ([]*proto.ConversationEvent, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ out := make([]*proto.ConversationEvent, 0)
+ for _, ev := range m.AllEvents {
+ if ev.ConversationId == conversationID {
+ out = append(out, ev)
+ }
+ }
+ return out, nil
+}
+
+func (m *MemoryEventLog) ExecEvents(_ context.Context, execID string) ([]*proto.ExecutionEvent, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ out := make([]*proto.ExecutionEvent, 0)
+ for _, ev := range m.AllExecEvents {
+ if ev.ExecId == execID {
+ out = append(out, ev)
+ }
+ }
+ return out, nil
+}
+
+// Drop removes every event for which drop returns true.
+// It is provided for testing and crash-simulation purposes.
+func (m *MemoryEventLog) Drop(drop func(*proto.ConversationEvent) bool) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ kept := m.AllEvents[:0]
+ for _, ev := range m.AllEvents {
+ if !drop(ev) {
+ kept = append(kept, ev)
+ }
+ }
+ m.AllEvents = kept
+}
+
+func (m *MemoryEventLog) DeleteAll(_ context.Context, conversationID string) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ var execIDs []string
+ var keptEvents []*proto.ConversationEvent
+ for _, ev := range m.AllEvents {
+ if ev.ConversationId == conversationID {
+ if ev.ExecId != "" {
+ execIDs = append(execIDs, ev.ExecId)
+ }
+ } else {
+ keptEvents = append(keptEvents, ev)
+ }
+ }
+ m.AllEvents = keptEvents
+
+ var keptExecEvents []*proto.ExecutionEvent
+ for _, ev := range m.AllExecEvents {
+ delete := false
+ for _, id := range execIDs {
+ if ev.ExecId == id {
+ delete = true
+ break
+ }
+ }
+ if !delete {
+ keptExecEvents = append(keptExecEvents, ev)
+ }
+ }
+ m.AllExecEvents = keptExecEvents
+
+ return nil
+}
+
+func (m *MemoryEventLog) Close() error {
+ return nil
+}
diff --git a/internal/controller2/eventlog/sqlite.go b/internal/controller2/eventlog/sqlite.go
new file mode 100644
index 0000000..2ac4b97
--- /dev/null
+++ b/internal/controller2/eventlog/sqlite.go
@@ -0,0 +1,251 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package eventlog
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "os"
+ "path/filepath"
+ "time"
+
+ "github.com/google/ax/proto"
+ _ "modernc.org/sqlite"
+)
+
+// SQLiteEventLog is a durable EventLog that persists events in a SQLite database.
+// It is safe for concurrent use.
+type SQLiteEventLog struct {
+ db *sql.DB
+}
+
+const sqliteBusyTimeout = 10 * time.Second
+
+// OpenSQLiteEventLog opens (or creates) a SQLite database at path and initializes the event log schema.
+func OpenSQLiteEventLog(path string) (*SQLiteEventLog, error) {
+ dir := filepath.Dir(path)
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return nil, fmt.Errorf("sqlite_eventlog: mkdir %s: %w", dir, err)
+ }
+
+ dsn := fmt.Sprintf("%s?_pragma=busy_timeout(%d)", path, sqliteBusyTimeout.Milliseconds())
+ db, err := sql.Open("sqlite", dsn)
+ if err != nil {
+ return nil, fmt.Errorf("sqlite_eventlog: open %s: %w", dsn, err)
+ }
+
+ // Create tables if they don't exist
+ if _, err := db.Exec(`
+ CREATE TABLE IF NOT EXISTS conversation_log (
+ conversation_id TEXT NOT NULL,
+ seq INTEGER NOT NULL,
+ payload TEXT NOT NULL,
+ PRIMARY KEY (conversation_id, seq)
+ )`); err != nil {
+ db.Close()
+ return nil, fmt.Errorf("sqlite_eventlog: create conversation_log table: %w", err)
+ }
+
+ if _, err := db.Exec(`
+ CREATE TABLE IF NOT EXISTS execution_log (
+ exec_id TEXT NOT NULL,
+ payload TEXT NOT NULL,
+ timestamp DATETIME NOT NULL
+ )`); err != nil {
+ db.Close()
+ return nil, fmt.Errorf("sqlite_eventlog: create execution_log table: %w", err)
+ }
+
+ // Create indexes if they don't exist
+ if _, err := db.Exec(`CREATE INDEX IF NOT EXISTS idx_execution_log_exec_id ON execution_log(exec_id)`); err != nil {
+ db.Close()
+ return nil, fmt.Errorf("sqlite_eventlog: create index exec_id: %w", err)
+ }
+
+ return &SQLiteEventLog{db: db}, nil
+}
+
+// Append serializes the event to JSON and inserts it into the database.
+func (l *SQLiteEventLog) Append(ctx context.Context, event *proto.ConversationEvent) (int32, error) {
+ seq := event.Seq
+ if seq == 0 {
+ err := l.db.QueryRowContext(ctx, "SELECT COALESCE(MAX(seq), 0) + 1 FROM conversation_log WHERE conversation_id = ?", event.ConversationId).Scan(&seq)
+ if err != nil {
+ return 0, fmt.Errorf("sqlite_eventlog: compute seq: %w", err)
+ }
+ event.Seq = seq
+ }
+
+ payload, err := marshalOpts.Marshal(event)
+ if err != nil {
+ return 0, fmt.Errorf("sqlite_eventlog: marshal event: %w", err)
+ }
+
+ _, err = l.db.ExecContext(ctx,
+ "INSERT INTO conversation_log (conversation_id, seq, payload) VALUES (?, ?, ?)",
+ event.ConversationId, event.Seq, string(payload))
+
+ if err != nil {
+ return 0, fmt.Errorf("sqlite_eventlog: insert conversation: %w", err)
+ }
+
+ return seq, nil
+}
+
+// AppendExec inserts an execution event into the database.
+// TODO(anj): Remove execution_log table and AppendExec when legacy controller is removed.
+func (l *SQLiteEventLog) AppendExec(ctx context.Context, event *proto.ExecutionEvent) error {
+ payload, err := marshalOpts.Marshal(event)
+ if err != nil {
+ return fmt.Errorf("sqlite_eventlog: marshal exec: %w", err)
+ }
+
+ var timestamp time.Time
+ if event.Timestamp != nil {
+ timestamp = event.Timestamp.AsTime()
+ } else {
+ timestamp = time.Now()
+ }
+
+ _, err = l.db.ExecContext(ctx,
+ "INSERT INTO execution_log (exec_id, payload, timestamp) VALUES (?, ?, ?)",
+ event.ExecId, string(payload), timestamp)
+
+ if err != nil {
+ return fmt.Errorf("sqlite_eventlog: insert exec: %w", err)
+ }
+
+ return nil
+}
+
+// Events retrieves all events from the database for a conversation, ordered by seq and execution order.
+func (l *SQLiteEventLog) Events(ctx context.Context, conversationID string) ([]*proto.ConversationEvent, error) {
+ rows, err := l.db.QueryContext(ctx, "SELECT payload FROM conversation_log WHERE conversation_id = ? ORDER BY seq", conversationID)
+ if err != nil {
+ return nil, fmt.Errorf("sqlite_eventlog: query conversation: %w", err)
+ }
+ defer rows.Close()
+
+ var events []*proto.ConversationEvent
+ for rows.Next() {
+ var payload string
+ if err := rows.Scan(&payload); err != nil {
+ return nil, fmt.Errorf("sqlite_eventlog: scan conversation: %w", err)
+ }
+
+ ev := &proto.ConversationEvent{}
+ if err := unmarshalOpts.Unmarshal([]byte(payload), ev); err != nil {
+ return nil, fmt.Errorf("sqlite_eventlog: unmarshal event: %w", err)
+ }
+ events = append(events, ev)
+ }
+
+ if err := rows.Err(); err != nil {
+ return nil, fmt.Errorf("sqlite_eventlog: iterate conversation: %w", err)
+ }
+
+ return events, nil
+}
+
+// ExecEvents retrieves all events from the database for a specific execution ID.
+func (l *SQLiteEventLog) ExecEvents(ctx context.Context, execID string) ([]*proto.ExecutionEvent, error) {
+ rows, err := l.db.QueryContext(ctx, "SELECT payload FROM execution_log WHERE exec_id = ? ORDER BY timestamp", execID)
+ if err != nil {
+ return nil, fmt.Errorf("sqlite_eventlog: query exec: %w", err)
+ }
+ defer rows.Close()
+
+ var events []*proto.ExecutionEvent
+ for rows.Next() {
+ var payload string
+ if err := rows.Scan(&payload); err != nil {
+ return nil, fmt.Errorf("sqlite_eventlog: scan exec: %w", err)
+ }
+
+ ev := &proto.ExecutionEvent{}
+ if err := unmarshalOpts.Unmarshal([]byte(payload), ev); err != nil {
+ continue
+ }
+ events = append(events, ev)
+ }
+
+ if err := rows.Err(); err != nil {
+ return nil, fmt.Errorf("sqlite_eventlog: iterate exec: %w", err)
+ }
+
+ return events, nil
+}
+
+// DeleteAll deletes all events for a specific conversation ID and its child executions.
+func (l *SQLiteEventLog) DeleteAll(ctx context.Context, conversationID string) error {
+ tx, err := l.db.BeginTx(ctx, nil)
+ if err != nil {
+ return fmt.Errorf("sqlite_eventlog: begin tx: %w", err)
+ }
+ defer tx.Rollback()
+
+ // TODO(jbd): Update the schema to include conversation_id at every execution event.
+
+ // Get all exec_ids for this conversation
+ rows, err := tx.QueryContext(ctx, "SELECT payload FROM conversation_log WHERE conversation_id = ?", conversationID)
+ if err != nil {
+ return fmt.Errorf("sqlite_eventlog: query conversation: %w", err)
+ }
+ defer rows.Close()
+
+ var execIDs []string
+ for rows.Next() {
+ var payload string
+ if err := rows.Scan(&payload); err != nil {
+ return fmt.Errorf("sqlite_eventlog: scan conversation: %w", err)
+ }
+
+ ev := &proto.ConversationEvent{}
+ if err := unmarshalOpts.Unmarshal([]byte(payload), ev); err != nil {
+ return fmt.Errorf("sqlite_eventlog: unmarshal event: %w", err)
+ }
+ if ev.ExecId != "" {
+ execIDs = append(execIDs, ev.ExecId)
+ }
+ }
+
+ if err := rows.Err(); err != nil {
+ return fmt.Errorf("sqlite_eventlog: iterate conversation: %w", err)
+ }
+
+ // Delete from execution_log
+ for _, execID := range execIDs {
+ if _, err := tx.ExecContext(ctx, "DELETE FROM execution_log WHERE exec_id = ?", execID); err != nil {
+ return fmt.Errorf("sqlite_eventlog: delete exec %s: %w", execID, err)
+ }
+ }
+
+ // Delete from conversation_log
+ if _, err := tx.ExecContext(ctx, "DELETE FROM conversation_log WHERE conversation_id = ?", conversationID); err != nil {
+ return fmt.Errorf("sqlite_eventlog: delete conversation: %w", err)
+ }
+
+ if err := tx.Commit(); err != nil {
+ return fmt.Errorf("sqlite_eventlog: commit tx: %w", err)
+ }
+
+ return nil
+}
+
+// Close releases the database connection.
+func (l *SQLiteEventLog) Close() error {
+ return l.db.Close()
+}
diff --git a/internal/controller2/eventlog/sqlite_test.go b/internal/controller2/eventlog/sqlite_test.go
new file mode 100644
index 0000000..3fd8085
--- /dev/null
+++ b/internal/controller2/eventlog/sqlite_test.go
@@ -0,0 +1,256 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package eventlog
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "sync"
+ "testing"
+
+ "github.com/google/ax/proto"
+ "google.golang.org/protobuf/types/known/timestamppb"
+)
+
+func TestSQLiteEventLog_AppendAndEvents(t *testing.T) {
+ ctx := context.Background()
+ dbPath := filepath.Join(t.TempDir(), "test.db")
+
+ log, err := OpenSQLiteEventLog(dbPath)
+ if err != nil {
+ t.Fatalf("failed to open sqlite event log: %v", err)
+ }
+ defer log.Close()
+
+ // 1. Test Conversation Log
+ cev1 := &proto.ConversationEvent{
+ ConversationId: "conv-1",
+ Seq: 1,
+ ExecId: "task-1",
+ }
+
+ cev2 := &proto.ConversationEvent{
+ ConversationId: "conv-1",
+ Seq: 2,
+ ExecId: "task-2",
+ }
+
+ if _, err := log.Append(ctx, cev1); err != nil {
+ t.Fatalf("failed to append cev1: %v", err)
+ }
+ if _, err := log.Append(ctx, cev2); err != nil {
+ t.Fatalf("failed to append cev2: %v", err)
+ }
+
+ cEvents, err := log.Events(ctx, "conv-1")
+ if err != nil {
+ t.Fatalf("failed to read conversation events: %v", err)
+ }
+
+ if len(cEvents) != 2 {
+ t.Fatalf("expected 2 conversation events, got %d", len(cEvents))
+ }
+
+ if cEvents[0].ExecId != "task-1" || cEvents[1].ExecId != "task-2" {
+ t.Errorf("conversation events mismatch")
+ }
+
+ // 2. Test Execution Log
+ ee1 := &proto.ExecutionEvent{
+ ExecId: "task-1",
+ State: proto.State_STATE_PENDING,
+ Timestamp: timestamppb.Now(),
+ Inputs: []*proto.Message{
+ {Role: "user", Content: &proto.Content{Type: &proto.Content_Text{Text: &proto.TextContent{Text: "hello"}}}},
+ },
+ }
+
+ if err := log.AppendExec(ctx, ee1); err != nil {
+ t.Fatalf("failed to append ee1: %v", err)
+ }
+
+ eEvents, err := log.ExecEvents(ctx, "task-1")
+ if err != nil {
+ t.Fatalf("failed to read execution events: %v", err)
+ }
+
+ if len(eEvents) != 1 {
+ t.Fatalf("expected 1 execution event, got %d", len(eEvents))
+ }
+
+ if eEvents[0].ExecId != "task-1" || eEvents[0].State != proto.State_STATE_PENDING {
+ t.Errorf("execution event mismatch")
+ }
+}
+
+func TestSQLiteEventLog_ConcurrentAppend(t *testing.T) {
+ ctx := context.Background()
+ dbPath := filepath.Join(t.TempDir(), "test.db")
+
+ log, err := OpenSQLiteEventLog(dbPath)
+ if err != nil {
+ t.Fatalf("failed to open sqlite event log: %v", err)
+ }
+ defer log.Close()
+
+ var wg sync.WaitGroup
+ numRoutines := 10
+ numEvents := 100
+
+ for i := range numRoutines {
+ wg.Add(1)
+ go func(agentIdx int) {
+ defer wg.Done()
+ for i := range numEvents {
+ ev := &proto.ConversationEvent{
+ ConversationId: "conv-concurrent",
+ Seq: int32(agentIdx*numEvents + i + 1),
+ ExecId: "task-concurrent",
+ }
+ if _, err := log.Append(ctx, ev); err != nil {
+ t.Errorf("concurrent append failed: %v", err)
+ }
+ }
+ }(i)
+ }
+
+ wg.Wait()
+
+ events, err := log.Events(ctx, "conv-concurrent")
+ if err != nil {
+ t.Fatalf("failed to read events: %v", err)
+ }
+
+ if len(events) != numRoutines*numEvents {
+ t.Fatalf("expected %d events, got %d", numRoutines*numEvents, len(events))
+ }
+}
+
+func TestSQLiteEventLog_Empty(t *testing.T) {
+ ctx := context.Background()
+ dbPath := filepath.Join(t.TempDir(), "test.db")
+
+ log, err := OpenSQLiteEventLog(dbPath)
+ if err != nil {
+ t.Fatalf("failed to open sqlite event log: %v", err)
+ }
+ defer log.Close()
+
+ events, err := log.Events(ctx, "conv-1")
+ if err != nil {
+ t.Fatalf("failed to read events: %v", err)
+ }
+
+ if len(events) != 0 {
+ t.Fatalf("expected 0 events, got %d", len(events))
+ }
+}
+
+func TestSQLiteEventLog_DeleteEvents(t *testing.T) {
+ ctx := context.Background()
+ dbPath := filepath.Join(t.TempDir(), "test.db")
+
+ log, err := OpenSQLiteEventLog(dbPath)
+ if err != nil {
+ t.Fatalf("failed to open sqlite event log: %v", err)
+ }
+ defer log.Close()
+
+ // Setup data
+ cev1 := &proto.ConversationEvent{ConversationId: "conv-1", Seq: 1, ExecId: "task-1"}
+ cev2 := &proto.ConversationEvent{ConversationId: "conv-1", Seq: 2, ExecId: "task-2"}
+ cev3 := &proto.ConversationEvent{ConversationId: "conv-2", Seq: 1, ExecId: "task-3"}
+
+ log.Append(ctx, cev1)
+ log.Append(ctx, cev2)
+ log.Append(ctx, cev3)
+
+ ee1 := &proto.ExecutionEvent{ExecId: "task-1", State: proto.State_STATE_PENDING}
+ ee2 := &proto.ExecutionEvent{ExecId: "task-2", State: proto.State_STATE_COMPLETED}
+ ee3 := &proto.ExecutionEvent{ExecId: "task-3", State: proto.State_STATE_PENDING}
+
+ log.AppendExec(ctx, ee1)
+ log.AppendExec(ctx, ee2)
+ log.AppendExec(ctx, ee3)
+
+ // Delete conv-1
+ if err := log.DeleteAll(ctx, "conv-1"); err != nil {
+ t.Fatalf("failed to delete events: %v", err)
+ }
+
+ // Verify conversation events
+ events, err := log.Events(ctx, "conv-1")
+ if err != nil {
+ t.Fatalf("failed to read events: %v", err)
+ }
+ if len(events) != 0 {
+ t.Errorf("expected 0 events for conv-1, got %d", len(events))
+ }
+
+ events, err = log.Events(ctx, "conv-2")
+ if err != nil {
+ t.Fatalf("failed to read events: %v", err)
+ }
+ if len(events) != 1 {
+ t.Errorf("expected 1 event for conv-2, got %d", len(events))
+ }
+
+ // Verify execution events
+ eEvents, err := log.ExecEvents(ctx, "task-1")
+ if err != nil {
+ t.Fatalf("failed to read exec events: %v", err)
+ }
+ if len(eEvents) != 0 {
+ t.Errorf("expected 0 exec events for task-1, got %d", len(eEvents))
+ }
+
+ eEvents, err = log.ExecEvents(ctx, "task-2")
+ if err != nil {
+ t.Fatalf("failed to read exec events: %v", err)
+ }
+ if len(eEvents) != 0 {
+ t.Errorf("expected 0 exec events for task-2, got %d", len(eEvents))
+ }
+
+ eEvents, err = log.ExecEvents(ctx, "task-3")
+ if err != nil {
+ t.Fatalf("failed to read exec events: %v", err)
+ }
+ if len(eEvents) != 1 {
+ t.Errorf("expected 1 exec event for task-3, got %d", len(eEvents))
+ }
+}
+
+func TestSQLiteEventLog_CreatesParentDirectory(t *testing.T) {
+ // Create a path with a non-existent parent directory
+ dbPath := filepath.Join(t.TempDir(), "newdir", "test.db")
+
+ log, err := OpenSQLiteEventLog(dbPath)
+ if err != nil {
+ t.Fatalf("failed to open sqlite event log and create directory: %v", err)
+ }
+ defer log.Close()
+
+ // Verify that the parent directory actually exists
+ if _, err := os.Stat(filepath.Dir(dbPath)); os.IsNotExist(err) {
+ t.Fatalf("expected parent directory to be created, but it does not exist")
+ }
+
+ // Verify that the database file was created
+ if _, err := os.Stat(dbPath); os.IsNotExist(err) {
+ t.Fatalf("expected database file to be created, but it does not exist")
+ }
+}