feat(tasks): add inherited context and resilient LLM execution
Add read-only task context inheritance, ordered task-level LLM failover, live Worker controls, cascading task cleanup, FIFO task concurrency, cancellation diagnostics, UI updates, tests, build script, and changelog.
This commit is contained in:
1 parent
7090b034f8
commit
9793b522d9
82 files changed
+11094
-1712
No files matched your search
+147
-49
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -913,7 +914,7 @@ func (s *AssetStore) CountByType(typ string) (int, error) {
|
||||
}
|
||||
|
||||
// QueryByCompany returns assets for a company, optionally filtered by type.
|
||||
// limit <= 0 means no limit — pair it with CountByCompany for server-side paging.
|
||||
// limit <= 0 means no limit.
|
||||
func (s *AssetStore) QueryByCompany(companyID int64, typ string, limit, offset int) ([]*Asset, error) {
|
||||
q := `SELECT id, type, company_id, array_to_json(task_ids)::text,
|
||||
COALESCE(domain,''), COALESCE(root_domain,''), COALESCE(ip,''),
|
||||
@@ -940,8 +941,6 @@ FROM assets WHERE company_id = $1`
|
||||
return scanAssets(rows)
|
||||
}
|
||||
|
||||
// CountByCompany returns the full number of assets attributed to a company
|
||||
// (optionally filtered by type), ignoring limit/offset.
|
||||
func (s *AssetStore) CountByCompany(companyID int64, typ string) (int, error) {
|
||||
q := `SELECT count(*) FROM assets WHERE company_id = $1`
|
||||
args := []any{companyID}
|
||||
@@ -954,8 +953,6 @@ func (s *AssetStore) CountByCompany(companyID int64, typ string) (int, error) {
|
||||
return n, err
|
||||
}
|
||||
|
||||
// pageClause appends limit/offset placeholders to args and returns the trailing
|
||||
// ORDER BY … LIMIT … OFFSET fragment. limit <= 0 means no limit.
|
||||
func pageClause(args *[]any, limit, offset int) string {
|
||||
q := ` ORDER BY last_seen DESC`
|
||||
if limit > 0 {
|
||||
@@ -970,7 +967,6 @@ func pageClause(args *[]any, limit, offset int) string {
|
||||
}
|
||||
|
||||
// QueryByTask returns assets rows that have a given task_id in task_ids.
|
||||
// limit <= 0 means no limit — pair it with CountByTask for server-side paging.
|
||||
func (s *AssetStore) QueryByTask(taskID int64, typ string, limit, offset int) ([]*Asset, error) {
|
||||
q := `SELECT id, type, company_id, array_to_json(task_ids)::text,
|
||||
COALESCE(domain,''), COALESCE(root_domain,''), COALESCE(ip,''),
|
||||
@@ -997,8 +993,6 @@ FROM assets WHERE $1 = ANY(task_ids)`
|
||||
return scanAssets(rows)
|
||||
}
|
||||
|
||||
// CountByTask returns the full number of assets attached to a task (optionally
|
||||
// filtered by type), ignoring limit/offset — lets the UI paginate on the server.
|
||||
func (s *AssetStore) CountByTask(taskID int64, typ string) (int, error) {
|
||||
q := `SELECT count(*) FROM assets WHERE $1 = ANY(task_ids)`
|
||||
args := []any{taskID}
|
||||
@@ -1011,7 +1005,6 @@ func (s *AssetStore) CountByTask(taskID int64, typ string) (int, error) {
|
||||
return n, err
|
||||
}
|
||||
|
||||
// CountsByTypeForTask returns asset counts per type for a single task.
|
||||
func (s *AssetStore) CountsByTypeForTask(taskID int64) (map[string]int, error) {
|
||||
rows, err := s.db.Query(`SELECT type, COUNT(*) FROM assets WHERE $1 = ANY(task_ids) GROUP BY type`, taskID)
|
||||
if err != nil {
|
||||
@@ -1021,6 +1014,151 @@ func (s *AssetStore) CountsByTypeForTask(taskID int64) (map[string]int, error) {
|
||||
return scanTypeCounts(rows)
|
||||
}
|
||||
|
||||
// DeleteByTaskID removes assets owned only by taskID and detaches taskID from
|
||||
// assets shared with other tasks. Full task deletion uses the coordinated
|
||||
// transaction in DeleteTaskCascadePrepared; this method remains for callers
|
||||
// that explicitly manage only asset associations.
|
||||
func (s *AssetStore) DeleteByTaskID(taskID int64) (int64, error) {
|
||||
res, err := s.db.Exec(`DELETE FROM assets WHERE task_ids = ARRAY[$1]::bigint[]`, taskID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
deleted, _ := res.RowsAffected()
|
||||
if _, err := s.db.Exec(`UPDATE assets SET task_ids = array_remove(task_ids, $1) WHERE $1 = ANY(task_ids)`, taskID); err != nil {
|
||||
return deleted, err
|
||||
}
|
||||
return deleted, nil
|
||||
}
|
||||
|
||||
// HostsByTask returns the exact HTTP host candidates attached to a task's
|
||||
// assets. Domain/IP columns cover root domains, subdomains and non-HTTP
|
||||
// services; URL covers HTTP services and endpoints.
|
||||
func (s *AssetStore) HostsByTask(taskID int64) ([]string, error) {
|
||||
rows, err := s.db.Query(`
|
||||
SELECT COALESCE(domain,''), COALESCE(ip,''), COALESCE(url,'')
|
||||
FROM assets WHERE $1 = ANY(task_ids)`, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
hosts := make(map[string]struct{})
|
||||
add := func(host string) {
|
||||
host = strings.TrimSpace(strings.ToLower(host))
|
||||
if host != "" {
|
||||
hosts[host] = struct{}{}
|
||||
}
|
||||
}
|
||||
for rows.Next() {
|
||||
var domain, ip, rawURL string
|
||||
if err := rows.Scan(&domain, &ip, &rawURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
add(domain)
|
||||
add(ip)
|
||||
if u, err := url.Parse(rawURL); err == nil {
|
||||
add(u.Hostname())
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]string, 0, len(hosts))
|
||||
for host := range hosts {
|
||||
out = append(out, host)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// HostsForTaskDeletion returns hosts that belong to the task being deleted and
|
||||
// are not referenced by any other live task. Current-task candidates include
|
||||
// both task_ids ownership and exploration anchors so legacy seeded assets (which
|
||||
// were anchor-only) are covered. Protection is host-wide: if another live task
|
||||
// references any asset for a candidate host, that host's global traffic remains.
|
||||
func (s *AssetStore) HostsForTaskDeletion(taskID, explorationID int64) ([]string, error) {
|
||||
return hostsForTaskDeletion(s.db, taskID, explorationID)
|
||||
}
|
||||
|
||||
type rowsQuerier interface {
|
||||
Query(query string, args ...any) (*sql.Rows, error)
|
||||
}
|
||||
|
||||
// hostsForTaskDeletion is shared by the read-only AssetStore API and the task
|
||||
// deletion transaction. Coordinated traffic deletion must call it through the
|
||||
// transaction path so asset/anchor writes stay locked until the task delete is
|
||||
// committed.
|
||||
func hostsForTaskDeletion(q rowsQuerier, taskID, explorationID int64) ([]string, error) {
|
||||
rows, err := q.Query(`
|
||||
WITH current_assets AS (
|
||||
SELECT id FROM assets WHERE $1 = ANY(task_ids)
|
||||
UNION
|
||||
SELECT ea.asset_id
|
||||
FROM exploration_anchors ea
|
||||
JOIN exploration_nodes n ON n.id=ea.node_id
|
||||
WHERE n.exploration_id=$2
|
||||
),
|
||||
other_assets AS (
|
||||
SELECT DISTINCT a.id
|
||||
FROM assets a
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM tasks t
|
||||
WHERE t.id<>$1 AND t.deleted_at IS NULL AND t.id=ANY(a.task_ids)
|
||||
) OR EXISTS (
|
||||
SELECT 1
|
||||
FROM exploration_anchors ea
|
||||
JOIN exploration_nodes n ON n.id=ea.node_id
|
||||
JOIN tasks t ON t.exploration_id=n.exploration_id
|
||||
WHERE ea.asset_id=a.id AND t.id<>$1 AND t.deleted_at IS NULL
|
||||
)
|
||||
)
|
||||
SELECT COALESCE(a.domain,''), COALESCE(a.ip,''), COALESCE(a.url,''), true
|
||||
FROM assets a JOIN current_assets c ON c.id=a.id
|
||||
UNION ALL
|
||||
SELECT COALESCE(a.domain,''), COALESCE(a.ip,''), COALESCE(a.url,''), false
|
||||
FROM assets a JOIN other_assets o ON o.id=a.id`, taskID, explorationID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
candidates := make(map[string]struct{})
|
||||
protected := make(map[string]struct{})
|
||||
add := func(dst map[string]struct{}, raw string) {
|
||||
raw = strings.TrimSpace(strings.ToLower(raw))
|
||||
if raw != "" {
|
||||
dst[raw] = struct{}{}
|
||||
}
|
||||
}
|
||||
for rows.Next() {
|
||||
var domain, ip, rawURL string
|
||||
var candidate bool
|
||||
if err := rows.Scan(&domain, &ip, &rawURL, &candidate); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dst := protected
|
||||
if candidate {
|
||||
dst = candidates
|
||||
}
|
||||
add(dst, domain)
|
||||
add(dst, ip)
|
||||
if u, err := url.Parse(rawURL); err == nil {
|
||||
add(dst, u.Hostname())
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]string, 0, len(candidates))
|
||||
for host := range candidates {
|
||||
if _, shared := protected[host]; !shared {
|
||||
out = append(out, host)
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
const assetSelectCols = `SELECT id, type, company_id, array_to_json(task_ids)::text,
|
||||
COALESCE(domain,''), COALESCE(root_domain,''), COALESCE(ip,''),
|
||||
COALESCE(c_segment::text,''), port,
|
||||
@@ -1053,45 +1191,6 @@ func (s *AssetStore) GetByIDs(ids []int64) ([]*Asset, error) {
|
||||
return scanAssets(rows)
|
||||
}
|
||||
|
||||
// DeleteByTaskID removes a task's assets: hard-deletes assets owned solely by this
|
||||
// task (task_ids = {taskID}) and de-associates the rest (drops this task from their
|
||||
// task_ids, keeping assets shared with other tasks intact). Returns rows deleted.
|
||||
func (s *AssetStore) DeleteByTaskID(taskID int64) (int64, error) {
|
||||
res, err := s.db.Exec(`DELETE FROM assets WHERE task_ids = ARRAY[$1]::bigint[]`, taskID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
if _, err := s.db.Exec(`UPDATE assets SET task_ids = array_remove(task_ids, $1) WHERE $1 = ANY(task_ids)`, taskID); err != nil {
|
||||
return n, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// HostsByTask returns the distinct hostnames/IPs the task's assets carry (domain,
|
||||
// root_domain, ip) — used to purge host-keyed traffic recorded for that task.
|
||||
func (s *AssetStore) HostsByTask(taskID int64) ([]string, error) {
|
||||
rows, err := s.db.Query(`
|
||||
SELECT DISTINCT h FROM (
|
||||
SELECT NULLIF(domain,'') AS h FROM assets WHERE $1 = ANY(task_ids)
|
||||
UNION SELECT NULLIF(root_domain,'') FROM assets WHERE $1 = ANY(task_ids)
|
||||
UNION SELECT NULLIF(ip,'') FROM assets WHERE $1 = ANY(task_ids)
|
||||
) q WHERE h IS NOT NULL AND h <> ''`, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []string
|
||||
for rows.Next() {
|
||||
var h string
|
||||
if err := rows.Scan(&h); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, h)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// DeleteByCompanyID hard-deletes all assets belonging to a company. Returns rows deleted.
|
||||
func (s *AssetStore) DeleteByCompanyID(companyID int64) (int64, error) {
|
||||
res, err := s.db.Exec(`DELETE FROM assets WHERE company_id = $1`, companyID)
|
||||
@@ -1161,7 +1260,6 @@ func (s *AssetStore) CountsByType() (map[string]int, error) {
|
||||
return scanTypeCounts(rows)
|
||||
}
|
||||
|
||||
// scanTypeCounts scans a (type, count) result set into a map.
|
||||
func scanTypeCounts(rows *sql.Rows) (map[string]int, error) {
|
||||
out := map[string]int{}
|
||||
for rows.Next() {
|
||||
|
||||
+5
-5
@@ -290,12 +290,12 @@ func TestUpsertHTTPService(t *testing.T) {
|
||||
sc := 200
|
||||
cl := int64(1024)
|
||||
id1, err := av2.UpsertHTTPService(UpsertHTTPServiceReq{
|
||||
URL: "https://www.httptest.example.com/",
|
||||
Technologies: []string{"nginx", "vue"},
|
||||
StatusCode: &sc,
|
||||
URL: "https://www.httptest.example.com/",
|
||||
Technologies: []string{"nginx", "vue"},
|
||||
StatusCode: &sc,
|
||||
ContentLength: &cl,
|
||||
PageTitle: "Test Site",
|
||||
TaskID: 1,
|
||||
PageTitle: "Test Site",
|
||||
TaskID: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
+276
-5
@@ -1,8 +1,11 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -133,9 +136,236 @@ VALUES ($1,$2,NULLIF($3,''),NULLIF($4,''),$5,NULLIF($6,''),NULLIF($7,''),$8,$9,$
|
||||
return p.ID, err
|
||||
}
|
||||
|
||||
var (
|
||||
ErrActiveLLMProfileDelete = errors.New("cannot delete the active LLM profile; activate another profile first")
|
||||
ErrLLMProfileReferencesChanged = errors.New("LLM profile references changed while deleting; retry the request")
|
||||
ErrLLMProfileNotFound = errors.New("LLM profile not found")
|
||||
)
|
||||
|
||||
func (d *DB) DeleteProfile(id int64) error {
|
||||
_, err := d.Exec(`DELETE FROM llm_profiles WHERE id=$1`, id)
|
||||
return err
|
||||
return d.DeleteProfileContext(context.Background(), id)
|
||||
}
|
||||
|
||||
// DeleteProfileContext removes a non-default profile while preserving the task
|
||||
// failover cursor. Reference changes are retried because a task, agent, or
|
||||
// conversation may start pointing at the profile between the initial scan and
|
||||
// the profile row lock. A bound prevents a continuously changing workload from
|
||||
// keeping an HTTP request alive forever.
|
||||
func (d *DB) DeleteProfileContext(ctx context.Context, id int64) error {
|
||||
const (
|
||||
maxAttempts = 8
|
||||
maxDuration = 15 * time.Second
|
||||
)
|
||||
ctx, cancel := context.WithTimeout(ctx, maxDuration)
|
||||
defer cancel()
|
||||
for attempt := 0; attempt < maxAttempts; attempt++ {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
retry, err := d.deleteProfile(ctx, id)
|
||||
if err != nil || !retry {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("%w: profile %d", ErrLLMProfileReferencesChanged, id)
|
||||
}
|
||||
|
||||
func (d *DB) deleteProfile(ctx context.Context, id int64) (bool, error) {
|
||||
tx, err := d.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// Reference setters lock their task/agent/conversation row before an
|
||||
// llm_profiles row can be locked by a foreign-key check. Keep deletion in the
|
||||
// same order: the old profile -> child order deadlocked with a setter's child
|
||||
// -> profile order. Sorting also gives concurrent profile deletions a stable
|
||||
// order when their chains overlap multiple tasks.
|
||||
lockedTasks, err := lockProfileReferenceRows(ctx, tx, `SELECT t.id
|
||||
FROM tasks t
|
||||
WHERE t.llm_profile_id=$1
|
||||
OR t.active_llm_profile_id=$1
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM task_llm_profiles x
|
||||
WHERE x.task_id=t.id AND x.profile_id=$1
|
||||
)
|
||||
ORDER BY t.id
|
||||
FOR UPDATE OF t`, id)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
lockedAgents, err := lockProfileReferenceRows(ctx, tx, `SELECT id FROM agents
|
||||
WHERE llm_profile_id=$1
|
||||
ORDER BY id
|
||||
FOR UPDATE`, id)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
lockedConversations, err := lockProfileReferenceRows(ctx, tx, `SELECT id FROM conversations
|
||||
WHERE llm_profile_id=$1
|
||||
ORDER BY id
|
||||
FOR UPDATE`, id)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
var isDefault bool
|
||||
if err := tx.QueryRowContext(ctx, `SELECT is_default FROM llm_profiles WHERE id=$1 FOR UPDATE`, id).Scan(&isDefault); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return false, ErrLLMProfileNotFound
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
if isDefault {
|
||||
return false, ErrActiveLLMProfileDelete
|
||||
}
|
||||
|
||||
type affectedTask struct {
|
||||
id int64
|
||||
position int
|
||||
wasActive bool
|
||||
}
|
||||
// A task may have committed a new reference after the first statement took
|
||||
// its snapshot but before this transaction acquired the profile lock. The
|
||||
// profile lock now prevents further references; retry if that committed task
|
||||
// was not part of the task-first lock set. Never acquire a new task lock while
|
||||
// holding the profile lock, because that would recreate the inversion.
|
||||
rows, err := tx.QueryContext(ctx, `SELECT ref_kind, ref_id FROM (
|
||||
SELECT 'task'::text AS ref_kind, t.id AS ref_id
|
||||
FROM tasks t
|
||||
WHERE t.llm_profile_id=$1
|
||||
OR t.active_llm_profile_id=$1
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM task_llm_profiles x
|
||||
WHERE x.task_id=t.id AND x.profile_id=$1
|
||||
)
|
||||
UNION ALL
|
||||
SELECT 'agent', a.id FROM agents a WHERE a.llm_profile_id=$1
|
||||
UNION ALL
|
||||
SELECT 'conversation', c.id FROM conversations c WHERE c.llm_profile_id=$1
|
||||
) refs
|
||||
ORDER BY ref_kind, ref_id`, id)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var (
|
||||
kind string
|
||||
rowID int64
|
||||
)
|
||||
if err := rows.Scan(&kind, &rowID); err != nil {
|
||||
rows.Close()
|
||||
return false, err
|
||||
}
|
||||
locked := false
|
||||
switch kind {
|
||||
case "task":
|
||||
_, locked = lockedTasks[rowID]
|
||||
case "agent":
|
||||
_, locked = lockedAgents[rowID]
|
||||
case "conversation":
|
||||
_, locked = lockedConversations[rowID]
|
||||
}
|
||||
if !locked {
|
||||
rows.Close()
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return false, err
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
rows, err = tx.QueryContext(ctx, `SELECT x.task_id, x.position, COALESCE(t.active_llm_profile_id=$1, false)
|
||||
FROM task_llm_profiles x
|
||||
JOIN tasks t ON t.id=x.task_id
|
||||
WHERE x.profile_id=$1
|
||||
ORDER BY x.task_id`, id)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var affected []affectedTask
|
||||
for rows.Next() {
|
||||
var task affectedTask
|
||||
if err := rows.Scan(&task.id, &task.position, &task.wasActive); err != nil {
|
||||
rows.Close()
|
||||
return false, err
|
||||
}
|
||||
affected = append(affected, task)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return false, err
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM llm_profiles WHERE id=$1`, id); err != nil {
|
||||
return false, err
|
||||
}
|
||||
// Only a successor after the deleted cursor is eligible. If there is none,
|
||||
// clear the explicit chain so the task falls back to its Agent/global provider;
|
||||
// profiles before a manually selected cursor must never be revived.
|
||||
for _, task := range affected {
|
||||
if !task.wasActive {
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE tasks SET llm_chain_revision=llm_chain_revision+1 WHERE id=$1`, task.id); err != nil {
|
||||
return false, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
var next int64
|
||||
err := tx.QueryRowContext(ctx, `SELECT profile_id FROM task_llm_profiles
|
||||
WHERE task_id=$1 AND position>$2 AND status='ready'
|
||||
ORDER BY position
|
||||
LIMIT 1`, task.id, task.position).Scan(&next)
|
||||
if err != nil && err != sql.ErrNoRows {
|
||||
return false, err
|
||||
}
|
||||
if err == sql.ErrNoRows {
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM task_llm_profiles WHERE task_id=$1`, task.id); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE tasks
|
||||
SET active_llm_profile_id=NULL, llm_profile_id=NULL, llm_chain_revision=llm_chain_revision+1
|
||||
WHERE id=$1`, task.id); err != nil {
|
||||
return false, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE tasks
|
||||
SET active_llm_profile_id=$2, llm_profile_id=$2, llm_chain_revision=llm_chain_revision+1
|
||||
WHERE id=$1`, task.id, next); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func lockProfileReferenceRows(ctx context.Context, tx *sql.Tx, query string, profileID int64) (map[int64]struct{}, error) {
|
||||
rows, err := tx.QueryContext(ctx, query, profileID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
locked := make(map[int64]struct{})
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
locked[id] = struct{}{}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return locked, nil
|
||||
}
|
||||
|
||||
// SetActiveProfile makes one profile the global default (single-default invariant).
|
||||
@@ -148,9 +378,13 @@ func (d *DB) SetActiveProfile(id int64) error {
|
||||
if _, err := tx.Exec(`UPDATE llm_profiles SET is_default=false WHERE is_default`); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(`UPDATE llm_profiles SET is_default=true WHERE id=$1`, id); err != nil {
|
||||
res, err := tx.Exec(`UPDATE llm_profiles SET is_default=true WHERE id=$1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n != 1 {
|
||||
return ErrLLMProfileNotFound
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
@@ -313,8 +547,45 @@ func (d *DB) SetAgentMaxTurns(key string, maxTurns int) error {
|
||||
// the binding (id == nil) so the agent follows the task/conversation pin, else the
|
||||
// global active profile. Precedence at runtime: agent binding → task/conv pin → active.
|
||||
func (d *DB) SetAgentLLMProfile(key string, id *int64) error {
|
||||
_, err := d.Exec(`UPDATE agents SET llm_profile_id=$1 WHERE key=$2`, id, key)
|
||||
return err
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// DeleteProfile locks reference rows before the profile row. Keep the same
|
||||
// order here so a concurrent rebind cannot form a child/profile deadlock.
|
||||
var agentID int64
|
||||
if err := tx.QueryRow(`SELECT id FROM agents WHERE key=$1 FOR UPDATE`, key).Scan(&agentID); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
// Preserve the previous UPDATE semantics: an unknown key is a no-op.
|
||||
return tx.Commit()
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := lockLLMProfileForReference(tx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(`UPDATE agents SET llm_profile_id=$1 WHERE id=$2`, id, agentID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// lockLLMProfileForReference makes the profile side of the shared lock-order
|
||||
// protocol explicit. Callers must already own the referencing child row.
|
||||
func lockLLMProfileForReference(tx *sql.Tx, profileID *int64) error {
|
||||
if profileID == nil {
|
||||
return nil
|
||||
}
|
||||
var lockedID int64
|
||||
if err := tx.QueryRow(`SELECT id FROM llm_profiles WHERE id=$1 FOR KEY SHARE`, *profileID).Scan(&lockedID); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return ErrLLMProfileNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetAgentWebSearch toggles whether an agent uses network search (still gated by
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -53,6 +55,15 @@ func TestPoolProfilesOrder(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteProfileContextHonorsCancellation(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
var d DB
|
||||
if err := d.DeleteProfileContext(ctx, 1); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("DeleteProfileContext error=%v, want context cancellation", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigStores(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
@@ -69,6 +80,9 @@ func TestConfigStores(t *testing.T) {
|
||||
if err := d.SetActiveProfile(pid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := d.DeleteProfile(pid); !errors.Is(err, ErrActiveLLMProfileDelete) {
|
||||
t.Fatalf("deleting active profile error=%v, want %v", err, ErrActiveLLMProfileDelete)
|
||||
}
|
||||
act, err := d.ActiveProfile()
|
||||
if err != nil || act == nil || act.APIKey != "secret123" {
|
||||
t.Fatalf("active profile/key: %+v err=%v", act, err)
|
||||
|
||||
+46
-5
@@ -69,19 +69,60 @@ func scanConv(row interface{ Scan(...any) error }) (Conversation, error) {
|
||||
// CreateConversation opens a new chat thread for agentKey with an initial title.
|
||||
// llmProfileID may be nil to use the globally active profile.
|
||||
func (d *DB) CreateConversation(agentKey, title string, llmProfileID *int64) (*Conversation, error) {
|
||||
c, err := scanConv(d.QueryRow(`
|
||||
INSERT INTO conversations(agent_key, title, llm_profile_id) VALUES ($1, $2, $3)
|
||||
RETURNING `+convCols, agentKey, title, llmProfileID))
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// Insert the child without a profile first. The new row is exclusively owned
|
||||
// by this transaction before it takes a profile lock, matching DeleteProfile's
|
||||
// child-row -> profile-row protocol.
|
||||
c, err := scanConv(tx.QueryRow(`
|
||||
INSERT INTO conversations(agent_key, title, llm_profile_id) VALUES ($1, $2, NULL)
|
||||
RETURNING `+convCols, agentKey, title))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := lockLLMProfileForReference(tx, llmProfileID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if llmProfileID != nil {
|
||||
c, err = scanConv(tx.QueryRow(`UPDATE conversations SET llm_profile_id=$2
|
||||
WHERE id=$1 RETURNING `+convCols, c.ID, llmProfileID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
// UpdateConversationProfile sets (or clears) the LLM profile override for a conversation.
|
||||
func (d *DB) UpdateConversationProfile(id int64, llmProfileID *int64) error {
|
||||
_, err := d.Exec(`UPDATE conversations SET llm_profile_id=$2 WHERE id=$1`, id, llmProfileID)
|
||||
return err
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
var lockedID int64
|
||||
if err := tx.QueryRow(`SELECT id FROM conversations WHERE id=$1 FOR UPDATE`, id).Scan(&lockedID); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
// Preserve the previous UPDATE semantics: an unknown id is a no-op.
|
||||
return tx.Commit()
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := lockLLMProfileForReference(tx, llmProfileID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(`UPDATE conversations SET llm_profile_id=$2 WHERE id=$1`, id, llmProfileID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// ListConversations returns all threads, most-recently-updated first.
|
||||
|
||||
+334
-41
@@ -25,34 +25,40 @@ func utf8Clean(s string) string {
|
||||
|
||||
// Node is a typed reasoning node (= old task_nodes). kind ∈ goal|intent|finding|hint.
|
||||
type Node struct {
|
||||
ID int64 `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
Payload json.RawMessage `json:"payload"`
|
||||
Priority int `json:"priority"`
|
||||
State string `json:"state"`
|
||||
Origin string `json:"origin,omitempty"`
|
||||
Owner string `json:"owner,omitempty"`
|
||||
Anchors []int64 `json:"anchors,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID int64 `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
Payload json.RawMessage `json:"payload"`
|
||||
Priority int `json:"priority"`
|
||||
State string `json:"state"`
|
||||
Origin string `json:"origin,omitempty"`
|
||||
Owner string `json:"owner,omitempty"`
|
||||
BlockedReason string `json:"blocked_reason,omitempty"`
|
||||
Anchors []int64 `json:"anchors,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
SourceTaskID int64 `json:"source_task_id,omitempty"`
|
||||
Inherited bool `json:"inherited,omitempty"`
|
||||
}
|
||||
|
||||
// Activity is one worker execution step (= old task_activity).
|
||||
type Activity struct {
|
||||
ID int64 `json:"id"`
|
||||
NodeID *int64 `json:"node_id,omitempty"`
|
||||
Worker string `json:"worker,omitempty"`
|
||||
Kind string `json:"kind,omitempty"`
|
||||
Tool string `json:"tool,omitempty"`
|
||||
ToolUseID string `json:"tool_use_id,omitempty"`
|
||||
IsError bool `json:"is_error"`
|
||||
Summary string `json:"summary,omitempty"`
|
||||
Detail string `json:"-"` // full blob; lazy-loaded, omitted from list payloads
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID int64 `json:"id"`
|
||||
NodeID *int64 `json:"node_id,omitempty"`
|
||||
Worker string `json:"worker,omitempty"`
|
||||
Kind string `json:"kind,omitempty"`
|
||||
Tool string `json:"tool,omitempty"`
|
||||
ToolUseID string `json:"tool_use_id,omitempty"`
|
||||
IsError bool `json:"is_error"`
|
||||
Summary string `json:"summary,omitempty"`
|
||||
Detail string `json:"-"` // full blob; lazy-loaded, omitted from list payloads
|
||||
Metadata json.RawMessage `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// Token usage — set only on the terminal kind='result' record; nil elsewhere.
|
||||
InputTokens *int `json:"input_tokens,omitempty"`
|
||||
OutputTokens *int `json:"output_tokens,omitempty"`
|
||||
CacheReadTokens *int `json:"cache_read_tokens,omitempty"`
|
||||
CacheWriteTokens *int `json:"cache_write_tokens,omitempty"`
|
||||
InputTokens *int `json:"input_tokens,omitempty"`
|
||||
OutputTokens *int `json:"output_tokens,omitempty"`
|
||||
CacheReadTokens *int `json:"cache_read_tokens,omitempty"`
|
||||
CacheWriteTokens *int `json:"cache_write_tokens,omitempty"`
|
||||
SourceTaskID int64 `json:"source_task_id,omitempty"`
|
||||
Inherited bool `json:"inherited,omitempty"`
|
||||
}
|
||||
|
||||
// TokenUsage is a per-worker token aggregate (TokenStatsByWorker).
|
||||
@@ -201,17 +207,17 @@ ON CONFLICT (exploration_id, src_id, rel, dst_id) DO NOTHING`, s.expID, from, re
|
||||
|
||||
// SetNodeState updates any node's state (never deletes).
|
||||
func (s *ExplorationStore) SetNodeState(id int64, state string) error {
|
||||
_, err := s.db.Exec(`UPDATE exploration_nodes SET state=$1 WHERE id=$2 AND exploration_id=$3`, state, id, s.expID)
|
||||
_, err := s.db.Exec(`UPDATE exploration_nodes SET state=$1, blocked_reason=NULL WHERE id=$2 AND exploration_id=$3`, state, id, s.expID)
|
||||
return err
|
||||
}
|
||||
|
||||
// SetIntentState updates an intent node's state (done/blocked/exhausted/open).
|
||||
// SetIntentState updates an intent node's state.
|
||||
// ResetRunningIntents returns any intent left in 'running' back to 'open' so it
|
||||
// is re-claimed. Called on startup: a 'running' intent with no live worker (a
|
||||
// backend restart or crashed worker goroutine left it stuck) would otherwise spin
|
||||
// forever in the UI. Workers re-run an intent from scratch, so reopening is safe.
|
||||
func (s *ExplorationStore) ResetRunningIntents() (int64, error) {
|
||||
res, err := s.db.Exec(`UPDATE exploration_nodes SET state='open', completed_at=NULL
|
||||
res, err := s.db.Exec(`UPDATE exploration_nodes SET state='open', completed_at=NULL, blocked_reason=NULL
|
||||
WHERE exploration_id=$1 AND kind='intent' AND state='running'`, s.expID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -226,7 +232,7 @@ WHERE exploration_id=$1 AND kind='intent' AND state='running'`, s.expID)
|
||||
// changed (false = intent absent or not in a rerunnable state). Used by the "重跑" button.
|
||||
func (s *ExplorationStore) ReopenIntent(id int64) (bool, error) {
|
||||
res, err := s.db.Exec(`UPDATE exploration_nodes
|
||||
SET state='open', completed_at=NULL
|
||||
SET state='open', completed_at=NULL, blocked_reason=NULL
|
||||
WHERE id=$1 AND exploration_id=$2 AND kind='intent'
|
||||
AND state IN ('blocked','exhausted','stopped')`, id, s.expID)
|
||||
if err != nil {
|
||||
@@ -240,7 +246,7 @@ WHERE id=$1 AND exploration_id=$2 AND kind='intent'
|
||||
// (batch rerun after e.g. an LLM/network outage that blocked many at once). Returns the
|
||||
// number reopened. Workers re-run each from scratch; kept graph writes remain.
|
||||
func (s *ExplorationStore) ReopenBlockedIntents() (int64, error) {
|
||||
res, err := s.db.Exec(`UPDATE exploration_nodes SET state='open', completed_at=NULL
|
||||
res, err := s.db.Exec(`UPDATE exploration_nodes SET state='open', completed_at=NULL, blocked_reason=NULL
|
||||
WHERE exploration_id=$1 AND kind='intent' AND state='blocked'`, s.expID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -253,17 +259,92 @@ func (s *ExplorationStore) SetIntentState(id int64, state string) error {
|
||||
// terminal states stamp completed_at; reopening (back to open/running) clears it.
|
||||
terminal := state == "done" || state == "blocked" || state == "exhausted" || state == "stopped"
|
||||
_, err := s.db.Exec(`UPDATE exploration_nodes
|
||||
SET state=$1, completed_at = CASE WHEN $4 THEN now() ELSE NULL END
|
||||
SET state=$1, blocked_reason=NULL, completed_at = CASE WHEN $4 THEN now() ELSE NULL END
|
||||
WHERE id=$2 AND exploration_id=$3 AND kind='intent'`, state, id, s.expID, terminal)
|
||||
return err
|
||||
}
|
||||
|
||||
const nodeCols = `id, kind, payload, priority, state, COALESCE(origin,''), COALESCE(owner,''), created_at`
|
||||
// IntentCleanup summarizes the blackboard records removed when a user cancels
|
||||
// one worker intent. Global assets and traffic are deliberately not part of this
|
||||
// operation; exploration anchors disappear only because their owning nodes do.
|
||||
type IntentCleanup struct {
|
||||
Intents int64 `json:"intents"`
|
||||
Facts int64 `json:"facts"`
|
||||
Findings int64 `json:"findings"`
|
||||
Activities int64 `json:"activities"`
|
||||
}
|
||||
|
||||
// CancelIntent removes one local intent and the fact/finding nodes it directly
|
||||
// yielded. The standalone finding row must be deleted before its node (whose FK
|
||||
// otherwise uses ON DELETE SET NULL), so the entire cleanup is kept in one DB
|
||||
// transaction. The caller must first stop a running worker to prevent late writes.
|
||||
func (s *ExplorationStore) CancelIntent(id int64) (IntentCleanup, error) {
|
||||
var out IntentCleanup
|
||||
tx, err := s.db.Begin()
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
var state string
|
||||
if err := tx.QueryRow(`SELECT state FROM exploration_nodes
|
||||
WHERE id=$1 AND exploration_id=$2 AND kind='intent' FOR UPDATE`, id, s.expID).Scan(&state); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return out, fmt.Errorf("intent not found")
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
if state != "running" && state != "paused" {
|
||||
return out, fmt.Errorf("intent state %s cannot be cancelled", state)
|
||||
}
|
||||
|
||||
if err := tx.QueryRow(`SELECT
|
||||
COUNT(*) FILTER (WHERE n.kind='fact'),
|
||||
COUNT(*) FILTER (WHERE n.kind='finding')
|
||||
FROM exploration_edges e
|
||||
JOIN exploration_nodes n ON n.id=e.dst_id AND n.exploration_id=e.exploration_id
|
||||
WHERE e.exploration_id=$1 AND e.src_id=$2 AND e.rel=$3
|
||||
AND n.kind IN ('fact','finding')`, s.expID, id, RelYields).Scan(&out.Facts, &out.Findings); err != nil {
|
||||
return out, err
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(`DELETE FROM findings f USING exploration_edges e, exploration_nodes n
|
||||
WHERE e.exploration_id=$1 AND e.src_id=$2 AND e.rel=$3
|
||||
AND n.id=e.dst_id AND n.exploration_id=e.exploration_id
|
||||
AND n.kind='finding' AND f.node_id=n.id`, s.expID, id, RelYields); err != nil {
|
||||
return out, err
|
||||
}
|
||||
res, err := tx.Exec(`DELETE FROM activity WHERE exploration_id=$1 AND node_id=$2`, s.expID, id)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Activities, _ = res.RowsAffected()
|
||||
|
||||
res, err = tx.Exec(`DELETE FROM exploration_nodes
|
||||
WHERE exploration_id=$1 AND (
|
||||
id=$2 OR id IN (
|
||||
SELECT e.dst_id FROM exploration_edges e
|
||||
JOIN exploration_nodes n ON n.id=e.dst_id AND n.exploration_id=e.exploration_id
|
||||
WHERE e.exploration_id=$1 AND e.src_id=$2 AND e.rel=$3
|
||||
AND n.kind IN ('fact','finding')
|
||||
)
|
||||
)`, s.expID, id, RelYields)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
if removed, _ := res.RowsAffected(); removed != 1+out.Facts+out.Findings {
|
||||
return out, fmt.Errorf("intent cleanup changed concurrently")
|
||||
}
|
||||
out.Intents = 1
|
||||
return out, tx.Commit()
|
||||
}
|
||||
|
||||
const nodeCols = `id, kind, payload, priority, state, COALESCE(origin,''), COALESCE(owner,''), COALESCE(blocked_reason,''), created_at`
|
||||
|
||||
func scanNode(sc interface{ Scan(...any) error }) (*Node, error) {
|
||||
var n Node
|
||||
var payload []byte
|
||||
if err := sc.Scan(&n.ID, &n.Kind, &payload, &n.Priority, &n.State, &n.Origin, &n.Owner, &n.CreatedAt); err != nil {
|
||||
if err := sc.Scan(&n.ID, &n.Kind, &payload, &n.Priority, &n.State, &n.Origin, &n.Owner, &n.BlockedReason, &n.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n.Payload = json.RawMessage(payload)
|
||||
@@ -455,6 +536,31 @@ WHERE e.exploration_id=$1 AND e.rel=$2 AND n.kind='finding'`, s.expID, RelYields
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// FindingIntentsTerminal is the inherited-history variant: it returns finding
|
||||
// lineage only when the producing intent has reached an immutable terminal
|
||||
// state. This keeps a source task's live worker topology private.
|
||||
func (s *ExplorationStore) FindingIntentsTerminal() (map[int64]int64, error) {
|
||||
rows, err := s.db.Query(`SELECT e.dst_id, e.src_id
|
||||
FROM exploration_edges e
|
||||
JOIN exploration_nodes finding ON finding.id=e.dst_id AND finding.exploration_id=e.exploration_id
|
||||
JOIN exploration_nodes intent ON intent.id=e.src_id AND intent.exploration_id=e.exploration_id
|
||||
WHERE e.exploration_id=$1 AND e.rel=$2 AND finding.kind='finding'
|
||||
AND intent.kind='intent' AND intent.state IN ('done','blocked','exhausted','stopped')`, s.expID, RelYields)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[int64]int64{}
|
||||
for rows.Next() {
|
||||
var findingID, intentID int64
|
||||
if err := rows.Scan(&findingID, &intentID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[findingID] = intentID
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Frontier returns open intents ordered by priority desc then id (FIFO tiebreak).
|
||||
func (s *ExplorationStore) Frontier(limit int) ([]*Node, error) {
|
||||
if limit <= 0 {
|
||||
@@ -516,12 +622,16 @@ func (s *ExplorationStore) Stats() (map[string]int, error) {
|
||||
|
||||
// AppendActivity records one worker step and returns its id.
|
||||
func (s *ExplorationStore) AppendActivity(a Activity) (int64, error) {
|
||||
metadata := a.Metadata
|
||||
if len(metadata) == 0 {
|
||||
metadata = json.RawMessage(`{}`)
|
||||
}
|
||||
var id int64
|
||||
err := s.db.QueryRow(`
|
||||
INSERT INTO activity(exploration_id, node_id, worker, kind, tool, tool_use_id, is_error, summary, detail, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens)
|
||||
VALUES ($1,$2,NULLIF($3,''),NULLIF($4,''),NULLIF($5,''),NULLIF($6,''),$7,NULLIF($8,''),NULLIF($9,''),$10,$11,$12,$13)
|
||||
INSERT INTO activity(exploration_id, node_id, worker, kind, tool, tool_use_id, is_error, summary, detail, metadata, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens)
|
||||
VALUES ($1,$2,NULLIF($3,''),NULLIF($4,''),NULLIF($5,''),NULLIF($6,''),$7,NULLIF($8,''),NULLIF($9,''),$10,$11,$12,$13,$14)
|
||||
RETURNING id`, s.expID, a.NodeID, utf8Clean(a.Worker), utf8Clean(a.Kind), utf8Clean(a.Tool), utf8Clean(a.ToolUseID), a.IsError, utf8Clean(a.Summary), utf8Clean(a.Detail),
|
||||
a.InputTokens, a.OutputTokens, a.CacheReadTokens, a.CacheWriteTokens).Scan(&id)
|
||||
metadata, a.InputTokens, a.OutputTokens, a.CacheReadTokens, a.CacheWriteTokens).Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
@@ -659,7 +769,7 @@ func (s *ExplorationStore) ActivityList(nodeID *int64, sinceID int64, limit int)
|
||||
}
|
||||
var rows *sql.Rows
|
||||
var err error
|
||||
const cols = `id, node_id, COALESCE(worker,''), COALESCE(kind,''), COALESCE(tool,''), COALESCE(tool_use_id,''), is_error, COALESCE(summary,''), created_at, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens`
|
||||
const cols = `id, node_id, COALESCE(worker,''), COALESCE(kind,''), COALESCE(tool,''), COALESCE(tool_use_id,''), is_error, COALESCE(summary,''), metadata, created_at, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens`
|
||||
if nodeID != nil {
|
||||
rows, err = s.db.Query(`SELECT `+cols+`
|
||||
FROM activity WHERE exploration_id=$1 AND node_id=$2 AND id>$3 ORDER BY id LIMIT $4`, s.expID, *nodeID, sinceID, limit)
|
||||
@@ -673,6 +783,43 @@ FROM activity WHERE exploration_id=$1 AND id>$2 ORDER BY id LIMIT $3`, s.expID,
|
||||
defer rows.Close()
|
||||
out := []Activity{}
|
||||
cursor := sinceID
|
||||
for rows.Next() {
|
||||
var a Activity
|
||||
if err := rows.Scan(&a.ID, &a.NodeID, &a.Worker, &a.Kind, &a.Tool, &a.ToolUseID, &a.IsError, &a.Summary, &a.Metadata, &a.CreatedAt,
|
||||
&a.InputTokens, &a.OutputTokens, &a.CacheReadTokens, &a.CacheWriteTokens); err != nil {
|
||||
return nil, sinceID, err
|
||||
}
|
||||
if a.ID > cursor {
|
||||
cursor = a.ID
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, cursor, rows.Err()
|
||||
}
|
||||
|
||||
// ActivityListForTerminalIntent is the inherited, incremental-read boundary.
|
||||
// The intent state check and activity read happen in one statement so a source
|
||||
// intent reopened between API-level checks cannot expose its new in-flight trace.
|
||||
// Model reasoning and accounting rows are never inherited.
|
||||
func (s *ExplorationStore) ActivityListForTerminalIntent(nodeID, sinceID int64, limit int) ([]Activity, int64, error) {
|
||||
if limit <= 0 {
|
||||
limit = 300
|
||||
}
|
||||
rows, err := s.db.Query(`SELECT a.id, a.node_id, COALESCE(a.worker,''), COALESCE(a.kind,''),
|
||||
COALESCE(a.tool,''), COALESCE(a.tool_use_id,''), a.is_error, COALESCE(a.summary,''),
|
||||
a.created_at, a.input_tokens, a.output_tokens, a.cache_read_tokens, a.cache_write_tokens
|
||||
FROM activity a
|
||||
JOIN exploration_nodes n ON n.id=a.node_id AND n.exploration_id=a.exploration_id
|
||||
WHERE a.exploration_id=$1 AND a.node_id=$2 AND a.id>$3
|
||||
AND n.kind='intent' AND n.state IN ('done','blocked','exhausted','stopped')
|
||||
AND a.kind NOT IN ('thinking','usage')
|
||||
ORDER BY a.id LIMIT $4`, s.expID, nodeID, sinceID, limit)
|
||||
if err != nil {
|
||||
return nil, sinceID, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []Activity{}
|
||||
cursor := sinceID
|
||||
for rows.Next() {
|
||||
var a Activity
|
||||
if err := rows.Scan(&a.ID, &a.NodeID, &a.Worker, &a.Kind, &a.Tool, &a.ToolUseID, &a.IsError, &a.Summary, &a.CreatedAt,
|
||||
@@ -719,7 +866,7 @@ func (s *ExplorationStore) ActivityPage(f ActivitySessionFilter, before int64, l
|
||||
if limit <= 0 {
|
||||
limit = 200
|
||||
}
|
||||
const cols = `id, node_id, COALESCE(worker,''), COALESCE(kind,''), COALESCE(tool,''), COALESCE(tool_use_id,''), is_error, COALESCE(summary,''), created_at, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens`
|
||||
const cols = `id, node_id, COALESCE(worker,''), COALESCE(kind,''), COALESCE(tool,''), COALESCE(tool_use_id,''), is_error, COALESCE(summary,''), metadata, created_at, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens`
|
||||
args := []any{s.expID}
|
||||
cond, cargs := f.cond(len(args) + 1)
|
||||
args = append(args, cargs...)
|
||||
@@ -736,6 +883,51 @@ ORDER BY id DESC LIMIT $%d`, cond, beforeArg, beforeArg, limitArg)
|
||||
}
|
||||
defer rows.Close()
|
||||
desc := []Activity{}
|
||||
for rows.Next() {
|
||||
var a Activity
|
||||
if err := rows.Scan(&a.ID, &a.NodeID, &a.Worker, &a.Kind, &a.Tool, &a.ToolUseID, &a.IsError, &a.Summary, &a.Metadata, &a.CreatedAt,
|
||||
&a.InputTokens, &a.OutputTokens, &a.CacheReadTokens, &a.CacheWriteTokens); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
desc = append(desc, a)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
hasMore := len(desc) > limit
|
||||
if hasMore {
|
||||
desc = desc[:limit]
|
||||
}
|
||||
// reverse the newest-first window into ascending id order for display.
|
||||
out := make([]Activity, len(desc))
|
||||
for i, a := range desc {
|
||||
out[len(desc)-1-i] = a
|
||||
}
|
||||
return out, hasMore, nil
|
||||
}
|
||||
|
||||
// ActivityPageForTerminalIntent is the inherited session-history boundary. It
|
||||
// combines ownership, terminal-state and row-kind checks in one query, closing
|
||||
// the race where a previously completed source intent is reopened before paging.
|
||||
func (s *ExplorationStore) ActivityPageForTerminalIntent(nodeID, before int64, limit int) ([]Activity, bool, error) {
|
||||
if limit <= 0 {
|
||||
limit = 200
|
||||
}
|
||||
rows, err := s.db.Query(`SELECT a.id, a.node_id, COALESCE(a.worker,''), COALESCE(a.kind,''),
|
||||
COALESCE(a.tool,''), COALESCE(a.tool_use_id,''), a.is_error, COALESCE(a.summary,''),
|
||||
a.created_at, a.input_tokens, a.output_tokens, a.cache_read_tokens, a.cache_write_tokens
|
||||
FROM activity a
|
||||
JOIN exploration_nodes n ON n.id=a.node_id AND n.exploration_id=a.exploration_id
|
||||
WHERE a.exploration_id=$1 AND a.node_id=$2
|
||||
AND n.kind='intent' AND n.state IN ('done','blocked','exhausted','stopped')
|
||||
AND a.kind NOT IN ('thinking','usage')
|
||||
AND ($3 <= 0 OR a.id < $3)
|
||||
ORDER BY a.id DESC LIMIT $4`, s.expID, nodeID, before, limit+1)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
defer rows.Close()
|
||||
desc := []Activity{}
|
||||
for rows.Next() {
|
||||
var a Activity
|
||||
if err := rows.Scan(&a.ID, &a.NodeID, &a.Worker, &a.Kind, &a.Tool, &a.ToolUseID, &a.IsError, &a.Summary, &a.CreatedAt,
|
||||
@@ -751,7 +943,6 @@ ORDER BY id DESC LIMIT $%d`, cond, beforeArg, beforeArg, limitArg)
|
||||
if hasMore {
|
||||
desc = desc[:limit]
|
||||
}
|
||||
// reverse the newest-first window into ascending id order for display.
|
||||
out := make([]Activity, len(desc))
|
||||
for i, a := range desc {
|
||||
out[len(desc)-1-i] = a
|
||||
@@ -817,6 +1008,26 @@ ORDER BY id LIMIT $3`, s.expID, nodeID, limit)
|
||||
return scanTrace(rows)
|
||||
}
|
||||
|
||||
// ActivityTraceForTerminalIntent returns one inherited work trace only while its
|
||||
// source intent is still terminal at query time.
|
||||
func (s *ExplorationStore) ActivityTraceForTerminalIntent(nodeID int64, limit int) ([]Activity, error) {
|
||||
if limit <= 0 {
|
||||
limit = 500
|
||||
}
|
||||
rows, err := s.db.Query(`SELECT a.id, a.node_id, COALESCE(a.worker,''), COALESCE(a.kind,''), COALESCE(a.tool,''), a.is_error, COALESCE(a.summary,'')
|
||||
FROM activity a
|
||||
JOIN exploration_nodes n ON n.id=a.node_id AND n.exploration_id=a.exploration_id
|
||||
WHERE a.exploration_id=$1 AND a.node_id=$2 AND n.kind='intent'
|
||||
AND n.state IN ('done','blocked','exhausted','stopped')
|
||||
AND a.kind NOT IN ('thinking','usage')
|
||||
ORDER BY a.id LIMIT $3`, s.expID, nodeID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanTrace(rows)
|
||||
}
|
||||
|
||||
// ActivityTraceSearch finds steps whose summary OR detail matches q
|
||||
// (case-insensitive), returning summaries only. nodeID != nil scopes to one work;
|
||||
// nil searches across ALL works (node_id IS NOT NULL — planner/main steps have no
|
||||
@@ -844,13 +1055,59 @@ AND (summary ILIKE $2 OR detail ILIKE $2) ORDER BY id LIMIT $3`, s.expID, like,
|
||||
return scanTrace(rows)
|
||||
}
|
||||
|
||||
// ActivityTraceSearchForTerminalIntent is the scoped inherited search variant;
|
||||
// terminal eligibility is evaluated by the same statement that reads the rows.
|
||||
func (s *ExplorationStore) ActivityTraceSearchForTerminalIntent(nodeID int64, q string, limit int) ([]Activity, error) {
|
||||
if limit <= 0 {
|
||||
limit = 100
|
||||
}
|
||||
like := "%" + q + "%"
|
||||
rows, err := s.db.Query(`SELECT a.id, a.node_id, COALESCE(a.worker,''), COALESCE(a.kind,''), COALESCE(a.tool,''), a.is_error, COALESCE(a.summary,'')
|
||||
FROM activity a
|
||||
JOIN exploration_nodes n ON n.id=a.node_id AND n.exploration_id=a.exploration_id
|
||||
WHERE a.exploration_id=$1 AND a.node_id=$2 AND n.kind='intent'
|
||||
AND n.state IN ('done','blocked','exhausted','stopped')
|
||||
AND a.kind NOT IN ('thinking','usage')
|
||||
AND (a.summary ILIKE $3 OR a.detail ILIKE $3)
|
||||
ORDER BY a.id LIMIT $4`, s.expID, nodeID, like, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanTrace(rows)
|
||||
}
|
||||
|
||||
// ActivityTraceSearchTerminalIntents searches inherited worker history without
|
||||
// exposing planner/main rows or work that is still open/running in the source.
|
||||
func (s *ExplorationStore) ActivityTraceSearchTerminalIntents(q string, limit int) ([]Activity, error) {
|
||||
if limit <= 0 {
|
||||
limit = 100
|
||||
}
|
||||
like := "%" + q + "%"
|
||||
rows, err := s.db.Query(`SELECT a.id, a.node_id, COALESCE(a.worker,''), COALESCE(a.kind,''), COALESCE(a.tool,''), a.is_error, COALESCE(a.summary,'')
|
||||
FROM activity a
|
||||
JOIN exploration_nodes n ON n.id=a.node_id AND n.exploration_id=a.exploration_id
|
||||
WHERE a.exploration_id=$1 AND n.kind='intent'
|
||||
AND n.state IN ('done','blocked','exhausted','stopped')
|
||||
AND a.kind NOT IN ('thinking','usage')
|
||||
AND (a.summary ILIKE $2 OR a.detail ILIKE $2)
|
||||
ORDER BY a.id LIMIT $3`, s.expID, like, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanTrace(rows)
|
||||
}
|
||||
|
||||
// AssetRef is a compact exploration node (intent/fact/finding) that references an
|
||||
// asset via an anchor — for the coverage graph's node drawer.
|
||||
type AssetRef struct {
|
||||
ID int64 `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
State string `json:"state"`
|
||||
Summary string `json:"summary"`
|
||||
ID int64 `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
State string `json:"state"`
|
||||
Summary string `json:"summary"`
|
||||
SourceTaskID int64 `json:"source_task_id,omitempty"`
|
||||
Inherited bool `json:"inherited,omitempty"`
|
||||
}
|
||||
|
||||
// AssetRefs returns the intents / facts / findings in THIS exploration anchored to
|
||||
@@ -943,6 +1200,42 @@ FROM activity WHERE exploration_id=$1 AND kind<>'thinking' AND id IN (`+strings.
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ActivityByIDsForTerminalIntents is the inherited-detail read boundary. It
|
||||
// deliberately excludes node-less planner/main rows, non-intent activities, live
|
||||
// source work, and thinking. Local callers that need legacy behavior use
|
||||
// ActivityByIDs instead.
|
||||
func (s *ExplorationStore) ActivityByIDsForTerminalIntents(ids []int64) ([]Activity, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
ph := make([]string, len(ids))
|
||||
args := make([]any, len(ids)+1)
|
||||
args[0] = s.expID
|
||||
for i, id := range ids {
|
||||
ph[i] = fmt.Sprintf("$%d", i+2)
|
||||
args[i+1] = id
|
||||
}
|
||||
rows, err := s.db.Query(`SELECT a.id, a.node_id, COALESCE(a.kind,''), COALESCE(a.tool,''), a.is_error, COALESCE(a.detail,'')
|
||||
FROM activity a
|
||||
JOIN exploration_nodes n ON n.id=a.node_id AND n.exploration_id=a.exploration_id
|
||||
WHERE a.exploration_id=$1 AND a.kind NOT IN ('thinking','usage') AND n.kind='intent'
|
||||
AND n.state IN ('done','blocked','exhausted','stopped')
|
||||
AND a.id IN (`+strings.Join(ph, ",")+`) ORDER BY a.id`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []Activity{}
|
||||
for rows.Next() {
|
||||
var a Activity
|
||||
if err := rows.Scan(&a.ID, &a.NodeID, &a.Kind, &a.Tool, &a.IsError, &a.Detail); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// AddStandaloneFinding writes a finding to the standalone findings table, which
|
||||
// persists across task deletion (task_id / node_id become NULL when the task or
|
||||
// exploration node is deleted). taskID and nodeID may be 0 (stored as NULL).
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// DirectSourceStore binds one directly related task to its exploration store.
|
||||
// It is intentionally a read-side helper: callers keep using the receiver store
|
||||
// for every graph mutation, frontier lookup, and intent claim.
|
||||
type DirectSourceStore struct {
|
||||
Task TaskSource
|
||||
Store *ExplorationStore
|
||||
}
|
||||
|
||||
// DirectSourceStores resolves the live, direct task relations for this
|
||||
// exploration. It deliberately queries on every call: relations disappear when
|
||||
// a source task is deleted, and inherited context must not retain stale rows.
|
||||
// Sources of a source are never expanded.
|
||||
func (s *ExplorationStore) DirectSourceStores() ([]DirectSourceStore, error) {
|
||||
rows, err := s.db.Query(`
|
||||
SELECT source.id, source.exploration_id, source.description, source.goal, source.status
|
||||
FROM tasks owner
|
||||
JOIN task_relations relation ON relation.task_id=owner.id
|
||||
JOIN tasks source ON source.id=relation.source_task_id AND source.deleted_at IS NULL
|
||||
WHERE owner.exploration_id=$1 AND owner.deleted_at IS NULL
|
||||
ORDER BY relation.created_at, source.id`, s.expID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []DirectSourceStore{}
|
||||
for rows.Next() {
|
||||
var source TaskSource
|
||||
if err := rows.Scan(&source.TaskID, &source.ExplorationID, &source.Description, &source.Goal, &source.Status); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, DirectSourceStore{Task: source, Store: s.db.Exploration(source.ExplorationID)})
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// TaskID returns the live task bound to this exploration. Explorations created
|
||||
// directly in tests or maintenance code have no task and return zero.
|
||||
func (s *ExplorationStore) TaskID() (int64, error) {
|
||||
var id int64
|
||||
err := s.db.QueryRow(`SELECT id FROM tasks WHERE exploration_id=$1 AND deleted_at IS NULL`, s.expID).Scan(&id)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return 0, nil
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func markInheritedNode(n *Node, taskID int64) *Node {
|
||||
if n == nil {
|
||||
return nil
|
||||
}
|
||||
n.SourceTaskID = taskID
|
||||
n.Inherited = true
|
||||
return n
|
||||
}
|
||||
|
||||
func markInheritedActivities(in []Activity, taskID int64) []Activity {
|
||||
for i := range in {
|
||||
in[i].SourceTaskID = taskID
|
||||
in[i].Inherited = true
|
||||
}
|
||||
return in
|
||||
}
|
||||
|
||||
func inheritedIntentTerminal(state string) bool {
|
||||
switch state {
|
||||
case "done", "blocked", "exhausted", "stopped":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// ListByKindWithSources returns local nodes followed by nodes from each direct
|
||||
// source in relation order. The limit remains per exploration, matching the
|
||||
// existing ListByKind contract while ensuring one large task cannot hide all
|
||||
// inherited context from another source.
|
||||
func (s *ExplorationStore) ListByKindWithSources(kind string, limit int) ([]*Node, error) {
|
||||
out, err := s.ListByKind(kind, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sources, err := s.DirectSourceStores()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, source := range sources {
|
||||
nodes, err := source.Store.ListByKind(kind, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, node := range nodes {
|
||||
if kind == KindIntent && !inheritedIntentTerminal(node.State) {
|
||||
continue
|
||||
}
|
||||
out = append(out, markInheritedNode(node, source.Task.TaskID))
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetNodeWithSources reads a node only when it belongs to this exploration or
|
||||
// one of its direct sources. Inherited nodes are tagged so tool callers can keep
|
||||
// them read-only and show their provenance.
|
||||
func (s *ExplorationStore) GetNodeWithSources(id int64) (*Node, error) {
|
||||
node, err := s.GetNode(id)
|
||||
if err != nil || node != nil {
|
||||
return node, err
|
||||
}
|
||||
sources, err := s.DirectSourceStores()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, source := range sources {
|
||||
node, err = source.Store.GetNode(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if node != nil {
|
||||
if node.Kind == KindIntent && !inheritedIntentTerminal(node.State) {
|
||||
continue
|
||||
}
|
||||
return markInheritedNode(node, source.Task.TaskID), nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// FindingIntentsWithSources combines finding lineage for the current
|
||||
// exploration and each direct source. Node ids are globally unique.
|
||||
func (s *ExplorationStore) FindingIntentsWithSources() (map[int64]int64, error) {
|
||||
out, err := s.FindingIntents()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sources, err := s.DirectSourceStores()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, source := range sources {
|
||||
items, err := source.Store.FindingIntentsTerminal()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for findingID, intentID := range items {
|
||||
out[findingID] = intentID
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ActivityTraceWithSources returns a work trace when its intent belongs to the
|
||||
// current exploration or a direct source. It never searches indirect sources.
|
||||
func (s *ExplorationStore) ActivityTraceWithSources(nodeID int64, limit int) ([]Activity, error) {
|
||||
acts, err := s.ActivityTrace(nodeID, limit)
|
||||
if err != nil || len(acts) > 0 {
|
||||
return acts, err
|
||||
}
|
||||
sources, err := s.DirectSourceStores()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, source := range sources {
|
||||
node, nodeErr := source.Store.GetNode(nodeID)
|
||||
if nodeErr != nil {
|
||||
return nil, nodeErr
|
||||
}
|
||||
if node == nil || node.Kind != KindIntent {
|
||||
continue
|
||||
}
|
||||
acts, err = source.Store.ActivityTraceForTerminalIntent(nodeID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(acts) > 0 {
|
||||
return markInheritedActivities(acts, source.Task.TaskID), nil
|
||||
}
|
||||
}
|
||||
return []Activity{}, nil
|
||||
}
|
||||
|
||||
// ActivityListWithSources is the source-aware equivalent used by
|
||||
// get_worker_output. Node ids are global, so the first owning exploration is
|
||||
// unambiguous even when the work has not emitted any activity yet.
|
||||
func (s *ExplorationStore) ActivityListWithSources(nodeID, sinceID int64, limit int) ([]Activity, int64, error) {
|
||||
node, err := s.GetNode(nodeID)
|
||||
if err != nil {
|
||||
return nil, sinceID, err
|
||||
}
|
||||
if node != nil {
|
||||
return s.ActivityList(&nodeID, sinceID, limit)
|
||||
}
|
||||
sources, err := s.DirectSourceStores()
|
||||
if err != nil {
|
||||
return nil, sinceID, err
|
||||
}
|
||||
for _, source := range sources {
|
||||
node, err = source.Store.GetNode(nodeID)
|
||||
if err != nil {
|
||||
return nil, sinceID, err
|
||||
}
|
||||
if node == nil || node.Kind != KindIntent {
|
||||
continue
|
||||
}
|
||||
acts, cursor, err := source.Store.ActivityListForTerminalIntent(nodeID, sinceID, limit)
|
||||
if err != nil {
|
||||
return nil, sinceID, err
|
||||
}
|
||||
return markInheritedActivities(acts, source.Task.TaskID), cursor, nil
|
||||
}
|
||||
return []Activity{}, sinceID, nil
|
||||
}
|
||||
|
||||
// ActivityDetailWithSources keeps the legacy local-task lookup (including local
|
||||
// thinking rows), while inherited details are restricted to terminal worker
|
||||
// intents. Source planner/main rows have no node id and must never become part of
|
||||
// inherited context.
|
||||
func (s *ExplorationStore) ActivityDetailWithSources(id int64) (string, error) {
|
||||
detail, err := s.ActivityDetail(id)
|
||||
if err != nil || detail != "" {
|
||||
return detail, err
|
||||
}
|
||||
acts, err := s.ActivityByIDsWithSources([]int64{id})
|
||||
if err != nil || len(acts) == 0 {
|
||||
return "", err
|
||||
}
|
||||
return acts[0].Detail, nil
|
||||
}
|
||||
|
||||
// ActivityTraceSearchWithSources performs the scoped worker-trace search used
|
||||
// by get_worker_trace. A node id resolves to at most one exploration because
|
||||
// exploration node ids are global.
|
||||
func (s *ExplorationStore) ActivityTraceSearchWithSources(nodeID int64, q string, limit int) ([]Activity, error) {
|
||||
acts, err := s.ActivityTraceSearch(&nodeID, q, limit)
|
||||
if err != nil || len(acts) > 0 {
|
||||
return acts, err
|
||||
}
|
||||
sources, err := s.DirectSourceStores()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, source := range sources {
|
||||
node, nodeErr := source.Store.GetNode(nodeID)
|
||||
if nodeErr != nil {
|
||||
return nil, nodeErr
|
||||
}
|
||||
if node == nil || node.Kind != KindIntent {
|
||||
continue
|
||||
}
|
||||
acts, err = source.Store.ActivityTraceSearchForTerminalIntent(nodeID, q, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(acts) > 0 {
|
||||
return markInheritedActivities(acts, source.Task.TaskID), nil
|
||||
}
|
||||
}
|
||||
return []Activity{}, nil
|
||||
}
|
||||
|
||||
// ActivityTraceSearchAllWithSources searches local worker traces plus every
|
||||
// direct source. The local owner is excluded only from the current exploration;
|
||||
// inherited traces are immutable historical context.
|
||||
func (s *ExplorationStore) ActivityTraceSearchAllWithSources(excludeNodeID int64, q string, limit int) ([]Activity, error) {
|
||||
if limit <= 0 {
|
||||
limit = 100
|
||||
}
|
||||
out, err := s.ActivityTraceSearchExcluding(excludeNodeID, q, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sources, err := s.DirectSourceStores()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, source := range sources {
|
||||
acts, err := source.Store.ActivityTraceSearchTerminalIntents(q, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, markInheritedActivities(acts, source.Task.TaskID)...)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
|
||||
if len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ActivityByIDsWithSources loads local step details with the legacy behavior. For
|
||||
// direct sources it only returns rows attached to terminal intents, preventing an
|
||||
// arbitrary global activity id from exposing source planner/main transcripts.
|
||||
func (s *ExplorationStore) ActivityByIDsWithSources(ids []int64) ([]Activity, error) {
|
||||
out, err := s.ActivityByIDs(ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sources, err := s.DirectSourceStores()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, source := range sources {
|
||||
acts, err := source.Store.ActivityByIDsForTerminalIntents(ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, markInheritedActivities(acts, source.Task.TaskID)...)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// AssetRefsWithSources returns anchored nodes from this exploration and each
|
||||
// direct source. Inherited entries retain their owning task id so API/UI callers
|
||||
// can present them as immutable context.
|
||||
func (s *ExplorationStore) AssetRefsWithSources(assetID int64) ([]AssetRef, error) {
|
||||
out, err := s.AssetRefs(assetID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sources, err := s.DirectSourceStores()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, source := range sources {
|
||||
refs, err := source.Store.AssetRefs(assetID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range refs {
|
||||
if refs[i].Kind == KindIntent && !inheritedIntentTerminal(refs[i].State) {
|
||||
continue
|
||||
}
|
||||
refs[i].SourceTaskID = source.Task.TaskID
|
||||
refs[i].Inherited = true
|
||||
out = append(out, refs[i])
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID > out[j].ID })
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInheritedActivityReadsRequireTerminalIntent(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
expID, err := d.CreateExploration("source activity boundary", "source activity boundary")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM explorations WHERE id=$1`, expID) })
|
||||
store := d.Exploration(expID)
|
||||
intentID, err := store.AddIntent(map[string]any{"summary": "source work"}, 1, nil, "planner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
appendStep := func(kind, summary string) int64 {
|
||||
t.Helper()
|
||||
id, appendErr := store.AppendActivity(Activity{
|
||||
NodeID: &intentID, Worker: "worker", Kind: kind, Summary: summary, Detail: summary + " detail",
|
||||
})
|
||||
if appendErr != nil {
|
||||
t.Fatal(appendErr)
|
||||
}
|
||||
return id
|
||||
}
|
||||
textID := appendStep("text", "shared text")
|
||||
thinkingID := appendStep("thinking", "private reasoning")
|
||||
usageID := appendStep("usage", "private accounting")
|
||||
resultID := appendStep("result", "shared result")
|
||||
if err := store.SetIntentState(intentID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
page, more, err := store.ActivityPageForTerminalIntent(intentID, 0, 10)
|
||||
if err != nil || more || len(page) != 2 || page[0].ID != textID || page[1].ID != resultID {
|
||||
t.Fatalf("terminal page boundary: page=%+v more=%v err=%v", page, more, err)
|
||||
}
|
||||
list, cursor, err := store.ActivityListForTerminalIntent(intentID, 0, 10)
|
||||
if err != nil || len(list) != 2 || cursor != resultID {
|
||||
t.Fatalf("terminal list boundary: list=%+v cursor=%d err=%v", list, cursor, err)
|
||||
}
|
||||
trace, err := store.ActivityTraceForTerminalIntent(intentID, 10)
|
||||
if err != nil || len(trace) != 2 {
|
||||
t.Fatalf("terminal trace boundary: trace=%+v err=%v", trace, err)
|
||||
}
|
||||
hits, err := store.ActivityTraceSearchForTerminalIntent(intentID, "shared", 10)
|
||||
if err != nil || len(hits) != 2 {
|
||||
t.Fatalf("terminal search boundary: hits=%+v err=%v", hits, err)
|
||||
}
|
||||
details, err := store.ActivityByIDsForTerminalIntents([]int64{textID, thinkingID, usageID, resultID})
|
||||
if err != nil || len(details) != 2 || details[0].ID != textID || details[1].ID != resultID {
|
||||
t.Fatalf("terminal detail boundary: details=%+v err=%v", details, err)
|
||||
}
|
||||
|
||||
// Reopening a source intent must close every inherited activity read even if
|
||||
// callers still hold a stale terminal-state snapshot.
|
||||
if err := store.SetIntentState(intentID, "running"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
page, _, err = store.ActivityPageForTerminalIntent(intentID, 0, 10)
|
||||
if err != nil || len(page) != 0 {
|
||||
t.Fatalf("reopened intent leaked through page: page=%+v err=%v", page, err)
|
||||
}
|
||||
list, _, err = store.ActivityListForTerminalIntent(intentID, 0, 10)
|
||||
if err != nil || len(list) != 0 {
|
||||
t.Fatalf("reopened intent leaked through list: list=%+v err=%v", list, err)
|
||||
}
|
||||
trace, err = store.ActivityTraceForTerminalIntent(intentID, 10)
|
||||
if err != nil || len(trace) != 0 {
|
||||
t.Fatalf("reopened intent leaked through trace: trace=%+v err=%v", trace, err)
|
||||
}
|
||||
hits, err = store.ActivityTraceSearchForTerminalIntent(intentID, "shared", 10)
|
||||
if err != nil || len(hits) != 0 {
|
||||
t.Fatalf("reopened intent leaked through search: hits=%+v err=%v", hits, err)
|
||||
}
|
||||
details, err = store.ActivityByIDsForTerminalIntents([]int64{textID, resultID})
|
||||
if err != nil || len(details) != 0 {
|
||||
t.Fatalf("reopened intent leaked through detail: details=%+v err=%v", details, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExplorationDirectSourceReadView(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
grand, err := d.CreateTask("grand source", "grand goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source, err := d.CreateTaskWithOptions("direct source", "source goal", TaskCreateOptions{
|
||||
SourceTaskIDs: []int64{grand.ID},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current, err := d.CreateTaskWithOptions("current", "current goal", TaskCreateOptions{
|
||||
SourceTaskIDs: []int64{source.ID},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = d.DeleteTask(current.ID)
|
||||
_ = d.DeleteTask(source.ID)
|
||||
_ = d.DeleteTask(grand.ID)
|
||||
})
|
||||
|
||||
grandStore := d.Exploration(grand.ExplorationID)
|
||||
sourceStore := d.Exploration(source.ExplorationID)
|
||||
currentStore := d.Exploration(current.ExplorationID)
|
||||
|
||||
grandFact, err := grandStore.AddNode(KindFact, map[string]any{"summary": "grand-only fact"}, 0, "confirmed", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sourceFact, err := sourceStore.AddNode(KindFact, map[string]any{"summary": "direct source fact"}, 0, "confirmed", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sourceFinding, err := sourceStore.AddNode(KindFinding, map[string]any{"summary": "direct source finding"}, 0, "confirmed", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sourceIntent, err := sourceStore.AddIntent(map[string]any{"summary": "source work"}, 9, nil, "planner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := sourceStore.Link(sourceIntent, RelYields, sourceFinding); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
currentIntent, err := currentStore.AddIntent(map[string]any{"summary": "current work"}, 1, nil, "planner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
currentFact, err := currentStore.AddNode(KindFact, map[string]any{"summary": "current fact"}, 0, "confirmed", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
sources, err := currentStore.DirectSourceStores()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(sources) != 1 || sources[0].Task.TaskID != source.ID {
|
||||
t.Fatalf("want only direct source %d, got %+v", source.ID, sources)
|
||||
}
|
||||
|
||||
frontier, err := currentStore.Frontier(20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(frontier) != 1 || frontier[0].ID != currentIntent {
|
||||
t.Fatalf("source intent leaked into local frontier: %+v", frontier)
|
||||
}
|
||||
if claimed, err := currentStore.ClaimIntent(sourceIntent, "wrong-task-worker"); err != nil || claimed {
|
||||
t.Fatalf("source intent must not be claimable: claimed=%v err=%v", claimed, err)
|
||||
}
|
||||
if got, err := currentStore.GetNodeWithSources(sourceIntent); err != nil || got != nil {
|
||||
t.Fatalf("live source intent must not be readable as inherited history: node=%+v err=%v", got, err)
|
||||
}
|
||||
if got, err := currentStore.ListByKindWithSources(KindIntent, 100); err != nil || len(got) != 1 || got[0].ID != currentIntent {
|
||||
t.Fatalf("live source intent leaked through inherited list: nodes=%+v err=%v", got, err)
|
||||
}
|
||||
if got, err := currentStore.FindingIntentsWithSources(); err != nil || got[sourceFinding] != 0 {
|
||||
t.Fatalf("live source intent leaked through finding lineage: lineage=%+v err=%v", got, err)
|
||||
}
|
||||
|
||||
facts, err := currentStore.ListByKindWithSources(KindFact, 100)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seenCurrent, seenSource, seenGrand := false, false, false
|
||||
for _, fact := range facts {
|
||||
switch fact.ID {
|
||||
case currentFact:
|
||||
seenCurrent = !fact.Inherited && fact.SourceTaskID == 0
|
||||
case sourceFact:
|
||||
seenSource = fact.Inherited && fact.SourceTaskID == source.ID
|
||||
case grandFact:
|
||||
seenGrand = true
|
||||
}
|
||||
}
|
||||
if !seenCurrent || !seenSource || seenGrand {
|
||||
t.Fatalf("unexpected direct-source fact view: current=%v source=%v grand=%v", seenCurrent, seenSource, seenGrand)
|
||||
}
|
||||
|
||||
gotSource, err := currentStore.GetNodeWithSources(sourceFact)
|
||||
if err != nil || gotSource == nil || !gotSource.Inherited || gotSource.SourceTaskID != source.ID {
|
||||
t.Fatalf("source node lookup: node=%+v err=%v", gotSource, err)
|
||||
}
|
||||
gotGrand, err := currentStore.GetNodeWithSources(grandFact)
|
||||
if err != nil || gotGrand != nil {
|
||||
t.Fatalf("indirect source must be invisible: node=%+v err=%v", gotGrand, err)
|
||||
}
|
||||
|
||||
// Existing write methods remain bound to currentStore.expID. Passing an
|
||||
// inherited id is a no-op and cannot mutate the source blackboard.
|
||||
if err := currentStore.SetNodeState(sourceFact, "dismissed"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unchanged, err := sourceStore.GetNode(sourceFact)
|
||||
if err != nil || unchanged == nil || unchanged.State != "confirmed" {
|
||||
t.Fatalf("inherited fact was mutated: node=%+v err=%v", unchanged, err)
|
||||
}
|
||||
|
||||
if err := sourceStore.SetIntentState(sourceIntent, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := currentStore.GetNodeWithSources(sourceIntent); err != nil || got == nil || !got.Inherited {
|
||||
t.Fatalf("terminal source intent should become readable history: node=%+v err=%v", got, err)
|
||||
}
|
||||
if got, err := currentStore.FindingIntentsWithSources(); err != nil || got[sourceFinding] != sourceIntent {
|
||||
t.Fatalf("terminal source finding lineage missing: lineage=%+v err=%v", got, err)
|
||||
}
|
||||
sourcePlannerStep, err := sourceStore.AppendActivity(Activity{
|
||||
Worker: "planner", Kind: "text", Summary: "private source planner", Detail: "private source planner transcript",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
openSourceIntent, err := sourceStore.AddIntent(map[string]any{"summary": "source work still running"}, 1, nil, "planner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := sourceStore.SetIntentState(openSourceIntent, "running"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
openSourceStep, err := sourceStore.AppendActivity(Activity{
|
||||
NodeID: &openSourceIntent, Worker: "source-live-worker", Kind: "text",
|
||||
Summary: "private live source work", Detail: "private live source transcript",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sourceStep, err := sourceStore.AppendActivity(Activity{
|
||||
NodeID: &sourceIntent, Worker: "source-worker", Kind: "tool_result", Tool: "HTTP",
|
||||
Summary: "source-secret response", Detail: "source-secret full detail",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
currentPlannerStep, err := currentStore.AppendActivity(Activity{
|
||||
Worker: "planner", Kind: "text", Summary: "current planner", Detail: "current planner detail",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
currentThinkingStep, err := currentStore.AppendActivity(Activity{
|
||||
Worker: "planner", Kind: "thinking", Summary: "current thinking", Detail: "current thinking detail",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
grandStep, err := grandStore.AppendActivity(Activity{
|
||||
NodeID: &grandFact, Worker: "grand-worker", Kind: "tool_result", Tool: "HTTP",
|
||||
Summary: "grand-only response", Detail: "grand-only detail",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
trace, err := currentStore.ActivityTraceWithSources(sourceIntent, 20)
|
||||
if err != nil || len(trace) != 1 || trace[0].ID != sourceStep || !trace[0].Inherited || trace[0].SourceTaskID != source.ID {
|
||||
t.Fatalf("source trace lookup: trace=%+v err=%v", trace, err)
|
||||
}
|
||||
hits, err := currentStore.ActivityTraceSearchAllWithSources(0, "source-secret", 20)
|
||||
if err != nil || len(hits) != 1 || hits[0].ID != sourceStep || !hits[0].Inherited {
|
||||
t.Fatalf("source trace search: hits=%+v err=%v", hits, err)
|
||||
}
|
||||
grandHits, err := currentStore.ActivityTraceSearchAllWithSources(0, "grand-only", 20)
|
||||
if err != nil || len(grandHits) != 0 {
|
||||
t.Fatalf("indirect source trace leaked: hits=%+v err=%v", grandHits, err)
|
||||
}
|
||||
liveHits, err := currentStore.ActivityTraceSearchAllWithSources(0, "private live source", 20)
|
||||
if err != nil || len(liveHits) != 0 {
|
||||
t.Fatalf("live source trace leaked: hits=%+v err=%v", liveHits, err)
|
||||
}
|
||||
if liveTrace, err := currentStore.ActivityTraceWithSources(openSourceIntent, 20); err != nil || len(liveTrace) != 0 {
|
||||
t.Fatalf("live inherited intent trace leaked: trace=%+v err=%v", liveTrace, err)
|
||||
}
|
||||
details, err := currentStore.ActivityByIDsWithSources([]int64{
|
||||
sourcePlannerStep, openSourceStep, sourceStep, currentPlannerStep, grandStep,
|
||||
})
|
||||
if err != nil || len(details) != 2 || details[0].ID != sourceStep || !details[0].Inherited || details[1].ID != currentPlannerStep || details[1].Inherited {
|
||||
t.Fatalf("source trace detail allow-list: details=%+v err=%v", details, err)
|
||||
}
|
||||
if detail, err := currentStore.ActivityDetailWithSources(sourcePlannerStep); err != nil || detail != "" {
|
||||
t.Fatalf("source planner transcript leaked: detail=%q err=%v", detail, err)
|
||||
}
|
||||
if detail, err := currentStore.ActivityDetailWithSources(openSourceStep); err != nil || detail != "" {
|
||||
t.Fatalf("live source intent transcript leaked: detail=%q err=%v", detail, err)
|
||||
}
|
||||
if detail, err := currentStore.ActivityDetailWithSources(currentPlannerStep); err != nil || detail != "current planner detail" {
|
||||
t.Fatalf("local activity detail behavior changed: detail=%q err=%v", detail, err)
|
||||
}
|
||||
if detail, err := currentStore.ActivityDetailWithSources(currentThinkingStep); err != nil || detail != "current thinking detail" {
|
||||
t.Fatalf("local thinking detail behavior changed: detail=%q err=%v", detail, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskAssetContextUsesDirectSourceScopeAndAnchors(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
grand, err := d.CreateTask("grand assets", "grand goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source, err := d.CreateTaskWithOptions("source assets", "source goal", TaskCreateOptions{SourceTaskIDs: []int64{grand.ID}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current, err := d.CreateTaskWithOptions("current assets", "current goal", TaskCreateOptions{SourceTaskIDs: []int64{source.ID}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assets := d.Assets()
|
||||
sourceTestedDomain := fmt.Sprintf("context-tested-%d.invalid", source.ID)
|
||||
sourceUntestedDomain := fmt.Sprintf("context-untested-%d.invalid", source.ID)
|
||||
sourceAnchoredOnlyDomain := fmt.Sprintf("context-anchor-only-%d.invalid", source.ID)
|
||||
grandDomain := fmt.Sprintf("context-grand-%d.invalid", grand.ID)
|
||||
sourceTestedID, err := assets.UpsertRootDomain(UpsertRootDomainReq{Domain: sourceTestedDomain, TaskID: source.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sourceUntestedID, err := assets.UpsertRootDomain(UpsertRootDomainReq{Domain: sourceUntestedDomain, TaskID: source.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sourceAnchoredOnlyID, err := assets.UpsertRootDomain(UpsertRootDomainReq{Domain: sourceAnchoredOnlyDomain, TaskID: source.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
grandID, err := assets.UpsertRootDomain(UpsertRootDomainReq{Domain: grandDomain, TaskID: grand.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = d.DeleteTask(current.ID)
|
||||
_ = d.DeleteTask(source.ID)
|
||||
_ = d.DeleteTask(grand.ID)
|
||||
_, _ = assets.DeleteByIDs([]int64{sourceTestedID, sourceUntestedID, sourceAnchoredOnlyID, grandID})
|
||||
})
|
||||
if _, err := assets.AddAgentScope(source.ID, "root_domain", sourceTestedDomain, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := assets.AddAgentScope(source.ID, "root_domain", sourceUntestedDomain, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := assets.AddAgentScope(grand.ID, "root_domain", grandDomain, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := d.Exploration(source.ExplorationID).AddNode(KindFact, map[string]any{"summary": "tested source asset"}, 0, "confirmed", "worker", []int64{sourceTestedID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := d.Exploration(source.ExplorationID).AddNode(KindFact, map[string]any{"summary": "anchored-only source asset"}, 0, "confirmed", "worker", []int64{sourceAnchoredOnlyID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := d.Exploration(grand.ExplorationID).AddNode(KindFact, map[string]any{"summary": "indirect tested asset"}, 0, "confirmed", "worker", []int64{grandID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
scopes, err := assets.ListTaskScopeWithSources(current.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(scopes) != 2 || scopes[0].TaskID != source.ID || scopes[1].TaskID != source.ID {
|
||||
t.Fatalf("direct source scopes only: %+v", scopes)
|
||||
}
|
||||
cov, err := assets.TaskCoverageWithSources(current.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cov.Denominator != 3 || cov.Tested != 2 {
|
||||
t.Fatalf("combined coverage: %+v", cov)
|
||||
}
|
||||
untested, total, err := assets.ListUntestedAssetsWithSources(current.ID, "", 10, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if total != 1 || len(untested) != 1 || untested[0].ID != sourceUntestedID {
|
||||
t.Fatalf("combined untested assets: total=%d assets=%+v", total, untested)
|
||||
}
|
||||
hosts, err := assets.HostsByTaskWithSources(current.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hostSet := map[string]bool{}
|
||||
for _, host := range hosts {
|
||||
hostSet[host] = true
|
||||
}
|
||||
if !hostSet[sourceTestedDomain] || !hostSet[sourceUntestedDomain] || !hostSet[sourceAnchoredOnlyDomain] || hostSet[grandDomain] {
|
||||
t.Fatalf("direct source hosts only: %v", hosts)
|
||||
}
|
||||
refs, err := d.Exploration(current.ExplorationID).AssetRefsWithSources(sourceAnchoredOnlyID)
|
||||
if err != nil || len(refs) != 1 || !refs[0].Inherited || refs[0].SourceTaskID != source.ID || refs[0].Kind != KindFact {
|
||||
t.Fatalf("source asset refs provenance: refs=%+v err=%v", refs, err)
|
||||
}
|
||||
grandRefs, err := d.Exploration(current.ExplorationID).AssetRefsWithSources(grandID)
|
||||
if err != nil || len(grandRefs) != 0 {
|
||||
t.Fatalf("indirect source asset refs leaked: refs=%+v err=%v", grandRefs, err)
|
||||
}
|
||||
graph, err := assets.BuildCoverageGraph(current.ID, current.ExplorationID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seenAnchoredOnly := false
|
||||
for _, node := range graph.Nodes {
|
||||
if node.AssetID == sourceAnchoredOnlyID {
|
||||
seenAnchoredOnly = node.Tested && node.InScope
|
||||
}
|
||||
}
|
||||
if !seenAnchoredOnly {
|
||||
t.Fatalf("anchored-only source asset missing from coverage graph: %+v", graph.Nodes)
|
||||
}
|
||||
}
|
||||
+135
-1
@@ -1,6 +1,9 @@
|
||||
package db
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExplorationFlow(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
@@ -112,3 +115,134 @@ func TestExplorationFlow(t *testing.T) {
|
||||
t.Fatalf("stats: %+v", st)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntentPauseResumeAndCancelCleanup(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) — skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
expID, err := d.CreateExploration("test", "worker control cleanup")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.Exec(`DELETE FROM explorations WHERE id=$1`, expID)
|
||||
es := d.Exploration(expID)
|
||||
|
||||
assetID, err := d.Assets().UpsertRootDomain(UpsertRootDomainReq{
|
||||
Domain: fmt.Sprintf("cancel-intent-%d.invalid", expID),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer deleteAsset(d, assetID)
|
||||
|
||||
otherIntent, err := es.AddIntent(map[string]any{"summary": "keep intent"}, 1, nil, "planner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
intentID, err := es.AddIntent(map[string]any{"summary": "cancel intent"}, 10, nil, "planner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if claimed, err := es.ClaimIntent(intentID, "worker-control-test"); err != nil || !claimed {
|
||||
t.Fatalf("initial claim: claimed=%v err=%v", claimed, err)
|
||||
}
|
||||
if err := es.SetIntentState(intentID, "paused"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
frontier, err := es.Frontier(10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, node := range frontier {
|
||||
if node.ID == intentID {
|
||||
t.Fatalf("paused intent %d must not enter frontier", intentID)
|
||||
}
|
||||
}
|
||||
if claimed, err := es.ClaimIntent(intentID, "worker-while-paused"); err != nil || claimed {
|
||||
t.Fatalf("paused intent claim: claimed=%v err=%v", claimed, err)
|
||||
}
|
||||
if err := es.SetIntentState(intentID, "open"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if claimed, err := es.ClaimIntent(intentID, "worker-after-resume"); err != nil || !claimed {
|
||||
t.Fatalf("resumed intent claim: claimed=%v err=%v", claimed, err)
|
||||
}
|
||||
if err := es.SetIntentState(intentID, "paused"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
directFact, err := es.AddNode("fact", map[string]any{"summary": "remove fact"}, 0, "confirmed", "worker", []int64{assetID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
directFinding, err := es.AddNode("finding", map[string]any{"summary": "remove finding"}, 0, "confirmed", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keptFact, err := es.AddNode("fact", map[string]any{"summary": "keep fact"}, 0, "confirmed", "other-worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := es.Link(intentID, RelYields, directFact); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := es.Link(intentID, RelYields, directFinding); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
findingRowID, err := es.AddStandaloneFinding(0, directFinding, "test", "cancelled finding", SeverityHigh, "summary", "evidence", "worker", []int64{assetID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
activityID, err := es.AppendActivity(Activity{NodeID: &intentID, Worker: "worker", Kind: "result", Summary: "remove activity"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keptActivityID, err := es.AppendActivity(Activity{NodeID: &otherIntent, Worker: "other-worker", Kind: "result", Summary: "keep activity"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cleanup, err := es.CancelIntent(intentID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cleanup.Intents != 1 || cleanup.Facts != 1 || cleanup.Findings != 1 || cleanup.Activities != 1 {
|
||||
t.Fatalf("unexpected cleanup counts: %+v", cleanup)
|
||||
}
|
||||
for _, nodeID := range []int64{intentID, directFact, directFinding} {
|
||||
node, err := es.GetNode(nodeID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if node != nil {
|
||||
t.Fatalf("node %d survived intent cancellation", nodeID)
|
||||
}
|
||||
}
|
||||
for _, nodeID := range []int64{otherIntent, keptFact} {
|
||||
node, err := es.GetNode(nodeID)
|
||||
if err != nil || node == nil {
|
||||
t.Fatalf("unrelated node %d removed: node=%v err=%v", nodeID, node, err)
|
||||
}
|
||||
}
|
||||
|
||||
assertCount := func(query string, want int, args ...any) {
|
||||
t.Helper()
|
||||
var got int
|
||||
if err := d.QueryRow(query, args...).Scan(&got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != want {
|
||||
t.Fatalf("query count=%d, want %d: %s", got, want, query)
|
||||
}
|
||||
}
|
||||
assertCount(`SELECT COUNT(*) FROM findings WHERE id=$1`, 0, findingRowID)
|
||||
assertCount(`SELECT COUNT(*) FROM activity WHERE id=$1`, 0, activityID)
|
||||
assertCount(`SELECT COUNT(*) FROM activity WHERE id=$1`, 1, keptActivityID)
|
||||
assertCount(`SELECT COUNT(*) FROM exploration_edges WHERE exploration_id=$1 AND (src_id=$2 OR dst_id=$2)`, 0, expID, intentID)
|
||||
assertCount(`SELECT COUNT(*) FROM exploration_anchors WHERE node_id=$1`, 0, directFact)
|
||||
assertCount(`SELECT COUNT(*) FROM assets WHERE id=$1`, 1, assetID)
|
||||
}
|
||||
+2
-1
@@ -9,7 +9,8 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// DBFinding is a row in the standalone findings table (persists across task deletion).
|
||||
// DBFinding is a row in the standalone findings table. It persists across task
|
||||
// deletion unless the caller explicitly requests related finding cleanup.
|
||||
type DBFinding struct {
|
||||
ID int64
|
||||
TaskID *int64
|
||||
|
||||
+79
-1
@@ -129,19 +129,40 @@ CREATE TABLE IF NOT EXISTS exploration_nodes (
|
||||
state TEXT NOT NULL DEFAULT 'open',
|
||||
origin TEXT,
|
||||
owner TEXT,
|
||||
blocked_reason TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
completed_at TIMESTAMPTZ,
|
||||
CONSTRAINT ck_node_kind CHECK (kind IN ('begin','goal','intent','fact','finding','hint')),
|
||||
CONSTRAINT ck_node_state CHECK (
|
||||
(kind='begin' AND state IN ('open')) OR
|
||||
(kind='intent' AND state IN ('open','running','done','blocked','exhausted','stopped')) OR
|
||||
(kind='intent' AND state IN ('open','running','paused','done','blocked','exhausted','stopped')) OR
|
||||
(kind='goal' AND state IN ('open','met','abandoned')) OR
|
||||
(kind='fact' AND state IN ('confirmed','dismissed','origin')) OR
|
||||
(kind='finding' AND state IN ('confirmed','dismissed')) OR
|
||||
(kind='hint' AND state IN ('active','consumed'))
|
||||
)
|
||||
);
|
||||
ALTER TABLE exploration_nodes ADD COLUMN IF NOT EXISTS blocked_reason TEXT;
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conrelid='exploration_nodes'::regclass
|
||||
AND conname='ck_node_state'
|
||||
AND pg_get_constraintdef(oid) NOT LIKE '%paused%'
|
||||
) THEN
|
||||
ALTER TABLE exploration_nodes DROP CONSTRAINT ck_node_state;
|
||||
ALTER TABLE exploration_nodes ADD CONSTRAINT ck_node_state CHECK (
|
||||
(kind='begin' AND state IN ('open')) OR
|
||||
(kind='intent' AND state IN ('open','running','paused','done','blocked','exhausted','stopped')) OR
|
||||
(kind='goal' AND state IN ('open','met','abandoned')) OR
|
||||
(kind='fact' AND state IN ('confirmed','dismissed','origin')) OR
|
||||
(kind='finding' AND state IN ('confirmed','dismissed')) OR
|
||||
(kind='hint' AND state IN ('active','consumed'))
|
||||
);
|
||||
END IF;
|
||||
END $$;
|
||||
CREATE INDEX IF NOT EXISTS idx_expnodes_part ON exploration_nodes(exploration_id, kind);
|
||||
CREATE INDEX IF NOT EXISTS idx_expnodes_frontier ON exploration_nodes(exploration_id, priority DESC)
|
||||
WHERE kind='intent' AND state='open';
|
||||
@@ -179,12 +200,14 @@ CREATE TABLE IF NOT EXISTS activity (
|
||||
is_error BOOLEAN NOT NULL DEFAULT false,
|
||||
summary TEXT,
|
||||
detail TEXT,
|
||||
metadata JSONB NOT NULL DEFAULT '{}',
|
||||
input_tokens INTEGER,
|
||||
output_tokens INTEGER,
|
||||
cache_read_tokens INTEGER,
|
||||
cache_write_tokens INTEGER,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
ALTER TABLE activity ADD COLUMN IF NOT EXISTS metadata JSONB NOT NULL DEFAULT '{}';
|
||||
CREATE INDEX IF NOT EXISTS idx_act_node ON activity(exploration_id, node_id, id);
|
||||
CREATE INDEX IF NOT EXISTS idx_act_since ON activity(exploration_id, id);
|
||||
-- Main/Plan history pages filter by worker (both carry NULL node_id, so idx_act_node
|
||||
@@ -256,6 +279,8 @@ CREATE TABLE IF NOT EXISTS tasks (
|
||||
paused BOOLEAN NOT NULL DEFAULT false,
|
||||
queued BOOLEAN NOT NULL DEFAULT false,
|
||||
llm_profile_id BIGINT REFERENCES llm_profiles(id) ON DELETE SET NULL,
|
||||
active_llm_profile_id BIGINT REFERENCES llm_profiles(id) ON DELETE SET NULL,
|
||||
llm_chain_revision BIGINT NOT NULL DEFAULT 0,
|
||||
company_id BIGINT REFERENCES companies(id) ON DELETE SET NULL,
|
||||
parent_ref TEXT,
|
||||
timeout_seconds INTEGER NOT NULL DEFAULT 0,
|
||||
@@ -276,6 +301,57 @@ CREATE TRIGGER trg_tasks_upd BEFORE UPDATE ON tasks
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS plan_heartbeat_seconds INTEGER NOT NULL DEFAULT 300;
|
||||
-- 并发上限挂起态;补旧库。true=因并发上限排队、等待空位自动启动。
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS queued BOOLEAN NOT NULL DEFAULT false;
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS active_llm_profile_id BIGINT REFERENCES llm_profiles(id) ON DELETE SET NULL;
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS llm_chain_revision BIGINT NOT NULL DEFAULT 0;
|
||||
|
||||
-- Direct, read-only task context inheritance. Relations are intentionally not
|
||||
-- recursive: a task sees only the source tasks explicitly chosen at creation.
|
||||
CREATE TABLE IF NOT EXISTS task_relations (
|
||||
task_id BIGINT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
||||
source_task_id BIGINT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (task_id, source_task_id),
|
||||
CONSTRAINT ck_task_relation_not_self CHECK (task_id <> source_task_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_task_relations_source ON task_relations(source_task_id);
|
||||
|
||||
-- Ordered task-level LLM failover chain. A quota-exhausted entry is skipped
|
||||
-- until the user saves/resets the chain, which clears all failure state.
|
||||
CREATE TABLE IF NOT EXISTS task_llm_profiles (
|
||||
task_id BIGINT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
||||
profile_id BIGINT NOT NULL REFERENCES llm_profiles(id) ON DELETE CASCADE,
|
||||
position INTEGER NOT NULL CHECK (position >= 0),
|
||||
status TEXT NOT NULL DEFAULT 'ready'
|
||||
CHECK (status IN ('ready','quota_exhausted')),
|
||||
last_error TEXT,
|
||||
exhausted_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (task_id, profile_id),
|
||||
UNIQUE (task_id, position)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_task_llm_profiles_order ON task_llm_profiles(task_id, position);
|
||||
CREATE INDEX IF NOT EXISTS idx_task_llm_profiles_profile ON task_llm_profiles(profile_id, task_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_tasks_llm_profile ON tasks(llm_profile_id) WHERE llm_profile_id IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_tasks_active_llm_profile ON tasks(active_llm_profile_id) WHERE active_llm_profile_id IS NOT NULL;
|
||||
DROP TRIGGER IF EXISTS trg_task_llm_profiles_upd ON task_llm_profiles;
|
||||
CREATE TRIGGER trg_task_llm_profiles_upd BEFORE UPDATE ON task_llm_profiles
|
||||
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
|
||||
|
||||
-- One-time-compatible backfill: old pinned tasks become one-entry chains. A user
|
||||
-- can still clear the chain later because the update path also clears the legacy
|
||||
-- llm_profile_id column, preventing this block from re-adding it on restart.
|
||||
INSERT INTO task_llm_profiles(task_id, profile_id, position)
|
||||
SELECT t.id, t.llm_profile_id, 0
|
||||
FROM tasks t
|
||||
WHERE t.llm_profile_id IS NOT NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM task_llm_profiles x WHERE x.task_id=t.id)
|
||||
ON CONFLICT DO NOTHING;
|
||||
UPDATE tasks t
|
||||
SET active_llm_profile_id = t.llm_profile_id
|
||||
WHERE t.active_llm_profile_id IS NULL
|
||||
AND t.llm_profile_id IS NOT NULL
|
||||
AND EXISTS (SELECT 1 FROM task_llm_profiles x WHERE x.task_id=t.id AND x.profile_id=t.llm_profile_id);
|
||||
|
||||
-- 任务测试范围(资产覆盖度的分母 + 授权边界)。
|
||||
-- 自动填(source='auto'):insertAssets 顶层按 worker 显式插入的资产类型加保守范围
|
||||
@@ -335,6 +411,7 @@ ALTER TABLE agents ADD COLUMN IF NOT EXISTS trigger_merge_mode TEXT NOT NUL
|
||||
ALTER TABLE agents ADD COLUMN IF NOT EXISTS trigger_max_parallel INTEGER NOT NULL DEFAULT 5;
|
||||
-- per-agent LLM 绑定(agent 级默认模型):列自初版即在上方 CREATE 中,此 ALTER 仅为极旧库兜底(幂等)。
|
||||
ALTER TABLE agents ADD COLUMN IF NOT EXISTS llm_profile_id BIGINT REFERENCES llm_profiles(id) ON DELETE SET NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_agents_llm_profile ON agents(llm_profile_id) WHERE llm_profile_id IS NOT NULL;
|
||||
DROP TRIGGER IF EXISTS trg_agents_upd ON agents;
|
||||
CREATE TRIGGER trg_agents_upd BEFORE UPDATE ON agents
|
||||
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
|
||||
@@ -454,6 +531,7 @@ CREATE TABLE IF NOT EXISTS conversations (
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_conversations_llm_profile ON conversations(llm_profile_id) WHERE llm_profile_id IS NOT NULL;
|
||||
DROP TRIGGER IF EXISTS trg_conversations_upd ON conversations;
|
||||
CREATE TRIGGER trg_conversations_upd BEFORE UPDATE ON conversations
|
||||
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// directTaskContextCTE is the current task plus exactly its explicitly related
|
||||
// source tasks. It is deliberately non-recursive.
|
||||
const directTaskContextCTE = `
|
||||
context_tasks AS (
|
||||
SELECT t.id AS task_id, t.exploration_id
|
||||
FROM tasks t
|
||||
WHERE t.id=$1 AND t.deleted_at IS NULL
|
||||
UNION ALL
|
||||
SELECT source.id, source.exploration_id
|
||||
FROM task_relations relation
|
||||
JOIN tasks source ON source.id=relation.source_task_id AND source.deleted_at IS NULL
|
||||
WHERE relation.task_id=$1
|
||||
)`
|
||||
|
||||
const contextCoverageCTE = directTaskContextCTE + `,
|
||||
target AS (
|
||||
SELECT DISTINCT a.id, a.type,
|
||||
COALESCE(a.url, a.domain, a.ip, a.app_name, a.root_domain, '') AS label
|
||||
FROM assets a
|
||||
JOIN task_scope ts ON (
|
||||
(ts.kind='company' AND a.company_id = ts.company_id)
|
||||
OR (ts.kind='root_domain' AND a.root_domain = ts.domain)
|
||||
OR (ts.kind='subdomain' AND a.domain = ts.domain)
|
||||
OR (ts.kind IN ('ip','cidr') AND a.ip IS NOT NULL AND a.ip !~ '[^0-9a-fA-F:.]' AND ts.net >>= a.ip::inet)
|
||||
)
|
||||
JOIN context_tasks ctx ON ctx.task_id=ts.task_id
|
||||
UNION
|
||||
SELECT a.id, a.type,
|
||||
COALESCE(a.url, a.domain, a.ip, a.app_name, a.root_domain, '') AS label
|
||||
FROM assets a
|
||||
JOIN exploration_anchors ea ON ea.asset_id=a.id
|
||||
JOIN exploration_nodes en ON en.id=ea.node_id
|
||||
JOIN context_tasks ctx ON ctx.exploration_id=en.exploration_id
|
||||
),
|
||||
tested AS (
|
||||
SELECT DISTINCT ea.asset_id
|
||||
FROM exploration_anchors ea
|
||||
JOIN exploration_nodes en ON en.id=ea.node_id AND en.kind='fact'
|
||||
JOIN context_tasks ctx ON ctx.exploration_id=en.exploration_id
|
||||
)`
|
||||
|
||||
// ListTaskScopeWithSources returns the current task's scope followed by the
|
||||
// scopes of its direct source tasks. TaskScope.TaskID preserves provenance.
|
||||
func (s *AssetStore) ListTaskScopeWithSources(taskID int64) ([]TaskScope, error) {
|
||||
rows, err := s.db.Query(`WITH `+directTaskContextCTE+`
|
||||
SELECT ts.id, ts.task_id, ts.kind, COALESCE(ts.company_id,0), COALESCE(ts.domain,''),
|
||||
COALESCE(ts.net::text,''), ts.source, COALESCE(ts.reason,'')
|
||||
FROM task_scope ts
|
||||
JOIN context_tasks ctx ON ctx.task_id=ts.task_id
|
||||
ORDER BY CASE WHEN ts.task_id=$1 THEN 0 ELSE 1 END, ts.id`, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []TaskScope{}
|
||||
for rows.Next() {
|
||||
var scope TaskScope
|
||||
var companyID int64
|
||||
if err := rows.Scan(&scope.ID, &scope.TaskID, &scope.Kind, &companyID, &scope.Domain, &scope.Net, &scope.Source, &scope.Reason); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if companyID > 0 {
|
||||
scope.CompanyID = &companyID
|
||||
}
|
||||
out = append(out, scope)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// TaskCoverageWithSources computes one coverage view over the union of the
|
||||
// current task and its direct sources: source scopes and anchored assets extend
|
||||
// the denominator, while fact anchors count as tested. No row is copied.
|
||||
func (s *AssetStore) TaskCoverageWithSources(taskID int64) (*Coverage, error) {
|
||||
cov := &Coverage{ByType: []CoverageByType{}}
|
||||
_ = s.db.QueryRow(`WITH `+directTaskContextCTE+`
|
||||
SELECT count(*) FROM task_scope ts JOIN context_tasks ctx ON ctx.task_id=ts.task_id`, taskID).Scan(&cov.ScopeRows)
|
||||
rows, err := s.db.Query(`WITH `+contextCoverageCTE+`
|
||||
SELECT target.type, count(*) AS total,
|
||||
count(*) FILTER (WHERE target.id IN (SELECT asset_id FROM tested)) AS tested
|
||||
FROM target GROUP BY target.type ORDER BY target.type`, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var byType CoverageByType
|
||||
if err := rows.Scan(&byType.Type, &byType.Total, &byType.Tested); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cov.ByType = append(cov.ByType, byType)
|
||||
cov.Denominator += byType.Total
|
||||
cov.Tested += byType.Tested
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cov.Denominator > 0 {
|
||||
pct := float64(cov.Tested) / float64(cov.Denominator)
|
||||
cov.Pct = &pct
|
||||
}
|
||||
return cov, nil
|
||||
}
|
||||
|
||||
// ListUntestedAssetsWithSources is the direct-source-aware backlog query used
|
||||
// by inherited tasks. Source fact anchors remove assets from the backlog.
|
||||
func (s *AssetStore) ListUntestedAssetsWithSources(taskID int64, typ string, limit, offset int) ([]CoverageAsset, int, error) {
|
||||
if limit <= 0 {
|
||||
limit = 10
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
typeFilter := ""
|
||||
args := []any{taskID}
|
||||
if typ != "" {
|
||||
typeFilter = " AND target.type = $2"
|
||||
args = append(args, typ)
|
||||
}
|
||||
var total int
|
||||
if err := s.db.QueryRow(`WITH `+contextCoverageCTE+`
|
||||
SELECT count(*) FROM target WHERE target.id NOT IN (SELECT asset_id FROM tested)`+typeFilter, args...).Scan(&total); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
pageArgs := append(append([]any{}, args...), limit, offset)
|
||||
limitPosition := strconv.Itoa(len(args) + 1)
|
||||
offsetPosition := strconv.Itoa(len(args) + 2)
|
||||
rows, err := s.db.Query(`WITH `+contextCoverageCTE+`
|
||||
SELECT target.id, target.type, target.label FROM target
|
||||
WHERE target.id NOT IN (SELECT asset_id FROM tested)`+typeFilter+`
|
||||
ORDER BY target.id LIMIT $`+limitPosition+` OFFSET $`+offsetPosition, pageArgs...)
|
||||
if err != nil {
|
||||
return nil, total, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []CoverageAsset{}
|
||||
for rows.Next() {
|
||||
var asset CoverageAsset
|
||||
if err := rows.Scan(&asset.ID, &asset.Type, &asset.Label); err != nil {
|
||||
return nil, total, err
|
||||
}
|
||||
out = append(out, asset)
|
||||
}
|
||||
return out, total, rows.Err()
|
||||
}
|
||||
|
||||
// HostsByTaskWithSources resolves exact HTTP host candidates from assets that
|
||||
// are attached to, anchored by, or in scope for the current task or a direct
|
||||
// source. Traffic remains global and is not copied. This read helper must not be
|
||||
// used for destructive task cleanup; HostsByTask intentionally retains that
|
||||
// narrower, task-owned behavior.
|
||||
func (s *AssetStore) HostsByTaskWithSources(taskID int64) ([]string, error) {
|
||||
rows, err := s.db.Query(`WITH `+directTaskContextCTE+`,
|
||||
context_assets AS (
|
||||
SELECT DISTINCT a.id
|
||||
FROM assets a
|
||||
WHERE EXISTS (SELECT 1 FROM context_tasks ctx WHERE ctx.task_id=ANY(a.task_ids))
|
||||
UNION
|
||||
SELECT ea.asset_id
|
||||
FROM exploration_anchors ea
|
||||
JOIN exploration_nodes en ON en.id=ea.node_id
|
||||
JOIN context_tasks ctx ON ctx.exploration_id=en.exploration_id
|
||||
UNION
|
||||
SELECT DISTINCT a.id
|
||||
FROM assets a
|
||||
JOIN task_scope ts ON (
|
||||
(ts.kind='company' AND a.company_id=ts.company_id)
|
||||
OR (ts.kind='root_domain' AND a.root_domain=ts.domain)
|
||||
OR (ts.kind='subdomain' AND a.domain=ts.domain)
|
||||
OR (ts.kind IN ('ip','cidr') AND a.ip IS NOT NULL AND a.ip !~ '[^0-9a-fA-F:.]' AND ts.net >>= a.ip::inet)
|
||||
)
|
||||
JOIN context_tasks ctx ON ctx.task_id=ts.task_id
|
||||
)
|
||||
SELECT COALESCE(a.domain,''), COALESCE(a.ip,''), COALESCE(a.url,'')
|
||||
FROM assets a JOIN context_assets ctx ON ctx.id=a.id`, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
hosts := map[string]struct{}{}
|
||||
add := func(host string) {
|
||||
host = strings.TrimSpace(strings.ToLower(host))
|
||||
if host != "" {
|
||||
hosts[host] = struct{}{}
|
||||
}
|
||||
}
|
||||
for rows.Next() {
|
||||
var domain, ip, rawURL string
|
||||
if err := rows.Scan(&domain, &ip, &rawURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
add(domain)
|
||||
add(ip)
|
||||
if parsed, err := url.Parse(rawURL); err == nil {
|
||||
add(parsed.Hostname())
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]string, 0, len(hosts))
|
||||
for host := range hosts {
|
||||
out = append(out, host)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const IntentBlockedLLMQuota = "llm_quota_exhausted"
|
||||
|
||||
// TaskLLMProfile is one ordered entry in a task's explicit failover chain.
|
||||
type TaskLLMProfile struct {
|
||||
ProfileID int64 `json:"profile_id"`
|
||||
Position int `json:"position"`
|
||||
Status string `json:"status"`
|
||||
LastError string `json:"last_error,omitempty"`
|
||||
ExhaustedAt *time.Time `json:"exhausted_at,omitempty"`
|
||||
}
|
||||
|
||||
// TaskSource identifies one directly related task and its exploration.
|
||||
type TaskSource struct {
|
||||
TaskID int64
|
||||
ExplorationID int64
|
||||
Description string
|
||||
Goal string
|
||||
Status string
|
||||
}
|
||||
|
||||
// TaskLLMTransition reports the shared task-level result of marking one profile
|
||||
// quota-exhausted. NextProfileID is nil when the explicit chain is exhausted.
|
||||
type TaskLLMTransition struct {
|
||||
PreviousProfileID int64
|
||||
NextProfileID *int64
|
||||
ChainExhausted bool
|
||||
Advanced bool
|
||||
// Stale means the chain was replaced after the failing call selected its
|
||||
// provider. The caller may retry a pre-stream request against the new chain,
|
||||
// but must not report or persist a transition for this result.
|
||||
Stale bool
|
||||
}
|
||||
|
||||
func (d *DB) hydrateTaskContext(t *Task) error {
|
||||
if t == nil {
|
||||
return nil
|
||||
}
|
||||
// A nil cursor on a non-empty chain is a persisted end-of-chain marker. Do not
|
||||
// repair it from an earlier ready entry: the user may have manually selected a
|
||||
// profile in the middle and legitimately exhausted every candidate after it.
|
||||
legacyProfileID, activeProfileID, revision, chain, err := d.taskLLMContext(t.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.LLMProfileID = legacyProfileID
|
||||
t.ActiveLLMProfileID = activeProfileID
|
||||
t.LLMChainRevision = revision
|
||||
sources, err := d.TaskSourceIDs(t.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.SourceTaskIDs = sources
|
||||
t.LLMProfileIDs = make([]int64, 0, len(chain))
|
||||
t.LLMFailoverState = "default"
|
||||
var latest *TaskLLMProfile
|
||||
activeReady := false
|
||||
for i := range chain {
|
||||
entry := chain[i]
|
||||
t.LLMProfileIDs = append(t.LLMProfileIDs, entry.ProfileID)
|
||||
if t.ActiveLLMProfileID != nil && entry.ProfileID == *t.ActiveLLMProfileID && entry.Status == "ready" {
|
||||
activeReady = true
|
||||
}
|
||||
if entry.ExhaustedAt != nil && (latest == nil || entry.ExhaustedAt.After(*latest.ExhaustedAt)) {
|
||||
copy := entry
|
||||
latest = ©
|
||||
}
|
||||
}
|
||||
if len(chain) > 0 {
|
||||
if activeReady {
|
||||
t.LLMFailoverState = "ready"
|
||||
} else {
|
||||
t.LLMFailoverState = "chain_exhausted"
|
||||
}
|
||||
}
|
||||
if latest != nil {
|
||||
t.LLMFailoverReason = latest.LastError
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// taskLLMContext reads the compatibility profile, current cursor, and ordered
|
||||
// chain in one statement. Runtime chain edits commit atomically, and one SQL
|
||||
// statement gives hydration one matching snapshot instead of a transient mix of
|
||||
// an old task cursor and a newly replaced chain (or vice versa).
|
||||
func (d *DB) taskLLMContext(taskID int64) (*int64, *int64, int64, []TaskLLMProfile, error) {
|
||||
rows, err := d.Query(`
|
||||
SELECT t.llm_profile_id, t.active_llm_profile_id, t.llm_chain_revision,
|
||||
p.profile_id, p.position, p.status, COALESCE(p.last_error,''), p.exhausted_at
|
||||
FROM tasks t
|
||||
LEFT JOIN task_llm_profiles p ON p.task_id=t.id
|
||||
WHERE t.id=$1
|
||||
ORDER BY p.position NULLS LAST`, taskID)
|
||||
if err != nil {
|
||||
return nil, nil, 0, nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var (
|
||||
legacyProfileID *int64
|
||||
activeProfileID *int64
|
||||
revision int64
|
||||
chain []TaskLLMProfile
|
||||
found bool
|
||||
)
|
||||
for rows.Next() {
|
||||
var legacy, active, profileID, position sql.NullInt64
|
||||
var rowRevision int64
|
||||
var status, lastError sql.NullString
|
||||
var exhaustedAt sql.NullTime
|
||||
if err := rows.Scan(&legacy, &active, &rowRevision, &profileID, &position, &status, &lastError, &exhaustedAt); err != nil {
|
||||
return nil, nil, 0, nil, err
|
||||
}
|
||||
if !found {
|
||||
found = true
|
||||
revision = rowRevision
|
||||
if legacy.Valid {
|
||||
id := legacy.Int64
|
||||
legacyProfileID = &id
|
||||
}
|
||||
if active.Valid {
|
||||
id := active.Int64
|
||||
activeProfileID = &id
|
||||
}
|
||||
}
|
||||
if !profileID.Valid {
|
||||
continue
|
||||
}
|
||||
entry := TaskLLMProfile{
|
||||
ProfileID: profileID.Int64,
|
||||
Position: int(position.Int64),
|
||||
Status: status.String,
|
||||
LastError: lastError.String,
|
||||
}
|
||||
if exhaustedAt.Valid {
|
||||
ts := exhaustedAt.Time
|
||||
entry.ExhaustedAt = &ts
|
||||
}
|
||||
chain = append(chain, entry)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, 0, nil, err
|
||||
}
|
||||
if !found {
|
||||
return nil, nil, 0, nil, sql.ErrNoRows
|
||||
}
|
||||
return legacyProfileID, activeProfileID, revision, chain, nil
|
||||
}
|
||||
|
||||
func (d *DB) TaskSourceIDs(taskID int64) ([]int64, error) {
|
||||
rows, err := d.Query(`SELECT source_task_id FROM task_relations WHERE task_id=$1 ORDER BY created_at, source_task_id`, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []int64
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, id)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) TaskSources(taskID int64) ([]TaskSource, error) {
|
||||
rows, err := d.Query(`
|
||||
SELECT t.id, t.exploration_id, t.description, t.goal, t.status
|
||||
FROM task_relations r
|
||||
JOIN tasks t ON t.id=r.source_task_id AND t.deleted_at IS NULL
|
||||
WHERE r.task_id=$1
|
||||
ORDER BY r.created_at, r.source_task_id`, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []TaskSource
|
||||
for rows.Next() {
|
||||
var source TaskSource
|
||||
if err := rows.Scan(&source.TaskID, &source.ExplorationID, &source.Description, &source.Goal, &source.Status); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, source)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) TaskLLMProfiles(taskID int64) ([]TaskLLMProfile, error) {
|
||||
rows, err := d.Query(`SELECT profile_id, position, status, COALESCE(last_error,''), exhausted_at
|
||||
FROM task_llm_profiles WHERE task_id=$1 ORDER BY position`, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []TaskLLMProfile
|
||||
for rows.Next() {
|
||||
var entry TaskLLMProfile
|
||||
if err := rows.Scan(&entry.ProfileID, &entry.Position, &entry.Status, &entry.LastError, &entry.ExhaustedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, entry)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ReplaceTaskLLMProfiles atomically replaces and resets the explicit task chain.
|
||||
// activeProfileID=0 selects the first entry. An empty list restores the existing
|
||||
// agent-binding/global fallback behavior.
|
||||
func (d *DB) ReplaceTaskLLMProfiles(taskID int64, profileIDs []int64, activeProfileID int64) error {
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
// Keep the task -> profile lock order shared by all task LLM mutations and
|
||||
// DeleteProfile. Inserts below may take KEY SHARE locks on llm_profiles for
|
||||
// their foreign keys, so the task row must be locked before any of them.
|
||||
var status string
|
||||
if err := tx.QueryRow(`SELECT status FROM tasks WHERE id=$1 AND deleted_at IS NULL FOR UPDATE`, taskID).Scan(&status); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return fmt.Errorf("task %d not found", taskID)
|
||||
}
|
||||
return err
|
||||
}
|
||||
if IsTerminal(status) {
|
||||
return fmt.Errorf("terminal task cannot change LLM profiles")
|
||||
}
|
||||
if _, err := tx.Exec(`DELETE FROM task_llm_profiles WHERE task_id=$1`, taskID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := insertTaskLLMProfiles(tx, taskID, profileIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(profileIDs) == 0 {
|
||||
activeProfileID = 0
|
||||
} else if activeProfileID == 0 {
|
||||
activeProfileID = profileIDs[0]
|
||||
}
|
||||
if activeProfileID > 0 {
|
||||
found := false
|
||||
for _, id := range profileIDs {
|
||||
found = found || id == activeProfileID
|
||||
}
|
||||
if !found {
|
||||
return fmt.Errorf("active LLM profile %d is not in the task chain", activeProfileID)
|
||||
}
|
||||
}
|
||||
var active any
|
||||
if activeProfileID > 0 {
|
||||
active = activeProfileID
|
||||
}
|
||||
if _, err := tx.Exec(`UPDATE tasks
|
||||
SET active_llm_profile_id=$2, llm_profile_id=$2, llm_chain_revision=llm_chain_revision+1
|
||||
WHERE id=$1`, taskID, active); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// MarkTaskLLMProfileQuotaExhausted advances the shared task cursor once. A late
|
||||
// in-flight error from an older profile records that entry as exhausted but does
|
||||
// not advance past the profile another call already selected.
|
||||
func (d *DB) MarkTaskLLMProfileQuotaExhausted(taskID, profileID int64, reason string) (TaskLLMTransition, error) {
|
||||
return d.markTaskLLMProfileQuotaExhausted(taskID, profileID, 0, false, reason)
|
||||
}
|
||||
|
||||
// MarkTaskLLMProfileQuotaExhaustedAtRevision applies a provider failure only
|
||||
// when it belongs to the chain snapshot used to start that call.
|
||||
func (d *DB) MarkTaskLLMProfileQuotaExhaustedAtRevision(taskID, profileID, revision int64, reason string) (TaskLLMTransition, error) {
|
||||
return d.markTaskLLMProfileQuotaExhausted(taskID, profileID, revision, true, reason)
|
||||
}
|
||||
|
||||
func (d *DB) markTaskLLMProfileQuotaExhausted(taskID, profileID, revision int64, checkRevision bool, reason string) (TaskLLMTransition, error) {
|
||||
var out TaskLLMTransition
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var (
|
||||
active sql.NullInt64
|
||||
currentRevision int64
|
||||
)
|
||||
if err := tx.QueryRow(`SELECT active_llm_profile_id, llm_chain_revision FROM tasks WHERE id=$1 FOR UPDATE`, taskID).Scan(&active, ¤tRevision); err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.PreviousProfileID = profileID
|
||||
if checkRevision && revision != currentRevision {
|
||||
out.Stale = true
|
||||
return out, tx.Commit()
|
||||
}
|
||||
var (
|
||||
position int
|
||||
entryStatus string
|
||||
)
|
||||
if err := tx.QueryRow(`SELECT position, status FROM task_llm_profiles WHERE task_id=$1 AND profile_id=$2`, taskID, profileID).
|
||||
Scan(&position, &entryStatus); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
// The chain was edited while this request was in flight. Its provider
|
||||
// error remains valid for the caller, but it must not mutate the new chain.
|
||||
return out, tx.Commit()
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
// Once the cursor reached the end, late failures must be idempotent. This also
|
||||
// prevents an older in-flight request from reviving a ready entry before a
|
||||
// manually selected starting position.
|
||||
if !active.Valid {
|
||||
out.ChainExhausted = true
|
||||
return out, tx.Commit()
|
||||
}
|
||||
reason = truncateUTF8(strings.TrimSpace(reason), 1000)
|
||||
if entryStatus != "quota_exhausted" {
|
||||
if _, err := tx.Exec(`UPDATE task_llm_profiles
|
||||
SET status='quota_exhausted', last_error=$3, exhausted_at=now()
|
||||
WHERE task_id=$1 AND profile_id=$2`, taskID, profileID, reason); err != nil {
|
||||
return out, err
|
||||
}
|
||||
}
|
||||
if active.Valid && active.Int64 != profileID {
|
||||
next := active.Int64
|
||||
out.NextProfileID = &next
|
||||
return out, tx.Commit()
|
||||
}
|
||||
var next int64
|
||||
err = tx.QueryRow(`SELECT profile_id FROM task_llm_profiles
|
||||
WHERE task_id=$1 AND position>$2 AND status='ready'
|
||||
ORDER BY position LIMIT 1`, taskID, position).Scan(&next)
|
||||
switch err {
|
||||
case nil:
|
||||
out.Advanced = true
|
||||
out.NextProfileID = &next
|
||||
if _, err := tx.Exec(`UPDATE tasks SET active_llm_profile_id=$2, llm_profile_id=$2 WHERE id=$1`, taskID, next); err != nil {
|
||||
return out, err
|
||||
}
|
||||
case sql.ErrNoRows:
|
||||
out.Advanced = true
|
||||
out.ChainExhausted = true
|
||||
if _, err := tx.Exec(`UPDATE tasks SET active_llm_profile_id=NULL, llm_profile_id=NULL WHERE id=$1`, taskID); err != nil {
|
||||
return out, err
|
||||
}
|
||||
default:
|
||||
return out, err
|
||||
}
|
||||
return out, tx.Commit()
|
||||
}
|
||||
|
||||
func truncateUTF8(value string, maxBytes int) string {
|
||||
value = strings.ToValidUTF8(value, "\uFFFD")
|
||||
if maxBytes <= 0 {
|
||||
return ""
|
||||
}
|
||||
if len(value) <= maxBytes {
|
||||
return value
|
||||
}
|
||||
end := maxBytes
|
||||
for end > 0 && !utf8.ValidString(value[:end]) {
|
||||
end--
|
||||
}
|
||||
return value[:end]
|
||||
}
|
||||
|
||||
func (s *ExplorationStore) SetIntentBlockedReason(id int64, reason string) error {
|
||||
_, err := s.db.Exec(`UPDATE exploration_nodes
|
||||
SET state='blocked', blocked_reason=NULLIF($1,''), completed_at=now()
|
||||
WHERE id=$2 AND exploration_id=$3 AND kind='intent'`, reason, id, s.expID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *ExplorationStore) ReopenIntentsByBlockedReason(reason string) (int64, error) {
|
||||
res, err := s.db.Exec(`UPDATE exploration_nodes
|
||||
SET state='open', blocked_reason=NULL, completed_at=NULL
|
||||
WHERE exploration_id=$1 AND kind='intent' AND state='blocked' AND blocked_reason=$2`, s.expID, reason)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
return n, nil
|
||||
}
|
||||
@@ -0,0 +1,527 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTaskLLMProfileMutationsLockTaskBeforeProfile(t *testing.T) {
|
||||
dsn := testDSN(t)
|
||||
d, err := Open(dsn)
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
suffix := time.Now().UnixNano()
|
||||
first, err := d.SaveProfile(&LLMProfile{
|
||||
Name: fmt.Sprintf("lock-order-first-%d", suffix), Format: "openai", Model: "first", APIKey: "test-key",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := d.SaveProfile(&LLMProfile{
|
||||
Name: fmt.Sprintf("lock-order-second-%d", suffix), Format: "openai", Model: "second", APIKey: "test-key",
|
||||
})
|
||||
if err != nil {
|
||||
_ = d.DeleteProfile(first)
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := d.CreateTaskWithOptions("LLM lock order", "verify concurrent mutation locks", TaskCreateOptions{
|
||||
LLMProfileIDs: []int64{first, second},
|
||||
})
|
||||
if err != nil {
|
||||
_ = d.DeleteProfile(first)
|
||||
_ = d.DeleteProfile(second)
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = d.DeleteTask(task.ID)
|
||||
_ = d.DeleteProfile(first)
|
||||
_ = d.DeleteProfile(second)
|
||||
})
|
||||
|
||||
replaceDB, replacePID := openSingleConnectionTestDB(t, dsn)
|
||||
replaceBlocker, err := d.Begin()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer replaceBlocker.Rollback()
|
||||
if _, err := replaceBlocker.Exec(`SELECT id FROM tasks WHERE id=$1 FOR UPDATE`, task.ID); err != nil {
|
||||
replaceBlocker.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
replaceDone := make(chan error, 1)
|
||||
go func() {
|
||||
replaceDone <- replaceDB.ReplaceTaskLLMProfiles(task.ID, []int64{second, first}, second)
|
||||
}()
|
||||
if err := waitForBackendBlock(d, replacePID, replaceDone); err != nil {
|
||||
replaceBlocker.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertProfilesUnlocked(t, d, first, second)
|
||||
if err := replaceBlocker.Rollback(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := waitForMutationResult(replaceDone); err != nil {
|
||||
t.Fatalf("replace chain: %v", err)
|
||||
}
|
||||
|
||||
deleteDB, deletePID := openSingleConnectionTestDB(t, dsn)
|
||||
deleteBlocker, err := d.Begin()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer deleteBlocker.Rollback()
|
||||
if _, err := deleteBlocker.Exec(`SELECT id FROM tasks WHERE id=$1 FOR UPDATE`, task.ID); err != nil {
|
||||
deleteBlocker.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
deleteDone := make(chan error, 1)
|
||||
go func() {
|
||||
deleteDone <- deleteDB.DeleteProfile(second)
|
||||
}()
|
||||
if err := waitForBackendBlock(d, deletePID, deleteDone); err != nil {
|
||||
deleteBlocker.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertProfilesUnlocked(t, d, second)
|
||||
if err := deleteBlocker.Rollback(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := waitForMutationResult(deleteDone); err != nil {
|
||||
t.Fatalf("delete profile: %v", err)
|
||||
}
|
||||
|
||||
got, err := d.GetTask(task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.ActiveLLMProfileID == nil || *got.ActiveLLMProfileID != first {
|
||||
t.Fatalf("deleting the active profile did not select its successor: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteProfileLocksNonTaskReferencesBeforeProfile(t *testing.T) {
|
||||
dsn := testDSN(t)
|
||||
|
||||
t.Run("agent", func(t *testing.T) {
|
||||
d, err := Open(dsn)
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
suffix := time.Now().UnixNano()
|
||||
profileID, err := d.SaveProfile(&LLMProfile{
|
||||
Name: fmt.Sprintf("agent-lock-profile-%d", suffix), Format: "openai", Model: "agent-lock", APIKey: "test-key",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
agent, err := d.CreateAgent(fmt.Sprintf("lock_agent_%d", suffix), "lock agent", "")
|
||||
if err != nil {
|
||||
_ = d.DeleteProfile(profileID)
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := d.SetAgentLLMProfile(agent.Key, &profileID); err != nil {
|
||||
_ = d.DeleteAgent(agent.Key)
|
||||
_ = d.DeleteProfile(profileID)
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = d.DeleteAgent(agent.Key)
|
||||
_ = d.DeleteProfile(profileID)
|
||||
})
|
||||
|
||||
blocker, err := d.Begin()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer blocker.Rollback()
|
||||
if _, err := blocker.Exec(`SELECT id FROM agents WHERE id=$1 FOR UPDATE`, agent.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deleteDB, deletePID := openSingleConnectionTestDB(t, dsn)
|
||||
deleteDone := make(chan error, 1)
|
||||
go func() { deleteDone <- deleteDB.DeleteProfile(profileID) }()
|
||||
if err := waitForBackendBlock(d, deletePID, deleteDone); err != nil {
|
||||
blocker.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertProfilesUnlocked(t, d, profileID)
|
||||
if err := blocker.Rollback(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := waitForMutationResult(deleteDone); err != nil {
|
||||
t.Fatalf("delete agent profile: %v", err)
|
||||
}
|
||||
got, err := d.GetAgentByKey(agent.Key)
|
||||
if err != nil || got == nil || got.LLMProfileID != nil {
|
||||
t.Fatalf("agent binding was not cleared: agent=%+v err=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("conversation", func(t *testing.T) {
|
||||
d, err := Open(dsn)
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
suffix := time.Now().UnixNano()
|
||||
profileID, err := d.SaveProfile(&LLMProfile{
|
||||
Name: fmt.Sprintf("conversation-lock-profile-%d", suffix), Format: "openai", Model: "conversation-lock", APIKey: "test-key",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conversation, err := d.CreateConversation("planner", "lock conversation", &profileID)
|
||||
if err != nil {
|
||||
_ = d.DeleteProfile(profileID)
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = d.DeleteConversation(conversation.ID)
|
||||
_ = d.DeleteProfile(profileID)
|
||||
})
|
||||
|
||||
blocker, err := d.Begin()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer blocker.Rollback()
|
||||
if _, err := blocker.Exec(`SELECT id FROM conversations WHERE id=$1 FOR UPDATE`, conversation.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deleteDB, deletePID := openSingleConnectionTestDB(t, dsn)
|
||||
deleteDone := make(chan error, 1)
|
||||
go func() { deleteDone <- deleteDB.DeleteProfile(profileID) }()
|
||||
if err := waitForBackendBlock(d, deletePID, deleteDone); err != nil {
|
||||
blocker.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertProfilesUnlocked(t, d, profileID)
|
||||
if err := blocker.Rollback(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := waitForMutationResult(deleteDone); err != nil {
|
||||
t.Fatalf("delete conversation profile: %v", err)
|
||||
}
|
||||
got, err := d.GetConversation(conversation.ID)
|
||||
if err != nil || got == nil || got.LLMProfileID != nil {
|
||||
t.Fatalf("conversation binding was not cleared: conversation=%+v err=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNonTaskProfileMutationsLockReferenceBeforeProfile(t *testing.T) {
|
||||
dsn := testDSN(t)
|
||||
|
||||
t.Run("agent", func(t *testing.T) {
|
||||
d, err := Open(dsn)
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
suffix := time.Now().UnixNano()
|
||||
profileID, err := d.SaveProfile(&LLMProfile{
|
||||
Name: fmt.Sprintf("agent-write-lock-profile-%d", suffix), Format: "openai", Model: "agent-write-lock", APIKey: "test-key",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
agent, err := d.CreateAgent(fmt.Sprintf("write_lock_agent_%d", suffix), "write lock agent", "")
|
||||
if err != nil {
|
||||
_ = d.DeleteProfile(profileID)
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = d.DeleteAgent(agent.Key)
|
||||
_ = d.DeleteProfile(profileID)
|
||||
})
|
||||
|
||||
blocker, err := d.Begin()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer blocker.Rollback()
|
||||
if _, err := blocker.Exec(`SELECT id FROM agents WHERE id=$1 FOR UPDATE`, agent.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mutationDB, mutationPID := openSingleConnectionTestDB(t, dsn)
|
||||
mutationDone := make(chan error, 1)
|
||||
go func() { mutationDone <- mutationDB.SetAgentLLMProfile(agent.Key, &profileID) }()
|
||||
if err := waitForBackendBlock(d, mutationPID, mutationDone); err != nil {
|
||||
blocker.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertProfilesUnlocked(t, d, profileID)
|
||||
if err := blocker.Rollback(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := waitForMutationResult(mutationDone); err != nil {
|
||||
t.Fatalf("bind agent profile: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("conversation", func(t *testing.T) {
|
||||
d, err := Open(dsn)
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
suffix := time.Now().UnixNano()
|
||||
profileID, err := d.SaveProfile(&LLMProfile{
|
||||
Name: fmt.Sprintf("conversation-write-lock-profile-%d", suffix), Format: "openai", Model: "conversation-write-lock", APIKey: "test-key",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conversation, err := d.CreateConversation("planner", "write lock conversation", nil)
|
||||
if err != nil {
|
||||
_ = d.DeleteProfile(profileID)
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = d.DeleteConversation(conversation.ID)
|
||||
_ = d.DeleteProfile(profileID)
|
||||
})
|
||||
|
||||
blocker, err := d.Begin()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer blocker.Rollback()
|
||||
if _, err := blocker.Exec(`SELECT id FROM conversations WHERE id=$1 FOR UPDATE`, conversation.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mutationDB, mutationPID := openSingleConnectionTestDB(t, dsn)
|
||||
mutationDone := make(chan error, 1)
|
||||
go func() { mutationDone <- mutationDB.UpdateConversationProfile(conversation.ID, &profileID) }()
|
||||
if err := waitForBackendBlock(d, mutationPID, mutationDone); err != nil {
|
||||
blocker.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertProfilesUnlocked(t, d, profileID)
|
||||
if err := blocker.Rollback(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := waitForMutationResult(mutationDone); err != nil {
|
||||
t.Fatalf("bind conversation profile: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCreateConversationAndDeleteProfileDoNotDeadlock(t *testing.T) {
|
||||
dsn := testDSN(t)
|
||||
d, err := Open(dsn)
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
suffix := time.Now().UnixNano()
|
||||
profileID, err := d.SaveProfile(&LLMProfile{
|
||||
Name: fmt.Sprintf("conversation-create-race-profile-%d", suffix), Format: "openai", Model: "conversation-create-race", APIKey: "test-key",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
title := fmt.Sprintf("conversation create race %d", suffix)
|
||||
t.Cleanup(func() {
|
||||
_, _ = d.Exec(`DELETE FROM conversations WHERE title=$1`, title)
|
||||
_ = d.DeleteProfile(profileID)
|
||||
})
|
||||
|
||||
profileBlocker, err := d.Begin()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer profileBlocker.Rollback()
|
||||
if _, err := profileBlocker.Exec(`SELECT id FROM llm_profiles WHERE id=$1 FOR UPDATE`, profileID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
createDB, createPID := openSingleConnectionTestDB(t, dsn)
|
||||
type createResult struct {
|
||||
conversation *Conversation
|
||||
err error
|
||||
}
|
||||
createDone := make(chan createResult, 1)
|
||||
createStatus := make(chan error, 1)
|
||||
go func() {
|
||||
conversation, err := createDB.CreateConversation("planner", title, &profileID)
|
||||
createDone <- createResult{conversation: conversation, err: err}
|
||||
createStatus <- err
|
||||
}()
|
||||
if err := waitForBackendBlock(d, createPID, createStatus); err != nil {
|
||||
profileBlocker.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
deleteDB, deletePID := openSingleConnectionTestDB(t, dsn)
|
||||
deleteDone := make(chan error, 1)
|
||||
go func() { deleteDone <- deleteDB.DeleteProfile(profileID) }()
|
||||
if err := waitForBackendBlock(d, deletePID, deleteDone); err != nil {
|
||||
profileBlocker.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := profileBlocker.Rollback(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var created createResult
|
||||
select {
|
||||
case created = <-createDone:
|
||||
case <-time.After(12 * time.Second):
|
||||
t.Fatal("timed out waiting for conversation creation")
|
||||
}
|
||||
if err := waitForMutationResult(deleteDone); err != nil {
|
||||
t.Fatalf("delete profile during conversation creation: %v", err)
|
||||
}
|
||||
var persisted int
|
||||
if err := d.QueryRow(`SELECT count(*) FROM conversations WHERE title=$1`, title).Scan(&persisted); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if created.err == nil {
|
||||
if created.conversation == nil || persisted != 1 {
|
||||
t.Fatalf("successful creation was not committed atomically: conversation=%+v count=%d", created.conversation, persisted)
|
||||
}
|
||||
} else if persisted != 0 {
|
||||
t.Fatalf("failed creation left a partial conversation row: err=%v count=%d", created.err, persisted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteProfileRetriesReferenceCommittedAfterInitialScan(t *testing.T) {
|
||||
dsn := testDSN(t)
|
||||
d, err := Open(dsn)
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
suffix := time.Now().UnixNano()
|
||||
profileID, err := d.SaveProfile(&LLMProfile{
|
||||
Name: fmt.Sprintf("late-reference-profile-%d", suffix), Format: "openai", Model: "late-reference", APIKey: "test-key",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := d.CreateTask("late profile reference", "exercise delete retry", nil, 0, 0)
|
||||
if err != nil {
|
||||
_ = d.DeleteProfile(profileID)
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = d.DeleteTask(task.ID)
|
||||
_ = d.DeleteProfile(profileID)
|
||||
})
|
||||
|
||||
// Keep the new reference uncommitted while deletion takes its initial
|
||||
// READ COMMITTED snapshot. The task is therefore absent from the first lock
|
||||
// set, while its FK KEY SHARE lock makes deletion wait at the profile row.
|
||||
referenceTx, err := d.Begin()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer referenceTx.Rollback()
|
||||
if _, err := referenceTx.Exec(`UPDATE tasks
|
||||
SET llm_profile_id=$2, active_llm_profile_id=$2
|
||||
WHERE id=$1`, task.ID, profileID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := referenceTx.Exec(`INSERT INTO task_llm_profiles(task_id, profile_id, position)
|
||||
VALUES ($1,$2,0)`, task.ID, profileID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
deleteDB, deletePID := openSingleConnectionTestDB(t, dsn)
|
||||
deleteDone := make(chan error, 1)
|
||||
go func() { deleteDone <- deleteDB.DeleteProfile(profileID) }()
|
||||
if err := waitForBackendBlock(d, deletePID, deleteDone); err != nil {
|
||||
referenceTx.Rollback()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := referenceTx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := waitForMutationResult(deleteDone); err != nil {
|
||||
t.Fatalf("delete profile after late reference: %v", err)
|
||||
}
|
||||
|
||||
got, err := d.GetTask(task.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.ActiveLLMProfileID != nil || len(got.LLMProfileIDs) != 0 || got.LLMChainRevision != 1 {
|
||||
t.Fatalf("late task reference was not handled by a locked retry: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func openSingleConnectionTestDB(t *testing.T, dsn string) (*DB, int) {
|
||||
t.Helper()
|
||||
sqlDB, err := sql.Open("pgx", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
sqlDB.SetMaxIdleConns(1)
|
||||
t.Cleanup(func() { _ = sqlDB.Close() })
|
||||
if _, err := sqlDB.Exec(`SET statement_timeout='10s'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var pid int
|
||||
if err := sqlDB.QueryRow(`SELECT pg_backend_pid()`).Scan(&pid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &DB{sqlDB}, pid
|
||||
}
|
||||
|
||||
func waitForBackendBlock(observer *DB, pid int, done <-chan error) error {
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
select {
|
||||
case err := <-done:
|
||||
return fmt.Errorf("mutation returned before reaching the expected reference-row lock: %v", err)
|
||||
default:
|
||||
}
|
||||
var blockers int
|
||||
if err := observer.QueryRow(`SELECT cardinality(pg_blocking_pids($1))`, pid).Scan(&blockers); err != nil {
|
||||
return err
|
||||
}
|
||||
if blockers > 0 {
|
||||
return nil
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("backend %d did not block within 5s", pid)
|
||||
}
|
||||
|
||||
func assertProfilesUnlocked(t *testing.T, d *DB, profileIDs ...int64) {
|
||||
t.Helper()
|
||||
probe, err := d.Begin()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer probe.Rollback()
|
||||
for _, profileID := range profileIDs {
|
||||
var lockedID int64
|
||||
if err := probe.QueryRow(`SELECT id FROM llm_profiles WHERE id=$1 FOR UPDATE NOWAIT`, profileID).Scan(&lockedID); err != nil {
|
||||
t.Fatalf("profile %d was locked before the task row: %v", profileID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func waitForMutationResult(done <-chan error) error {
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-time.After(12 * time.Second):
|
||||
return fmt.Errorf("timed out waiting for task LLM mutation")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func TestTruncateUTF8PreservesValidEncoding(t *testing.T) {
|
||||
t.Parallel()
|
||||
input := strings.Repeat("额度不足", 400)
|
||||
got := truncateUTF8(input, 1000)
|
||||
if len(got) > 1000 {
|
||||
t.Fatalf("truncated value has %d bytes, want at most 1000", len(got))
|
||||
}
|
||||
if !utf8.ValidString(got) {
|
||||
t.Fatalf("truncated value is not valid UTF-8: %q", got[len(got)-8:])
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncateUTF8RepairsInvalidInput(t *testing.T) {
|
||||
t.Parallel()
|
||||
got := truncateUTF8("bad\xffvalue", 1000)
|
||||
if !utf8.ValidString(got) {
|
||||
t.Fatalf("repaired value is not valid UTF-8: %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
func TestDeleteTaskTrafficHostsUseOneLockedTransaction(t *testing.T) {
|
||||
dsn := testDSN(t)
|
||||
d, err := Open(dsn)
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
t.Run("sharing committed before deletion lock is observed", func(t *testing.T) {
|
||||
first, second, host, rootAssetID := createTaskDeleteRaceFixture(t, d)
|
||||
serviceURL := "https://" + host + "/concurrent-owner"
|
||||
t.Cleanup(func() {
|
||||
_ = d.DeleteTask(first.ID)
|
||||
_ = d.DeleteTask(second.ID)
|
||||
_, _ = d.Exec(`DELETE FROM assets WHERE id=$1 OR url=$2`, rootAssetID, serviceURL)
|
||||
})
|
||||
|
||||
writer, _ := openTaskDeleteTestDB(t, dsn)
|
||||
writerTx, err := writer.Begin()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer writerTx.Rollback()
|
||||
if _, err := writerTx.Exec(`
|
||||
INSERT INTO assets(type, url, service_type, domain, task_ids)
|
||||
VALUES ('service', $1, 'http', $2, ARRAY[$3]::bigint[])`, serviceURL, host, second.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
deleter, deleterPID := openTaskDeleteTestDB(t, dsn)
|
||||
var preparedHosts []string
|
||||
deleteDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, deleteErr := deleter.DeleteTaskCascadePrepared(first.ID, true, false, false, func(p TaskDeletePreparation) error {
|
||||
preparedHosts = append([]string(nil), p.TrafficHosts...)
|
||||
return nil
|
||||
})
|
||||
deleteDone <- deleteErr
|
||||
}()
|
||||
|
||||
if err := waitForTaskDeleteBlock(d, deleterPID, deleteDone); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := writerTx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := waitForTaskDeleteResult(deleteDone); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if containsDeleteHost(preparedHosts, host) {
|
||||
t.Fatalf("newly shared host %q was selected for traffic deletion: %v", host, preparedHosts)
|
||||
}
|
||||
var remaining int
|
||||
if err := d.QueryRow(`SELECT count(*) FROM assets WHERE url=$1 AND $2=ANY(task_ids)`, serviceURL, second.ID).Scan(&remaining); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if remaining != 1 {
|
||||
t.Fatalf("concurrent owner's asset was not preserved: count=%d", remaining)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("sharing cannot enter between host resolution and commit", func(t *testing.T) {
|
||||
first, second, host, rootAssetID := createTaskDeleteRaceFixture(t, d)
|
||||
serviceURL := "https://" + host + "/late-owner"
|
||||
t.Cleanup(func() {
|
||||
_ = d.DeleteTask(first.ID)
|
||||
_ = d.DeleteTask(second.ID)
|
||||
_, _ = d.Exec(`DELETE FROM assets WHERE id=$1 OR url=$2`, rootAssetID, serviceURL)
|
||||
})
|
||||
|
||||
deleter, _ := openTaskDeleteTestDB(t, dsn)
|
||||
prepared := make(chan TaskDeletePreparation, 1)
|
||||
releasePrepare := make(chan struct{})
|
||||
deleteDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, deleteErr := deleter.DeleteTaskCascadePrepared(first.ID, true, false, false, func(p TaskDeletePreparation) error {
|
||||
prepared <- p
|
||||
<-releasePrepare
|
||||
return nil
|
||||
})
|
||||
deleteDone <- deleteErr
|
||||
}()
|
||||
|
||||
var plan TaskDeletePreparation
|
||||
select {
|
||||
case plan = <-prepared:
|
||||
case err := <-deleteDone:
|
||||
close(releasePrepare)
|
||||
t.Fatalf("delete returned before preparation: %v", err)
|
||||
case <-time.After(5 * time.Second):
|
||||
close(releasePrepare)
|
||||
t.Fatal("timed out waiting for task delete preparation")
|
||||
}
|
||||
if !containsDeleteHost(plan.TrafficHosts, host) {
|
||||
close(releasePrepare)
|
||||
t.Fatalf("exclusive host %q missing from preparation: %v", host, plan.TrafficHosts)
|
||||
}
|
||||
|
||||
writer, writerPID := openTaskDeleteTestDB(t, dsn)
|
||||
writerDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, writeErr := writer.Exec(`
|
||||
INSERT INTO assets(type, url, service_type, domain, task_ids)
|
||||
VALUES ('service', $1, 'http', $2, ARRAY[$3]::bigint[])`, serviceURL, host, second.ID)
|
||||
writerDone <- writeErr
|
||||
}()
|
||||
if err := waitForTaskDeleteBlock(d, writerPID, writerDone); err != nil {
|
||||
close(releasePrepare)
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
close(releasePrepare)
|
||||
if err := waitForTaskDeleteResult(deleteDone); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := waitForTaskDeleteResult(writerDone); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func createTaskDeleteRaceFixture(t *testing.T, d *DB) (first, second *Task, host string, rootAssetID int64) {
|
||||
t.Helper()
|
||||
var err error
|
||||
first, err = d.CreateTask("delete race owner", "delete safely", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err = d.CreateTask("delete race sharer", "preserve shared host", nil, 0, 0)
|
||||
if err != nil {
|
||||
_ = d.DeleteTask(first.ID)
|
||||
t.Fatal(err)
|
||||
}
|
||||
host = fmt.Sprintf("task-delete-race-%d.example.test", first.ID)
|
||||
rootAssetID, err = d.Assets().UpsertRootDomain(UpsertRootDomainReq{Domain: host, TaskID: first.ID})
|
||||
if err != nil {
|
||||
_ = d.DeleteTask(first.ID)
|
||||
_ = d.DeleteTask(second.ID)
|
||||
t.Fatal(err)
|
||||
}
|
||||
return first, second, host, rootAssetID
|
||||
}
|
||||
|
||||
func openTaskDeleteTestDB(t *testing.T, dsn string) (*DB, int) {
|
||||
t.Helper()
|
||||
sqlDB, err := sql.Open("pgx", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(1)
|
||||
sqlDB.SetMaxIdleConns(1)
|
||||
t.Cleanup(func() { _ = sqlDB.Close() })
|
||||
if _, err := sqlDB.Exec(`SET statement_timeout='10s'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var pid int
|
||||
if err := sqlDB.QueryRow(`SELECT pg_backend_pid()`).Scan(&pid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &DB{sqlDB}, pid
|
||||
}
|
||||
|
||||
func waitForTaskDeleteBlock(observer *DB, pid int, done <-chan error) error {
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
select {
|
||||
case err := <-done:
|
||||
return fmt.Errorf("operation returned before reaching the task deletion lock: %v", err)
|
||||
default:
|
||||
}
|
||||
var blockers int
|
||||
if err := observer.QueryRow(`SELECT cardinality(pg_blocking_pids($1))`, pid).Scan(&blockers); err != nil {
|
||||
return err
|
||||
}
|
||||
if blockers > 0 {
|
||||
return nil
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
return fmt.Errorf("backend %d did not block within 5s", pid)
|
||||
}
|
||||
|
||||
func waitForTaskDeleteResult(done <-chan error) error {
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-time.After(12 * time.Second):
|
||||
return fmt.Errorf("timed out waiting for concurrent task deletion operation")
|
||||
}
|
||||
}
|
||||
|
||||
func containsDeleteHost(hosts []string, want string) bool {
|
||||
for _, host := range hosts {
|
||||
if host == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
+7
-7
@@ -347,23 +347,23 @@ func hostPortOf(n *CoverageGraphNode) (string, int) {
|
||||
return host, port
|
||||
}
|
||||
|
||||
// BuildCoverageGraph assembles the full coverage graph for a task: every in-scope
|
||||
// asset (all types) plus the connector root domains / companies needed to link
|
||||
// them, with a tested flag on each in-scope asset. The frontend does the folding
|
||||
// and highlighting; this only returns nodes + derived containment edges.
|
||||
func (s *AssetStore) BuildCoverageGraph(taskID, expID int64) (*CoverageGraphData, error) {
|
||||
// BuildCoverageGraph assembles the full coverage graph for a task and its direct
|
||||
// read-only sources: every in-scope asset plus connector root domains/companies,
|
||||
// with current-or-source fact anchors reflected in Tested. The legacy expID
|
||||
// argument is retained for API compatibility; the task registry is authoritative.
|
||||
func (s *AssetStore) BuildCoverageGraph(taskID, _ int64) (*CoverageGraphData, error) {
|
||||
g := &CoverageGraphData{Nodes: []CoverageGraphNode{}, Edges: []CoverageGraphEdge{}}
|
||||
if taskID <= 0 {
|
||||
return g, nil
|
||||
}
|
||||
rows, err := s.db.Query(`WITH `+covTargetCTE+`
|
||||
rows, err := s.db.Query(`WITH `+contextCoverageCTE+`
|
||||
SELECT a.id, a.type, COALESCE(a.company_id,0),
|
||||
COALESCE(a.domain,''), COALESCE(a.root_domain,''), COALESCE(a.ip,''),
|
||||
COALESCE(a.url,''), COALESCE(a.port,0), COALESCE(a.service_type,''),
|
||||
COALESCE(a.app_name,''), COALESCE(a.page_title,''), COALESCE(a.status_code,0),
|
||||
(a.id IN (SELECT asset_id FROM tested)) AS tested
|
||||
FROM assets a JOIN target t ON t.id = a.id
|
||||
ORDER BY a.id`, taskID, expID)
|
||||
ORDER BY a.id`, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCreateTaskRejectsTooManySourcesBeforeOpeningTransaction(t *testing.T) {
|
||||
sourceIDs := make([]int64, MaxTaskSourceCount+1)
|
||||
for i := range sourceIDs {
|
||||
sourceIDs[i] = int64(i + 1)
|
||||
}
|
||||
|
||||
// No database handle is needed: validation must run before Begin so an
|
||||
// oversized request cannot consume a connection or create partial rows.
|
||||
_, err := (&DB{}).CreateTaskWithOptions("child", "goal", TaskCreateOptions{SourceTaskIDs: sourceIDs})
|
||||
if err == nil || !strings.Contains(err.Error(), "too many source tasks") {
|
||||
t.Fatalf("expected source-count validation error, got %v", err)
|
||||
}
|
||||
}
|
||||
+262
-34
@@ -1,23 +1,34 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Task is a row in the task registry (1:1 with an exploration).
|
||||
type Task struct {
|
||||
ID int64 `json:"id"`
|
||||
Description string `json:"description"`
|
||||
Goal string `json:"goal"`
|
||||
ExplorationID int64 `json:"exploration_id"`
|
||||
Status string `json:"status"`
|
||||
Paused bool `json:"paused"`
|
||||
Queued bool `json:"queued"` // 因并发上限被挂起、等待空位自动启动;true=尚未开跑
|
||||
LLMProfileID *int64 `json:"llm_profile_id,omitempty"`
|
||||
ParentRef string `json:"parent_ref,omitempty"` // 父任务 id(编排 spawn 记录;空=顶层)
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"` // 进入终态(done/failed/timeout)的时刻;非终态为 nil
|
||||
ID int64 `json:"id"`
|
||||
Description string `json:"description"`
|
||||
Goal string `json:"goal"`
|
||||
ExplorationID int64 `json:"exploration_id"`
|
||||
Status string `json:"status"`
|
||||
Paused bool `json:"paused"`
|
||||
Queued bool `json:"queued"`
|
||||
LLMProfileID *int64 `json:"llm_profile_id,omitempty"`
|
||||
// Task-level ordered LLM chain. LLMProfileID remains the compatibility alias
|
||||
// for ActiveLLMProfileID while older API clients still send one profile id.
|
||||
LLMProfileIDs []int64 `json:"llm_profile_ids,omitempty"`
|
||||
ActiveLLMProfileID *int64 `json:"active_llm_profile_id,omitempty"`
|
||||
LLMChainRevision int64 `json:"-"`
|
||||
LLMFailoverState string `json:"llm_failover_state,omitempty"`
|
||||
LLMFailoverReason string `json:"llm_failover_reason,omitempty"`
|
||||
SourceTaskIDs []int64 `json:"source_task_ids,omitempty"`
|
||||
ParentRef string `json:"parent_ref,omitempty"` // 父任务 id(编排 spawn 记录;空=顶层)
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"` // 进入终态(done/failed/timeout)的时刻;非终态为 nil
|
||||
// 任务级超时(见 docs/任务级超时与收尾设计.md)。
|
||||
TimeoutSeconds int `json:"timeout_seconds"` // 0=不限时
|
||||
FirstRunAt *time.Time `json:"first_run_at,omitempty"` // 首次真正开始运行的时刻(非 created_at);nil=尚未运行
|
||||
@@ -27,6 +38,23 @@ type Task struct {
|
||||
PlanHeartbeatSeconds int `json:"plan_heartbeat_seconds"`
|
||||
}
|
||||
|
||||
// TaskDeleteResult reports optional related-data cleanup performed in the same
|
||||
// transaction as the task/exploration delete.
|
||||
type TaskDeleteResult struct {
|
||||
AssetsDeleted int64
|
||||
AssetsDetached int64
|
||||
FindingsDeleted int64
|
||||
LLMRecordsDeleted int64
|
||||
}
|
||||
|
||||
// TaskDeletePreparation is produced inside the PostgreSQL deletion transaction
|
||||
// after asset and anchor writers have been excluded. Prepare callbacks may use
|
||||
// TrafficHosts to stage an external traffic deletion before PostgreSQL commits.
|
||||
type TaskDeletePreparation struct {
|
||||
ExplorationID int64
|
||||
TrafficHosts []string
|
||||
}
|
||||
|
||||
// IsTerminal reports whether a task status is a terminal (finished) state.
|
||||
// 单一真源,替换散落各处的 done/failed 硬编码判定。
|
||||
func IsTerminal(status string) bool {
|
||||
@@ -40,6 +68,12 @@ func IsTerminal(status string) bool {
|
||||
// 低于它(含缺省 0 / 负值 / 误配的小值)一律抬到 10min,防止把 planner 打爆。
|
||||
const MinPlanHeartbeatSeconds = 600
|
||||
|
||||
// MaxTaskSourceCount bounds the amount of live inherited context one task can
|
||||
// pull into every planner/main-agent prompt. Inheritance is intentionally direct
|
||||
// only; keeping the fan-in bounded also prevents a single create request from
|
||||
// multiplying graph and asset-context queries without limit.
|
||||
const MaxTaskSourceCount = 8
|
||||
|
||||
func normalizeHeartbeat(sec int) int {
|
||||
if sec < MinPlanHeartbeatSeconds {
|
||||
return MinPlanHeartbeatSeconds
|
||||
@@ -48,6 +82,30 @@ func normalizeHeartbeat(sec int) int {
|
||||
}
|
||||
|
||||
func (d *DB) CreateTask(description, goal string, llmProfileID *int64, timeoutSeconds, planHeartbeatSeconds int) (*Task, error) {
|
||||
var ids []int64
|
||||
if llmProfileID != nil {
|
||||
ids = []int64{*llmProfileID}
|
||||
}
|
||||
return d.CreateTaskWithOptions(description, goal, TaskCreateOptions{
|
||||
LLMProfileIDs: ids, TimeoutSeconds: timeoutSeconds, PlanHeartbeatSeconds: planHeartbeatSeconds,
|
||||
})
|
||||
}
|
||||
|
||||
// TaskCreateOptions contains the task data that must be committed atomically
|
||||
// with the task/exploration row.
|
||||
type TaskCreateOptions struct {
|
||||
SourceTaskIDs []int64
|
||||
LLMProfileIDs []int64
|
||||
TimeoutSeconds int
|
||||
PlanHeartbeatSeconds int
|
||||
}
|
||||
|
||||
// CreateTaskWithOptions creates an exploration, task, direct source relations,
|
||||
// and the ordered task LLM chain in one transaction.
|
||||
func (d *DB) CreateTaskWithOptions(description, goal string, opts TaskCreateOptions) (*Task, error) {
|
||||
if len(opts.SourceTaskIDs) > MaxTaskSourceCount {
|
||||
return nil, fmt.Errorf("too many source tasks: got %d, maximum is %d", len(opts.SourceTaskIDs), MaxTaskSourceCount)
|
||||
}
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -72,24 +130,80 @@ INSERT INTO exploration_nodes(exploration_id, kind, payload, priority, state, or
|
||||
VALUES ($1, 'fact', $2, 0, 'origin', 'system')`, expID, string(originPayload)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if timeoutSeconds < 0 {
|
||||
timeoutSeconds = 0
|
||||
if opts.TimeoutSeconds < 0 {
|
||||
opts.TimeoutSeconds = 0
|
||||
}
|
||||
opts.PlanHeartbeatSeconds = normalizeHeartbeat(opts.PlanHeartbeatSeconds)
|
||||
var active *int64
|
||||
if len(opts.LLMProfileIDs) > 0 {
|
||||
id := opts.LLMProfileIDs[0]
|
||||
active = &id
|
||||
}
|
||||
t := &Task{
|
||||
Description: description, Goal: goal, ExplorationID: expID,
|
||||
LLMProfileID: active, ActiveLLMProfileID: active,
|
||||
LLMProfileIDs: append([]int64(nil), opts.LLMProfileIDs...),
|
||||
SourceTaskIDs: append([]int64(nil), opts.SourceTaskIDs...),
|
||||
TimeoutSeconds: opts.TimeoutSeconds, PlanHeartbeatSeconds: opts.PlanHeartbeatSeconds,
|
||||
}
|
||||
planHeartbeatSeconds = normalizeHeartbeat(planHeartbeatSeconds) // <=0→300,<30→30
|
||||
t := &Task{Description: description, Goal: goal, ExplorationID: expID, LLMProfileID: llmProfileID, TimeoutSeconds: timeoutSeconds, PlanHeartbeatSeconds: planHeartbeatSeconds}
|
||||
if err := tx.QueryRow(`
|
||||
INSERT INTO tasks(description, goal, exploration_id, llm_profile_id, timeout_seconds, plan_heartbeat_seconds) VALUES ($1,$2,$3,$4,$5,$6)
|
||||
RETURNING id, status, paused, created_at`, description, goal, expID, llmProfileID, timeoutSeconds, planHeartbeatSeconds).Scan(&t.ID, &t.Status, &t.Paused, &t.CreatedAt); err != nil {
|
||||
INSERT INTO tasks(description, goal, exploration_id, llm_profile_id, active_llm_profile_id, timeout_seconds, plan_heartbeat_seconds)
|
||||
VALUES ($1,$2,$3,$4,$4,$5,$6)
|
||||
RETURNING id, status, paused, created_at`, description, goal, expID, active, opts.TimeoutSeconds, opts.PlanHeartbeatSeconds).Scan(&t.ID, &t.Status, &t.Paused, &t.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := insertTaskRelations(tx, t.ID, opts.SourceTaskIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := insertTaskLLMProfiles(tx, t.ID, opts.LLMProfileIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(opts.LLMProfileIDs) == 0 {
|
||||
t.LLMFailoverState = "default"
|
||||
} else {
|
||||
t.LLMFailoverState = "ready"
|
||||
}
|
||||
return t, tx.Commit()
|
||||
}
|
||||
|
||||
const taskCols = `id, description, goal, exploration_id, status, paused, queued, llm_profile_id, COALESCE(parent_ref,''), created_at, completed_at, COALESCE(timeout_seconds,0), COALESCE(plan_heartbeat_seconds,300), first_run_at, deadline_at`
|
||||
func insertTaskRelations(tx *sql.Tx, taskID int64, sourceIDs []int64) error {
|
||||
seen := map[int64]bool{}
|
||||
for _, sourceID := range sourceIDs {
|
||||
if sourceID <= 0 || sourceID == taskID || seen[sourceID] {
|
||||
return fmt.Errorf("invalid or duplicate source task id %d", sourceID)
|
||||
}
|
||||
seen[sourceID] = true
|
||||
res, err := tx.Exec(`INSERT INTO task_relations(task_id, source_task_id)
|
||||
SELECT $1, id FROM tasks WHERE id=$2 AND deleted_at IS NULL`, taskID, sourceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n != 1 {
|
||||
return fmt.Errorf("source task %d not found", sourceID)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func insertTaskLLMProfiles(tx *sql.Tx, taskID int64, profileIDs []int64) error {
|
||||
seen := map[int64]bool{}
|
||||
for position, profileID := range profileIDs {
|
||||
if profileID <= 0 || seen[profileID] {
|
||||
return fmt.Errorf("invalid or duplicate LLM profile id %d", profileID)
|
||||
}
|
||||
seen[profileID] = true
|
||||
if _, err := tx.Exec(`INSERT INTO task_llm_profiles(task_id, profile_id, position) VALUES ($1,$2,$3)`, taskID, profileID, position); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const taskCols = `id, description, goal, exploration_id, status, paused, queued, llm_profile_id, active_llm_profile_id, COALESCE(parent_ref,''), created_at, completed_at, COALESCE(timeout_seconds,0), COALESCE(plan_heartbeat_seconds,300), first_run_at, deadline_at`
|
||||
|
||||
func scanTask(sc interface{ Scan(...any) error }) (*Task, error) {
|
||||
var t Task
|
||||
if err := sc.Scan(&t.ID, &t.Description, &t.Goal, &t.ExplorationID, &t.Status, &t.Paused, &t.Queued, &t.LLMProfileID, &t.ParentRef, &t.CreatedAt, &t.CompletedAt, &t.TimeoutSeconds, &t.PlanHeartbeatSeconds, &t.FirstRunAt, &t.DeadlineAt); err != nil {
|
||||
if err := sc.Scan(&t.ID, &t.Description, &t.Goal, &t.ExplorationID, &t.Status, &t.Paused, &t.Queued, &t.LLMProfileID, &t.ActiveLLMProfileID, &t.ParentRef, &t.CreatedAt, &t.CompletedAt, &t.TimeoutSeconds, &t.PlanHeartbeatSeconds, &t.FirstRunAt, &t.DeadlineAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &t, nil
|
||||
@@ -116,7 +230,16 @@ func (d *DB) ListTasks() ([]*Task, error) {
|
||||
}
|
||||
out = append(out, t)
|
||||
}
|
||||
return out, rows.Err()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows.Close()
|
||||
for _, task := range out {
|
||||
if err := d.hydrateTaskContext(task); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetTask returns one alive task (nil if not found/deleted).
|
||||
@@ -128,6 +251,9 @@ func (d *DB) GetTask(id int64) (*Task, error) {
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if err := d.hydrateTaskContext(t); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
@@ -137,8 +263,6 @@ func (d *DB) SetPaused(id int64, paused bool) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// SetQueued persists a task's queued flag (并发上限挂起态). A queued task is held
|
||||
// (engine not started) until the concurrency reconciler promotes it into a free slot.
|
||||
func (d *DB) SetQueued(id int64, queued bool) error {
|
||||
_, err := d.Exec(`UPDATE tasks SET queued=$1 WHERE id=$2`, queued, id)
|
||||
return err
|
||||
@@ -192,28 +316,132 @@ UPDATE tasks
|
||||
return deadline, err
|
||||
}
|
||||
|
||||
// DeleteTask hard-deletes a task and its exploration subgraph (nodes/edges/
|
||||
// activity via ON DELETE CASCADE). The task row is removed first so the
|
||||
// ON DELETE RESTRICT on tasks.exploration_id does not block the exploration delete.
|
||||
// Global assets are NOT touched.
|
||||
// DeleteTask preserves the historical behavior: remove the task and its
|
||||
// exploration subgraph while retaining global assets.
|
||||
func (d *DB) DeleteTask(id int64) error {
|
||||
_, err := d.DeleteTaskCascade(id, false, false)
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteTaskCascade hard-deletes a task and its exploration subgraph
|
||||
// (nodes/edges/activity via ON DELETE CASCADE). Optional standalone findings and
|
||||
// assets owned only by this task are deleted in the same transaction; shared
|
||||
// assets are retained and only have this task id detached. deleteLLMRecords is
|
||||
// optional to preserve callers of the original two-option API.
|
||||
func (d *DB) DeleteTaskCascade(id int64, deleteAssets, deleteFindings bool, deleteLLMRecords ...bool) (TaskDeleteResult, error) {
|
||||
deleteRecords := len(deleteLLMRecords) > 0 && deleteLLMRecords[0]
|
||||
return d.DeleteTaskCascadePrepared(id, deleteAssets, deleteFindings, deleteRecords, nil)
|
||||
}
|
||||
|
||||
// DeleteTaskCascadePrepared coordinates reversible external deletion with the
|
||||
// PostgreSQL cascade. When prepare is non-nil, host ownership is resolved and
|
||||
// prepare is invoked inside this transaction while asset and anchor writers are
|
||||
// excluded. The locks remain held through commit, closing the window where a
|
||||
// host could become shared after its traffic had already been staged.
|
||||
//
|
||||
// prepare must only stage reversible work. Any returned error or later database
|
||||
// error rolls PostgreSQL back; the caller remains responsible for rolling back
|
||||
// external work that its callback staged successfully.
|
||||
func (d *DB) DeleteTaskCascadePrepared(
|
||||
id int64,
|
||||
deleteAssets, deleteFindings, deleteLLMRecords bool,
|
||||
prepare func(TaskDeletePreparation) error,
|
||||
) (TaskDeleteResult, error) {
|
||||
var result TaskDeleteResult
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
return result, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var expID int64
|
||||
if err := tx.QueryRow(`SELECT exploration_id FROM tasks WHERE id=$1`, id).Scan(&expID); err != nil {
|
||||
if err.Error() == "sql: no rows in result set" {
|
||||
return nil // already gone
|
||||
if err := tx.QueryRow(`SELECT exploration_id FROM tasks WHERE id=$1 FOR UPDATE`, id).Scan(&expID); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return result, nil // already gone
|
||||
}
|
||||
return err
|
||||
return result, err
|
||||
}
|
||||
|
||||
// SHARE ROW EXCLUSIVE conflicts with every INSERT/UPDATE/DELETE on these
|
||||
// tables and with another coordinated deletion. Taking both in one fixed order
|
||||
// prevents phantoms (a distinct asset row for the same host) as well as new
|
||||
// ownership/anchor references until the deletion transaction commits.
|
||||
if deleteAssets || prepare != nil {
|
||||
if _, err := tx.Exec(`LOCK TABLE assets, exploration_anchors IN SHARE ROW EXCLUSIVE MODE`); err != nil {
|
||||
return result, err
|
||||
}
|
||||
}
|
||||
if prepare != nil {
|
||||
hosts, err := hostsForTaskDeletion(tx, id, expID)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
if err := prepare(TaskDeletePreparation{
|
||||
ExplorationID: expID,
|
||||
TrafficHosts: hosts,
|
||||
}); err != nil {
|
||||
return result, err
|
||||
}
|
||||
}
|
||||
if deleteAssets {
|
||||
// Ownership is the union of explicit task_ids and this exploration's anchors.
|
||||
// An asset is deletable only when no other live task references it through
|
||||
// either mechanism. This covers legacy anchor-only seeds without destroying
|
||||
// evidence anchored by another task.
|
||||
res, err := tx.Exec(`
|
||||
WITH candidate_assets AS (
|
||||
SELECT id FROM assets WHERE $1 = ANY(task_ids)
|
||||
UNION
|
||||
SELECT ea.asset_id
|
||||
FROM exploration_anchors ea
|
||||
JOIN exploration_nodes n ON n.id=ea.node_id
|
||||
WHERE n.exploration_id=$2
|
||||
),
|
||||
deletable AS (
|
||||
SELECT a.id
|
||||
FROM assets a
|
||||
JOIN candidate_assets c ON c.id=a.id
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM tasks t
|
||||
WHERE t.id<>$1 AND t.deleted_at IS NULL AND t.id=ANY(a.task_ids)
|
||||
) AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM exploration_anchors ea
|
||||
JOIN exploration_nodes n ON n.id=ea.node_id
|
||||
JOIN tasks t ON t.exploration_id=n.exploration_id
|
||||
WHERE ea.asset_id=a.id AND t.id<>$1 AND t.deleted_at IS NULL
|
||||
)
|
||||
)
|
||||
DELETE FROM assets a USING deletable d WHERE a.id=d.id`, id, expID)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.AssetsDeleted, _ = res.RowsAffected()
|
||||
|
||||
res, err = tx.Exec(`UPDATE assets SET task_ids = array_remove(task_ids, $1) WHERE $1 = ANY(task_ids)`, id)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.AssetsDetached, _ = res.RowsAffected()
|
||||
}
|
||||
if deleteFindings {
|
||||
res, err := tx.Exec(`DELETE FROM findings WHERE task_id = $1`, id)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.FindingsDeleted, _ = res.RowsAffected()
|
||||
}
|
||||
if deleteLLMRecords {
|
||||
res, err := tx.Exec(`DELETE FROM llm_records WHERE COALESCE(task_id,'')=$1`, strconv.FormatInt(id, 10))
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.LLMRecordsDeleted, _ = res.RowsAffected()
|
||||
}
|
||||
if _, err := tx.Exec(`DELETE FROM tasks WHERE id=$1`, id); err != nil {
|
||||
return err
|
||||
return result, err
|
||||
}
|
||||
if _, err := tx.Exec(`DELETE FROM explorations WHERE id=$1`, expID); err != nil {
|
||||
return err
|
||||
return result, err
|
||||
}
|
||||
return tx.Commit()
|
||||
return result, tx.Commit()
|
||||
}
|
||||
+409
-1
@@ -1,6 +1,11 @@
|
||||
package db
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTaskLifecycleAndDeleteCascade(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
@@ -75,3 +80,406 @@ func TestTaskLifecycleAndDeleteCascade(t *testing.T) {
|
||||
t.Fatalf("exploration should be deleted, got %d", exps)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskDeleteCascadeAssets(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) — skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
first, err := d.CreateTask("级联删除测试", "目标A", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := d.CreateTask("共享资产保留测试", "目标B", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assets := d.Assets()
|
||||
exclusiveID, err := assets.UpsertRootDomain(UpsertRootDomainReq{
|
||||
Domain: fmt.Sprintf("delete-%d.example.test", first.ID),
|
||||
TaskID: first.ID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sharedDomain := fmt.Sprintf("shared-%d.example.test", first.ID)
|
||||
sharedID, err := assets.UpsertRootDomain(UpsertRootDomainReq{Domain: sharedDomain, TaskID: first.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := assets.UpsertRootDomain(UpsertRootDomainReq{Domain: sharedDomain, TaskID: second.ID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
anchorOnlyDomain := fmt.Sprintf("anchor-only-%d.example.test", first.ID)
|
||||
anchorOnlyID, err := assets.UpsertRootDomain(UpsertRootDomainReq{Domain: anchorOnlyDomain})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
firstOrigin, err := d.Exploration(first.ExplorationID).OriginFactID()
|
||||
if err != nil || firstOrigin == 0 {
|
||||
t.Fatalf("first origin: id=%d err=%v", firstOrigin, err)
|
||||
}
|
||||
if err := d.Exploration(first.ExplorationID).Anchor(firstOrigin, anchorOnlyID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
protectedDomain := fmt.Sprintf("other-anchor-%d.example.test", first.ID)
|
||||
protectedID, err := assets.UpsertRootDomain(UpsertRootDomainReq{Domain: protectedDomain, TaskID: first.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secondOrigin, err := d.Exploration(second.ExplorationID).OriginFactID()
|
||||
if err != nil || secondOrigin == 0 {
|
||||
t.Fatalf("second origin: id=%d err=%v", secondOrigin, err)
|
||||
}
|
||||
if err := d.Exploration(second.ExplorationID).Anchor(secondOrigin, protectedID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = d.DeleteTask(first.ID)
|
||||
_ = d.DeleteTask(second.ID)
|
||||
_, _ = assets.DeleteByIDs([]int64{exclusiveID, sharedID, anchorOnlyID, protectedID})
|
||||
})
|
||||
|
||||
hosts, err := assets.HostsByTask(first.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hostSet := make(map[string]bool, len(hosts))
|
||||
for _, host := range hosts {
|
||||
hostSet[host] = true
|
||||
}
|
||||
if !hostSet[fmt.Sprintf("delete-%d.example.test", first.ID)] || !hostSet[sharedDomain] {
|
||||
t.Fatalf("task hosts missing cascade fixtures: %v", hosts)
|
||||
}
|
||||
deletableHosts, err := assets.HostsForTaskDeletion(first.ID, first.ExplorationID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deletableSet := make(map[string]bool, len(deletableHosts))
|
||||
for _, host := range deletableHosts {
|
||||
deletableSet[host] = true
|
||||
}
|
||||
if !deletableSet[fmt.Sprintf("delete-%d.example.test", first.ID)] || !deletableSet[anchorOnlyDomain] {
|
||||
t.Fatalf("exclusive or anchor-only cleanup host missing: %v", deletableHosts)
|
||||
}
|
||||
if deletableSet[sharedDomain] || deletableSet[protectedDomain] {
|
||||
t.Fatalf("shared host was not protected from traffic cleanup: %v", deletableHosts)
|
||||
}
|
||||
|
||||
findingID, err := d.AddFinding(first.ID, 0, "__task_delete_cascade__", "", SeverityHigh, "summary", "evidence", "tester", []int64{exclusiveID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result, err := d.DeleteTaskCascade(first.ID, true, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.AssetsDeleted < 2 || result.AssetsDetached < 2 {
|
||||
t.Fatalf("unexpected asset cleanup result: %+v", result)
|
||||
}
|
||||
if result.FindingsDeleted != 1 {
|
||||
t.Fatalf("unexpected finding cleanup result: %+v", result)
|
||||
}
|
||||
if finding, err := d.GetFinding(findingID); err != nil || finding != nil {
|
||||
t.Fatalf("finding should be deleted, got finding=%+v err=%v", finding, err)
|
||||
}
|
||||
remaining, err := assets.GetByIDs([]int64{exclusiveID, sharedID, anchorOnlyID, protectedID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(remaining) != 2 {
|
||||
t.Fatalf("only shared and other-anchored assets should remain, got %+v", remaining)
|
||||
}
|
||||
byID := make(map[int64]*Asset, len(remaining))
|
||||
for _, asset := range remaining {
|
||||
byID[asset.ID] = asset
|
||||
}
|
||||
if shared := byID[sharedID]; shared == nil || len(shared.TaskIDs) != 1 || shared.TaskIDs[0] != second.ID {
|
||||
t.Fatalf("deleted task should be detached from shared asset: %+v", shared)
|
||||
}
|
||||
if protected := byID[protectedID]; protected == nil || len(protected.TaskIDs) != 0 {
|
||||
t.Fatalf("other task's anchor should preserve the asset after detaching ownership: %+v", protected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskRelationsAndLLMFailoverChain(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
suffix := time.Now().UnixNano()
|
||||
profileIDs := make([]int64, 0, 3)
|
||||
for i := 0; i < 3; i++ {
|
||||
id, err := d.SaveProfile(&LLMProfile{
|
||||
Name: fmt.Sprintf("task-chain-%d-%d", suffix, i), Format: "openai",
|
||||
Model: fmt.Sprintf("model-%d", i), APIKey: "test-key",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
profileIDs = append(profileIDs, id)
|
||||
}
|
||||
|
||||
sourceA, err := d.CreateTask("source A", "goal A", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sourceB, err := d.CreateTask("source B", "goal B", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
child, err := d.CreateTaskWithOptions("child", "new goal", TaskCreateOptions{
|
||||
SourceTaskIDs: []int64{sourceA.ID, sourceB.ID},
|
||||
LLMProfileIDs: profileIDs,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = d.DeleteTask(child.ID)
|
||||
_ = d.DeleteTask(sourceA.ID)
|
||||
_ = d.DeleteTask(sourceB.ID)
|
||||
for _, id := range profileIDs {
|
||||
_ = d.DeleteProfile(id)
|
||||
}
|
||||
})
|
||||
|
||||
got, err := d.GetTask(child.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fmt.Sprint(got.SourceTaskIDs) != fmt.Sprint([]int64{sourceA.ID, sourceB.ID}) {
|
||||
t.Fatalf("unexpected direct sources: %v", got.SourceTaskIDs)
|
||||
}
|
||||
if fmt.Sprint(got.LLMProfileIDs) != fmt.Sprint(profileIDs) || got.ActiveLLMProfileID == nil || *got.ActiveLLMProfileID != profileIDs[0] {
|
||||
t.Fatalf("unexpected initial chain: %+v", got)
|
||||
}
|
||||
initialRevision := got.LLMChainRevision
|
||||
if err := d.ReplaceTaskLLMProfiles(child.ID, profileIDs, profileIDs[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
staleRevision, err := d.MarkTaskLLMProfileQuotaExhaustedAtRevision(child.ID, profileIDs[0], initialRevision, "late quota from prior generation")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !staleRevision.Stale || staleRevision.Advanced || staleRevision.ChainExhausted {
|
||||
t.Fatalf("old chain revision changed replacement chain: %+v", staleRevision)
|
||||
}
|
||||
got, err = d.GetTask(child.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.LLMChainRevision <= initialRevision || got.ActiveLLMProfileID == nil || *got.ActiveLLMProfileID != profileIDs[0] {
|
||||
t.Fatalf("replacement revision/cursor not preserved: %+v", got)
|
||||
}
|
||||
|
||||
transition, err := d.MarkTaskLLMProfileQuotaExhausted(child.ID, profileIDs[0], "insufficient_quota")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !transition.Advanced || transition.ChainExhausted || transition.NextProfileID == nil || *transition.NextProfileID != profileIDs[1] {
|
||||
t.Fatalf("unexpected first transition: %+v", transition)
|
||||
}
|
||||
late, err := d.MarkTaskLLMProfileQuotaExhausted(child.ID, profileIDs[0], "late duplicate")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if late.Advanced || late.NextProfileID == nil || *late.NextProfileID != profileIDs[1] {
|
||||
t.Fatalf("late failure advanced past current profile: %+v", late)
|
||||
}
|
||||
if _, err := d.MarkTaskLLMProfileQuotaExhausted(child.ID, profileIDs[1], "quota_exceeded"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
last, err := d.MarkTaskLLMProfileQuotaExhausted(child.ID, profileIDs[2], "余额不足")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !last.Advanced || !last.ChainExhausted || last.NextProfileID != nil {
|
||||
t.Fatalf("unexpected exhausted transition: %+v", last)
|
||||
}
|
||||
duplicateLast, err := d.MarkTaskLLMProfileQuotaExhausted(child.ID, profileIDs[2], "late final duplicate")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if duplicateLast.Advanced || !duplicateLast.ChainExhausted || duplicateLast.NextProfileID != nil {
|
||||
t.Fatalf("duplicate final failure must be idempotent: %+v", duplicateLast)
|
||||
}
|
||||
got, err = d.GetTask(child.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.ActiveLLMProfileID != nil || got.LLMFailoverState != "chain_exhausted" {
|
||||
t.Fatalf("chain exhaustion was not persisted: %+v", got)
|
||||
}
|
||||
|
||||
// Two requests can observe the same last active profile. Only the transaction
|
||||
// that clears the cursor may report an advance; the late one is idempotent.
|
||||
if err := d.ReplaceTaskLLMProfiles(child.ID, []int64{profileIDs[2]}, profileIDs[2]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
transitions := make(chan TaskLLMTransition, 2)
|
||||
errs := make(chan error, 2)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 2; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
transition, markErr := d.MarkTaskLLMProfileQuotaExhausted(child.ID, profileIDs[2], "concurrent final quota")
|
||||
if markErr != nil {
|
||||
errs <- markErr
|
||||
return
|
||||
}
|
||||
transitions <- transition
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
close(transitions)
|
||||
for markErr := range errs {
|
||||
t.Fatal(markErr)
|
||||
}
|
||||
advanced := 0
|
||||
for transition := range transitions {
|
||||
if transition.Advanced {
|
||||
advanced++
|
||||
}
|
||||
if !transition.ChainExhausted {
|
||||
t.Fatalf("concurrent final transition must report exhausted chain: %+v", transition)
|
||||
}
|
||||
}
|
||||
if advanced != 1 {
|
||||
t.Fatalf("last profile advanced %d times, want exactly once", advanced)
|
||||
}
|
||||
|
||||
// Starting manually from the middle consumes only candidates after that cursor.
|
||||
// Earlier ready profiles must not be revived by hydration or unrelated deletes.
|
||||
if err := d.ReplaceTaskLLMProfiles(child.ID, []int64{profileIDs[2], profileIDs[0], profileIDs[1]}, profileIDs[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if step, err := d.MarkTaskLLMProfileQuotaExhausted(child.ID, profileIDs[0], "middle quota"); err != nil || step.NextProfileID == nil || *step.NextProfileID != profileIDs[1] {
|
||||
t.Fatalf("middle cursor did not advance to its successor: transition=%+v err=%v", step, err)
|
||||
}
|
||||
if end, err := d.MarkTaskLLMProfileQuotaExhausted(child.ID, profileIDs[1], "tail quota"); err != nil || !end.ChainExhausted {
|
||||
t.Fatalf("tail did not exhaust manual chain: transition=%+v err=%v", end, err)
|
||||
}
|
||||
got, err = d.GetTask(child.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.ActiveLLMProfileID != nil || got.LLMFailoverState != "chain_exhausted" {
|
||||
t.Fatalf("hydration revived a profile before the manual cursor: %+v", got)
|
||||
}
|
||||
unrelatedID, err := d.SaveProfile(&LLMProfile{
|
||||
Name: fmt.Sprintf("task-chain-unrelated-%d", suffix), Format: "openai", Model: "other", APIKey: "test-key",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := d.DeleteProfile(unrelatedID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err = d.GetTask(child.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.ActiveLLMProfileID != nil || got.LLMFailoverState != "chain_exhausted" {
|
||||
t.Fatalf("deleting an unrelated profile revived an exhausted chain: %+v", got)
|
||||
}
|
||||
|
||||
// A call that finishes after its profile was removed from the chain is stale:
|
||||
// preserve the new cursor and surface the original provider error upstream.
|
||||
if err := d.ReplaceTaskLLMProfiles(child.ID, []int64{profileIDs[2], profileIDs[1]}, profileIDs[2]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stale, err := d.MarkTaskLLMProfileQuotaExhausted(child.ID, profileIDs[0], "obsolete in-flight quota")
|
||||
if err != nil {
|
||||
t.Fatalf("removed in-flight profile returned an internal error: %v", err)
|
||||
}
|
||||
if stale.Advanced || stale.ChainExhausted || stale.NextProfileID != nil {
|
||||
t.Fatalf("removed in-flight profile changed the replacement chain: %+v", stale)
|
||||
}
|
||||
got, err = d.GetTask(child.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.ActiveLLMProfileID == nil || *got.ActiveLLMProfileID != profileIDs[2] {
|
||||
t.Fatalf("stale failure changed active replacement profile: %+v", got)
|
||||
}
|
||||
|
||||
if err := d.ReplaceTaskLLMProfiles(child.ID, []int64{profileIDs[2], profileIDs[0], profileIDs[1]}, profileIDs[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err = d.GetTask(child.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.ActiveLLMProfileID == nil || *got.ActiveLLMProfileID != profileIDs[0] || got.LLMFailoverState != "ready" || got.LLMFailoverReason != "" {
|
||||
t.Fatalf("chain reset did not clear failure state: %+v", got)
|
||||
}
|
||||
|
||||
if err := d.DeleteProfile(profileIDs[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err = d.GetTask(child.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.ActiveLLMProfileID == nil || *got.ActiveLLMProfileID != profileIDs[1] {
|
||||
t.Fatalf("deleting active profile did not select next ready entry: %+v", got)
|
||||
}
|
||||
if err := d.DeleteProfile(profileIDs[1]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err = d.GetTask(child.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.ActiveLLMProfileID != nil || len(got.LLMProfileIDs) != 0 || got.LLMFailoverState != "default" {
|
||||
t.Fatalf("deleting active chain tail must fall back instead of wrapping: %+v", got)
|
||||
}
|
||||
|
||||
if err := d.DeleteTask(sourceA.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err = d.GetTask(child.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fmt.Sprint(got.SourceTaskIDs) != fmt.Sprint([]int64{sourceB.ID}) {
|
||||
t.Fatalf("source delete did not cascade only its relation: %v", got.SourceTaskIDs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskContextRejectsDuplicatesAndTerminalEdits(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
source, err := d.CreateTask("source", "goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = d.DeleteTask(source.ID) })
|
||||
if _, err := d.CreateTaskWithOptions("bad", "goal", TaskCreateOptions{SourceTaskIDs: []int64{source.ID, source.ID}}); err == nil {
|
||||
t.Fatal("duplicate source task ids should be rejected")
|
||||
}
|
||||
|
||||
task, err := d.CreateTask("terminal", "goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = d.DeleteTask(task.ID) })
|
||||
if err := d.SetStatus(task.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := d.ReplaceTaskLLMProfiles(task.ID, nil, 0); err == nil {
|
||||
t.Fatal("terminal task LLM edit should be rejected")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user