ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)
Go aiai-agentsautonomous-agentsbug-bountydockergolanglinuxllmmcpnextjspenetration-testingpentestpostgresqlreareactred-teamsecuritysecurity-automationsqlitetypescript
Drain task goroutines on shutdown and replay activities that could not be stored.
protonmatter0234025d2850
diff --git a/cmd/artex/main.go b/cmd/artex/main.goindex 99e1180..ebf5e5b 100644--- a/cmd/artex/main.go+++ b/cmd/artex/main.go@@ -127,9 +127,21 @@ func run() int {<-ctx.Done()log.Println("shutting down...")- shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ drainCtx, drainCancel := context.WithTimeout(context.Background(), 15*time.Second)+ drainErr := srv.Wait(drainCtx)+ drainCancel()+ if drainErr != nil {+ log.Printf("task drain: %v", drainErr)+ }+ shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()- _ = httpSrv.Shutdown(shutdownCtx)+ if err := httpSrv.Shutdown(shutdownCtx); err != nil {+ log.Printf("http shutdown: %v", err)+ return 1+ }+ if drainErr != nil {+ return 1+ }return 0}diff --git a/db/activity_outbox.go b/db/activity_outbox.gonew file mode 100644index 0000000..c00c775--- /dev/null+++ b/db/activity_outbox.go@@ -0,0 +1,90 @@+package db++import (+ "encoding/json"+ "fmt"+)++// activityOutboxPayload is Activity plus Detail. Activity.Detail is omitted+// from ordinary JSON (the list payload stays small); the outbox has to keep it+// so a replayed row is the same step that failed to store.+type activityOutboxPayload struct {+ Activity+ Detail string `json:"detail,omitempty"`+}++func marshalActivity(a Activity) ([]byte, error) {+ return json.Marshal(activityOutboxPayload{Activity: a, Detail: a.Detail})+}++func unmarshalActivity(raw []byte) (Activity, error) {+ var payload activityOutboxPayload+ if err := json.Unmarshal(raw, &payload); err != nil {+ return Activity{}, err+ }+ a := payload.Activity+ a.Detail = payload.Detail+ return a, nil+}++// EnqueueActivity keeps one activity that AppendActivity could not store.+func (s *ExplorationStore) EnqueueActivity(a Activity, cause string) error {+ if s == nil || s.db == nil {+ return fmt.Errorf("activity outbox: no store")+ }+ raw, err := marshalActivity(a)+ if err != nil {+ return err+ }+ _, err = s.db.Exec(`INSERT INTO activity_outbox (exploration_id, payload, last_error) VALUES ($1, $2::jsonb, $3)`, s.expID, string(raw), cause)+ return err+}++// FlushActivityOutbox inserts queued activities in order and deletes each row+// that lands. A row that still cannot be inserted stays, with last_error+// updated, and the flush stops so later rows keep their order. A payload that+// cannot be decoded is discarded.+func (s *ExplorationStore) FlushActivityOutbox() (int, error) {+ if s == nil || s.db == nil {+ return 0, fmt.Errorf("activity outbox: no store")+ }+ rows, err := s.db.Query(`SELECT id, payload FROM activity_outbox WHERE exploration_id=$1 ORDER BY id`, s.expID)+ if err != nil {+ return 0, err+ }+ defer rows.Close()+ type item struct {+ id int64+ payload []byte+ }+ var items []item+ for rows.Next() {+ var it item+ if err := rows.Scan(&it.id, &it.payload); err != nil {+ return 0, err+ }+ items = append(items, it)+ }+ if err := rows.Err(); err != nil {+ return 0, err+ }+ stored := 0+ for _, it := range items {+ a, err := unmarshalActivity(it.payload)+ if err != nil {+ if _, delErr := s.db.Exec(`DELETE FROM activity_outbox WHERE id=$1`, it.id); delErr != nil {+ return stored, delErr+ }+ continue+ }+ if _, err := s.AppendActivity(a); err != nil {+ _, _ = s.db.Exec(`UPDATE activity_outbox SET last_error=$2 WHERE id=$1`, it.id, err.Error())+ return stored, err+ }+ if _, err := s.db.Exec(`DELETE FROM activity_outbox WHERE id=$1`, it.id); err != nil {+ return stored, err+ }+ stored+++ }+ return stored, nil+}diff --git a/db/activity_outbox_test.go b/db/activity_outbox_test.gonew file mode 100644index 0000000..ae64b69--- /dev/null+++ b/db/activity_outbox_test.go@@ -0,0 +1,18 @@+package db++import "testing"++func TestActivityOutboxKeepsDetail(t *testing.T) {+ in := Activity{Worker: "worker", Kind: "tool_result", Summary: "done", Detail: "full body", IsError: true}+ raw, err := marshalActivity(in)+ if err != nil {+ t.Fatal(err)+ }+ out, err := unmarshalActivity(raw)+ if err != nil {+ t.Fatal(err)+ }+ if out.Detail != in.Detail || out.Summary != in.Summary || out.Worker != in.Worker || out.Kind != in.Kind || !out.IsError {+ t.Fatalf("round trip = %+v", out)+ }+}diff --git a/db/exploration.go b/db/exploration.goindex ea8a55b..e55424b 100644--- a/db/exploration.go+++ b/db/exploration.go@@ -354,7 +354,10 @@ WHERE exploration_id=$1 AND kind='intent' AND state='running'if err != nil {return 0, err}- n, _ := res.RowsAffected()+ n, err := res.RowsAffected()+ if err != nil {+ return 0, err+ }return n, nil}diff --git a/db/migrate_test.go b/db/migrate_test.goindex 2ca9d54..fc6d756 100644--- a/db/migrate_test.go+++ b/db/migrate_test.go@@ -137,9 +137,9 @@ func assertEmbeddedApplied(t *testing.T, d *DB) []appliedMigration {version intname string}{{1, llmRecordsMigration}, {2, llmUsageMigration}, {3, "0003_task_scope_icp_index.sql"}, {4, "0004_llm_usage_ts_index.sql"},- {5, "0005_traffic_rewrite_rules.sql"}}+ {5, "0005_traffic_rewrite_rules.sql"}, {6, "0006_activity_outbox.sql"}}if len(applied) != len(want) {- t.Fatalf("schema_migrations = %+v, want versions 1 to 5", applied)+ t.Fatalf("schema_migrations = %+v, want versions 1 to 6", applied)}for i, w := range want {content, err := fs.ReadFile(migrationsFS(), w.name)diff --git a/db/migrations/0006_activity_outbox.sql b/db/migrations/0006_activity_outbox.sqlnew file mode 100644index 0000000..ff1396c--- /dev/null+++ b/db/migrations/0006_activity_outbox.sql@@ -0,0 +1,14 @@+-- Activities that could not be inserted (the exploration row was missing, or+-- the write failed after retries) are kept here and replayed into activity+-- once the parent row accepts them. No foreign key: the row has to survive+-- the missing exploration that caused the original failure.+CREATE TABLE IF NOT EXISTS activity_outbox (+ id BIGSERIAL PRIMARY KEY,+ exploration_id BIGINT NOT NULL,+ payload JSONB NOT NULL,+ last_error TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS activity_outbox_exploration_idx+ ON activity_outbox (exploration_id, id);diff --git a/server/engine.go b/server/engine.goindex 4e4ebad..b268860 100644--- a/server/engine.go+++ b/server/engine.go@@ -118,6 +118,7 @@ type Engine struct {// runs under one task-scoped context. Successful deletion cancels that context,// waits for all goroutines, then releases every task-level Engine reference.runtimeMu sync.Mutex+ draining boolruntimes map[string]*taskRuntime// per-task execution context: each planner.Plan / worker.Execute runs under it,@@ -162,7 +163,7 @@ type Engine struct {type taskRuntime struct {ctx context.Context- cancel context.CancelFunc+ cancel context.CancelCauseFuncwg sync.WaitGroup}@@ -231,9 +232,12 @@ func (e *Engine) IsDeleting(taskID string) bool {func (e *Engine) registerTaskRoutines(parent context.Context, taskID string, count int) *taskRuntime {e.runtimeMu.Lock()defer e.runtimeMu.Unlock()+ if e.draining {+ return nil+ }rt := e.runtimes[taskID]if rt == nil {- ctx, cancel := context.WithCancel(parent)+ ctx, cancel := context.WithCancelCause(parent)rt = &taskRuntime{ctx: ctx, cancel: cancel}e.runtimes[taskID] = rt}@@ -248,6 +252,43 @@ func runTaskRoutine(rt *taskRuntime, fn func(context.Context)) {}()}+// Wait blocks until the task goroutines registered at the moment of the call+// have finished, or until ctx ends. It refuses new registrations first so Add+// cannot race Wait. Goroutines that were already running are cancelled with+// AbortShutdown. That cancel does not write a terminal task status, and an+// in-flight intent claim stays running so the next start can reset it to open.+func (e *Engine) Wait(ctx context.Context) error {+ if e == nil {+ return nil+ }+ e.runtimeMu.Lock()+ e.draining = true+ groups := make([]*sync.WaitGroup, 0, len(e.runtimes))+ for _, rt := range e.runtimes {+ if rt == nil {+ continue+ }+ if rt.cancel != nil {+ rt.cancel(agent.AbortShutdown)+ }+ groups = append(groups, &rt.wg)+ }+ e.runtimeMu.Unlock()+ for _, wg := range groups {+ done := make(chan struct{})+ go func(wg *sync.WaitGroup) {+ wg.Wait()+ close(done)+ }(wg)+ select {+ case <-done:+ case <-ctx.Done():+ return ctx.Err()+ }+ }+ return nil+}+// StopTask permanently stops every long-lived goroutine and removes all Engine// state for a successfully deleted task. The delete barrier remains installed// until cleanup finishes, so no new task operation can race the teardown.@@ -260,7 +301,7 @@ func (e *Engine) StopTask(taskID string) {e.runtimeMu.Lock()rt := e.runtimes[taskID]if rt != nil {- rt.cancel()+ rt.cancel(agent.AbortTaskDeleted)}e.runtimeMu.Unlock()if rt != nil {@@ -664,6 +705,23 @@ func (e *Engine) emitActivity(t *Task, r db.Activity) db.Activity {}log.Printf("[activity] task %s dropping activity record (%d dropped for this task so far) worker=%s kind=%s tool=%s tuid=%s reason=%s summary=%q: %v%s",t.ID, n, r.Worker, r.Kind, r.Tool, r.ToolUseID, dropReason(err), preview(r.Summary, 80), err, diag)+ if t.Store != nil {+ if qerr := t.Store.EnqueueActivity(r, err.Error()); qerr != nil {+ log.Printf("[activity] task %s outbox: %v", t.ID, qerr)+ }+ }+ // The row has no database id. Publish an error copy so a live session+ // does not stay on "Running" while the original return value is unchanged.+ notice := r+ notice.IsError = true+ if notice.Summary == "" {+ notice.Summary = "activity was not stored"+ } else {+ notice.Summary += " (not stored)"+ }+ if e.bc != nil {+ e.bc.Publish(t.ID, notice)+ }e.touch(t.ID)return r}@@ -762,6 +820,10 @@ func (e *Engine) Run(ctx context.Context, t *Task) {}rt := e.registerTaskRoutines(ctx, t.ID, 2+workers)e.deleteMu.RUnlock()+ if rt == nil {+ e.started.Delete(t.ID)+ return+ }e.touch(t.ID)runTaskRoutine(rt, func(loopCtx context.Context) { e.plannerLoop(loopCtx, t) })runTaskRoutine(rt, func(loopCtx context.Context) { e.claimSweepLoop(loopCtx, t) })@@ -1266,6 +1328,13 @@ func (e *Engine) runIntent(ctx context.Context, t *Task, name string, worker *age.touch(t.ID)return true}+ // Process shutdown cancels the task context. Leave the claim running: AbortShutdown+ // says restart resets leftover running intents to open. Settling done or blocked+ // here would make that reset miss the intent, so the task would resume without it.+ if ectx.Err() != nil && errors.Is(context.Cause(ectx), agent.AbortShutdown) {+ log.Printf("[worker %s] task %s intent #%d shutdown: leaving the claim running", name, t.ID, intent.ID)+ return true+ }// killed by the planner: mark stopped (don't write back results, don't auto-reclaim).if killed {if err := t.Store.SettleIntentClaim(intent.ID, token, "stopped"); err != nil {diff --git a/server/engine_cancelcause_test.go b/server/engine_cancelcause_test.goindex d1f4f7a..44554b2 100644--- a/server/engine_cancelcause_test.go+++ b/server/engine_cancelcause_test.go@@ -9,6 +9,26 @@ import ("github.com/Autumn-27/artex/agent")+func TestWaitCancelsRuntimeWithShutdown(t *testing.T) {+ e := NewEngine(nil)+ rt := e.registerTaskRoutines(context.Background(), "t1", 1)+ if rt == nil {+ t.Fatal("runtime was not registered")+ }+ started := make(chan struct{})+ runTaskRoutine(rt, func(ctx context.Context) {+ close(started)+ <-ctx.Done()+ })+ <-started+ if err := e.Wait(context.Background()); err != nil {+ t.Fatal(err)+ }+ if !errors.Is(context.Cause(rt.ctx), agent.AbortShutdown) {+ t.Fatalf("cause=%v, want shutdown", context.Cause(rt.ctx))+ }+}+func TestPauseCancelsWithNamedCause(t *testing.T) {e := NewEngine(nil)execCtx := e.execContextFor(context.Background(), "t1")diff --git a/server/engine_timeout.go b/server/engine_timeout.goindex 37f5469..cb596d0 100644--- a/server/engine_timeout.go+++ b/server/engine_timeout.go@@ -161,6 +161,10 @@ func (e *Engine) startDeadlineCoordinator(ctx context.Context, t *Task) {}rt := e.registerTaskRoutines(ctx, t.ID, 1)e.deleteMu.RUnlock()+ if rt == nil {+ e.coordStarted.Delete(t.ID)+ return+ }runTaskRoutine(rt, func(loopCtx context.Context) { e.deadlineCoordinator(loopCtx, t) })}diff --git a/server/server.go b/server/server.goindex 7956221..8a1f1f1 100644--- a/server/server.go+++ b/server/server.go@@ -296,9 +296,16 @@ func (s *Server) restoreTaskRuntimes() {lifecycle := t.lifecycleSnapshot()// clear stale 'running' intents from a prior crash/restart (no live worker// owns them) so they re-claim instead of spinning forever in the UI.- if n, _ := t.Store.ResetRunningIntents(); n > 0 {+ if n, err := t.Store.ResetRunningIntents(); err != nil {+ log.Printf("[engine] task %s reset leftover running intents: %v", t.ID, err)+ } else if n > 0 {log.Printf("[engine] task %s reset %d leftover running intents to open", t.ID, n)}+ if n, err := t.Store.FlushActivityOutbox(); err != nil {+ log.Printf("[activity] task %s outbox: %v", t.ID, err)+ } else if n > 0 {+ log.Printf("[activity] task %s stored %d activities recovered from the outbox", t.ID, n)+ }if lifecycle.Paused {s.engine.Pause(t.ID, agent.AbortPausedOnReload)}@@ -320,6 +327,30 @@ func (s *Server) restoreTaskRuntimes() {}}+// Wait blocks until the task goroutines snapshotted now, and the archive+// worker, have finished, or until ctx ends.+func (s *Server) Wait(ctx context.Context) error {+ if s == nil {+ return nil+ }+ if s.engine != nil {+ if err := s.engine.Wait(ctx); err != nil {+ return err+ }+ }+ done := make(chan struct{})+ go func() {+ s.archiveWG.Wait()+ close(done)+ }()+ select {+ case <-done:+ return nil+ case <-ctx.Done():+ return ctx.Err()+ }+}+// agentMaxTurns returns the configured max_turns for an agent key (0 = unlimited,// also the fallback when no DB or no row).func (s *Server) agentMaxTurns(key string) int {