mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-11-27 10:21:50 +08:00
feat(tasks): stop tasks that miss a configurable findings checkpoint
This commit is contained in:
1 parent
39a8f2c31a
commit
997d2d98c0
24 files changed
+812
-64
No files matched your search
@@ -523,6 +523,12 @@ CREATE TABLE IF NOT EXISTS tasks (
|
||||
company_id BIGINT REFERENCES companies(id) ON DELETE SET NULL,
|
||||
parent_ref TEXT,
|
||||
timeout_seconds INTEGER NOT NULL DEFAULT 0,
|
||||
no_result_seconds INTEGER NOT NULL DEFAULT 0,
|
||||
no_result_min_findings INTEGER NOT NULL DEFAULT 1,
|
||||
no_result_min_severity TEXT NOT NULL DEFAULT '',
|
||||
no_result_base_seconds BIGINT NOT NULL DEFAULT 0,
|
||||
no_result_checked_at TIMESTAMPTZ,
|
||||
stop_reason TEXT NOT NULL DEFAULT '',
|
||||
plan_heartbeat_seconds INTEGER NOT NULL DEFAULT 300,
|
||||
coverage_enabled BOOLEAN NOT NULL DEFAULT true,
|
||||
worker_count INTEGER NOT NULL DEFAULT 0, -- 0=用全局默认 workers
|
||||
@@ -537,6 +543,13 @@ CREATE TABLE IF NOT EXISTS tasks (
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
-- Opt-in checkpoint based on active runtime; defaults preserve existing tasks.
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS no_result_seconds INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS no_result_min_findings INTEGER NOT NULL DEFAULT 1;
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS no_result_min_severity TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS no_result_base_seconds BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS no_result_checked_at TIMESTAMPTZ;
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS stop_reason TEXT NOT NULL DEFAULT '';
|
||||
CREATE INDEX IF NOT EXISTS idx_tasks_alive ON tasks(created_at DESC) WHERE deleted_at IS NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status) WHERE deleted_at IS NULL;
|
||||
DROP TRIGGER IF EXISTS trg_tasks_upd ON tasks;
|
||||
|
||||
@@ -123,6 +123,7 @@ AND NOT EXISTS (
|
||||
name='',remark='',category_id=NULL,description='',goal='',paused=true,queued=false,queued_at=NULL,queue_mode='',
|
||||
llm_profile_id=NULL,active_llm_profile_id=NULL,llm_chain_revision=llm_chain_revision+1,
|
||||
company_id=NULL,parent_ref=NULL,timeout_seconds=0,coverage_enabled=true,share_global_assets=false,worker_count=0,pinned_at=NULL,
|
||||
no_result_seconds=0,no_result_min_findings=1,no_result_min_severity='',no_result_base_seconds=0,no_result_checked_at=NULL,stop_reason='',
|
||||
first_run_at=NULL,deadline_at=NULL,archived_at=now(),deleted_at=now()
|
||||
WHERE id=$1`, taskID); err != nil {
|
||||
return err
|
||||
@@ -322,6 +323,11 @@ func restoreTaskStub(tx *sql.Tx, row map[string]any, taskID, remaining int64) er
|
||||
llm_profile_id=archived.llm_profile_id,active_llm_profile_id=archived.active_llm_profile_id,
|
||||
llm_chain_revision=archived.llm_chain_revision,company_id=archived.company_id,parent_ref=archived.parent_ref,
|
||||
timeout_seconds=archived.timeout_seconds,plan_heartbeat_seconds=archived.plan_heartbeat_seconds,
|
||||
no_result_seconds=COALESCE(archived.no_result_seconds,0),
|
||||
no_result_min_findings=COALESCE(archived.no_result_min_findings,1),
|
||||
no_result_min_severity=COALESCE(archived.no_result_min_severity,''),
|
||||
no_result_base_seconds=COALESCE(archived.no_result_base_seconds,0),
|
||||
no_result_checked_at=archived.no_result_checked_at,stop_reason=COALESCE(archived.stop_reason,''),
|
||||
coverage_enabled=archived.coverage_enabled,share_global_assets=COALESCE(archived.share_global_assets,false),worker_count=COALESCE(archived.worker_count,0),pinned_at=archived.pinned_at,first_run_at=archived.first_run_at,
|
||||
deadline_at=CASE WHEN archived.paused AND $3>0 THEN now()+make_interval(secs=>$3::double precision)
|
||||
ELSE archived.deadline_at END,
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
const StopReasonNoResult = "no_result"
|
||||
|
||||
// NormalizeNoResultOptions is shared by task creation and API validation.
|
||||
func NormalizeNoResultOptions(opts *TaskCreateOptions) error {
|
||||
if opts.NoResultSeconds < 0 {
|
||||
opts.NoResultSeconds = 0
|
||||
} else if opts.NoResultSeconds > 0 && opts.NoResultSeconds < 60 {
|
||||
opts.NoResultSeconds = 60
|
||||
}
|
||||
if opts.NoResultMinFindings < 1 {
|
||||
opts.NoResultMinFindings = 1
|
||||
}
|
||||
switch opts.NoResultMinSeverity {
|
||||
case "", "low", "medium", "high", "critical":
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("invalid no_result_min_severity: %q", opts.NoResultMinSeverity)
|
||||
}
|
||||
}
|
||||
|
||||
// CountQualifyingFindings counts task-local independent findings, using the case
|
||||
// severity for grouped observations. False positives never count; unassessed
|
||||
// findings count only when the caller sets no severity threshold.
|
||||
func (d *DB) CountQualifyingFindings(taskID int64, minSeverity string) (int, error) {
|
||||
if err := NormalizeNoResultOptions(&TaskCreateOptions{NoResultMinSeverity: minSeverity}); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var count int
|
||||
err := d.QueryRow(`WITH observations AS (
|
||||
SELECT CASE WHEN m.case_id IS NULL THEN 'f:'||f.id ELSE 'c:'||m.case_id END entity,
|
||||
CASE WHEN m.case_id IS NULL THEN f.severity ELSE c.severity END severity
|
||||
FROM findings f
|
||||
LEFT JOIN finding_case_members m ON m.finding_id=f.id
|
||||
LEFT JOIN finding_cases c ON c.id=m.case_id
|
||||
WHERE f.task_id=$1 AND f.status<>'false_positive'
|
||||
)
|
||||
SELECT count(DISTINCT entity) FROM observations
|
||||
WHERE $2='' OR array_position(ARRAY['low','medium','high','critical'],severity)
|
||||
>= array_position(ARRAY['low','medium','high','critical'],$2)`, taskID, minSeverity).Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
// MarkNoResultChecked durably claims the single checkpoint. A terminal task or
|
||||
// an already checked checkpoint returns nil, so concurrent callers cannot stop
|
||||
// a task twice. A failed decision also persists its reason so restart can finish
|
||||
// settling without recounting findings that arrived during the drain.
|
||||
func (d *DB) MarkNoResultChecked(taskID int64, stop bool) (*time.Time, error) {
|
||||
var checked time.Time
|
||||
err := d.QueryRow(`UPDATE tasks SET no_result_checked_at=now(), stop_reason=CASE WHEN $2 THEN 'no_result' ELSE '' END
|
||||
WHERE id=$1 AND deleted_at IS NULL AND no_result_checked_at IS NULL
|
||||
AND status NOT IN ('done','failed','timeout')
|
||||
RETURNING no_result_checked_at`, taskID, stop).Scan(&checked)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &checked, nil
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNormalizeNoResultOptions(t *testing.T) {
|
||||
for _, tc := range []struct{ seconds, count, wantSeconds, wantCount int }{
|
||||
{0, 0, 0, 1}, {-1, -1, 0, 1}, {1, 0, 60, 1}, {59, 2, 60, 2}, {60, 1, 60, 1}, {7200, 3, 7200, 3},
|
||||
} {
|
||||
opts := TaskCreateOptions{NoResultSeconds: tc.seconds, NoResultMinFindings: tc.count}
|
||||
if err := NormalizeNoResultOptions(&opts); err != nil || opts.NoResultSeconds != tc.wantSeconds || opts.NoResultMinFindings != tc.wantCount {
|
||||
t.Fatalf("normalize %+v = %+v, %v", tc, opts, err)
|
||||
}
|
||||
}
|
||||
if err := NormalizeNoResultOptions(&TaskCreateOptions{NoResultMinSeverity: "unknown"}); err == nil {
|
||||
t.Fatal("invalid severity accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCountQualifyingFindings(t *testing.T) {
|
||||
d, task, ids := caseTestDB(t)
|
||||
caseID, err := d.MergeFindingCase(t.Context(), task.ID, ids[:3], "same defect", "same cause", "test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The case's severity overrides the high/medium/low original reports.
|
||||
if _, err := d.Exec(`UPDATE finding_cases SET severity='medium' WHERE id=$1`, caseID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, severity := range []string{"", "critical", "low"} {
|
||||
id, err := d.AddFinding(task.ID, 0, "test", "test", severity, "", "", "test", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if severity == "critical" {
|
||||
if _, err := d.Exec(`UPDATE findings SET status='false_positive' WHERE id=$1`, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
child, err := d.CreateTaskWithOptions("child", "inherits only", TaskCreateOptions{SourceTaskIDs: []int64{task.ID}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = d.DeleteTask(child.ID) })
|
||||
for severity, want := range map[string]int{"": 4, "low": 3, "medium": 2, "high": 1, "critical": 0} {
|
||||
got, err := d.CountQualifyingFindings(task.ID, severity)
|
||||
if err != nil || got != want {
|
||||
t.Errorf("severity %q: count=%d, err=%v, want %d", severity, got, err, want)
|
||||
}
|
||||
if got, err := d.CountQualifyingFindings(child.ID, severity); err != nil || got != 0 {
|
||||
t.Errorf("inherited findings counted: %d, %v", got, err)
|
||||
}
|
||||
}
|
||||
// A case with only false-positive observations contributes nothing.
|
||||
if _, err := d.Exec(`UPDATE findings SET status='false_positive' WHERE id=ANY($1)`, ids[:3]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := d.CountQualifyingFindings(task.ID, ""); err != nil || got != 3 {
|
||||
t.Fatalf("false-positive case: count=%d err=%v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoResultPersistenceGuardAndLegacyArchive(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.Close()
|
||||
task, err := d.CreateTaskWithOptions("checkpoint", "goal", TaskCreateOptions{
|
||||
NoResultSeconds: 1, NoResultMinFindings: 0, NoResultMinSeverity: "high",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.DeleteTask(task.ID)
|
||||
if stored, err := d.GetTask(task.ID); err != nil || stored.NoResultSeconds != 60 || stored.NoResultMinFindings != 1 || stored.NoResultMinSeverity != "high" {
|
||||
t.Fatalf("creation round trip: %+v, %v", stored, err)
|
||||
}
|
||||
if checked, err := d.MarkNoResultChecked(task.ID, true); err != nil || checked == nil {
|
||||
t.Fatalf("first check: %v, %v", checked, err)
|
||||
}
|
||||
if checked, err := d.MarkNoResultChecked(task.ID, true); err != nil || checked != nil {
|
||||
t.Fatalf("second check: %v, %v", checked, err)
|
||||
}
|
||||
if _, _, won, err := d.SetTerminalStatusGuardedReasonRuntime(task.ID, "timeout", StopReasonNoResult); err != nil || !won {
|
||||
t.Fatalf("stop: won=%v err=%v", won, err)
|
||||
}
|
||||
if _, _, won, err := d.SetTerminalStatusGuardedReasonRuntime(task.ID, "done", ""); err != nil || won {
|
||||
t.Fatalf("terminal guard: won=%v err=%v", won, err)
|
||||
}
|
||||
stored, err := d.GetTask(task.ID)
|
||||
if err != nil || stored.StopReason != StopReasonNoResult || stored.NoResultCheckedAt == nil {
|
||||
t.Fatalf("persisted decision: %+v, %v", stored, err)
|
||||
}
|
||||
if err := d.SetStatus(task.ID, "running"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored, err := d.GetTask(task.ID); err != nil || stored.StopReason != "" {
|
||||
t.Fatalf("nonterminal reason not cleared: %+v, %v", stored, err)
|
||||
}
|
||||
if _, _, won, err := d.SetTerminalStatusGuardedReasonRuntime(task.ID, "done", StopReasonNoResult); err != nil || !won {
|
||||
t.Fatalf("completed stop: won=%v err=%v", won, err)
|
||||
}
|
||||
if stored, err := d.GetTask(task.ID); err != nil || stored.StopReason != "" {
|
||||
t.Fatalf("done must have no stop reason: %+v, %v", stored, err)
|
||||
}
|
||||
var raw []byte
|
||||
if err := d.QueryRow(`SELECT to_jsonb(t) FROM tasks t WHERE id=$1`, task.ID).Scan(&raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var row map[string]any
|
||||
if err := json.Unmarshal(raw, &row); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, key := range []string{"no_result_seconds", "no_result_min_findings", "no_result_min_severity", "no_result_base_seconds", "no_result_checked_at", "stop_reason"} {
|
||||
delete(row, key)
|
||||
}
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err := restoreTaskStub(tx, row, task.ID, 0); err != nil {
|
||||
t.Fatalf("restore old archive without checkpoint fields: %v", err)
|
||||
}
|
||||
var seconds, minimum int
|
||||
var severity, reason string
|
||||
if err := tx.QueryRow(`SELECT no_result_seconds,no_result_min_findings,no_result_min_severity,stop_reason FROM tasks WHERE id=$1`, task.ID).Scan(&seconds, &minimum, &severity, &reason); err != nil || seconds != 0 || minimum != 1 || severity != "" || reason != "" {
|
||||
t.Fatalf("legacy defaults: %d %d %q %q, %v", seconds, minimum, severity, reason, err)
|
||||
}
|
||||
}
|
||||
+35
-10
@@ -42,7 +42,14 @@ type Task struct {
|
||||
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)。
|
||||
// Optional active-runtime checkpoint; StopReason also persists a pending stop.
|
||||
NoResultSeconds int `json:"no_result_seconds"`
|
||||
NoResultMinFindings int `json:"no_result_min_findings"`
|
||||
NoResultMinSeverity string `json:"no_result_min_severity"`
|
||||
NoResultBaseSeconds int64 `json:"no_result_base_seconds"`
|
||||
NoResultCheckedAt *time.Time `json:"no_result_checked_at,omitempty"`
|
||||
StopReason string `json:"stop_reason"`
|
||||
// 任务级绝对墙钟超时。
|
||||
TimeoutSeconds int `json:"timeout_seconds"` // 0=不限时
|
||||
FirstRunAt *time.Time `json:"first_run_at,omitempty"` // 首次真正开始运行的时刻(非 created_at);nil=尚未运行
|
||||
DeadlineAt *time.Time `json:"deadline_at,omitempty"` // = first_run_at + timeout_seconds;nil=不限或未运行
|
||||
@@ -184,6 +191,9 @@ type TaskCreateOptions struct {
|
||||
CompanyIDs []int64
|
||||
LLMProfileIDs []int64
|
||||
TimeoutSeconds int
|
||||
NoResultSeconds int
|
||||
NoResultMinFindings int
|
||||
NoResultMinSeverity string
|
||||
PlanHeartbeatSeconds int
|
||||
// CoverageEnabled 是「资产覆盖度功能」开关;nil=默认开(true),让不关心该开关的创建
|
||||
// 路径(编排 spawn、老 API)沿用原行为。仅 web 创建任务时可显式传 false 关闭。
|
||||
@@ -201,6 +211,9 @@ type TaskCreateOptions struct {
|
||||
// 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 err := NormalizeNoResultOptions(&opts); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(opts.SourceTaskIDs) > MaxTaskSourceCount {
|
||||
return nil, fmt.Errorf("too many source tasks: got %d, maximum is %d", len(opts.SourceTaskIDs), MaxTaskSourceCount)
|
||||
}
|
||||
@@ -267,16 +280,17 @@ VALUES ($1, 'fact', $2, 0, 'origin', 'system')`, expID, string(originPayload));
|
||||
Name: opts.Name, CategoryID: opts.CategoryID, CategoryName: categoryName,
|
||||
Description: description, Goal: goal, ExplorationID: expID,
|
||||
LLMProfileID: active, ActiveLLMProfileID: active,
|
||||
LLMProfileIDs: append([]int64(nil), opts.LLMProfileIDs...),
|
||||
SourceTaskIDs: append([]int64(nil), opts.SourceTaskIDs...),
|
||||
CompanyIDs: append([]int64(nil), opts.CompanyIDs...),
|
||||
LLMProfileIDs: append([]int64(nil), opts.LLMProfileIDs...),
|
||||
SourceTaskIDs: append([]int64(nil), opts.SourceTaskIDs...),
|
||||
CompanyIDs: append([]int64(nil), opts.CompanyIDs...),
|
||||
NoResultSeconds: opts.NoResultSeconds, NoResultMinFindings: opts.NoResultMinFindings, NoResultMinSeverity: opts.NoResultMinSeverity,
|
||||
TimeoutSeconds: opts.TimeoutSeconds, PlanHeartbeatSeconds: opts.PlanHeartbeatSeconds,
|
||||
CoverageEnabled: coverageEnabled, ShareGlobalAssets: opts.ShareGlobalAssets, WorkerCount: opts.WorkerCount, Remark: opts.Remark,
|
||||
}
|
||||
if err := tx.QueryRow(`
|
||||
INSERT INTO tasks(name, remark, category_id, description, goal, exploration_id, llm_profile_id, active_llm_profile_id, timeout_seconds, plan_heartbeat_seconds, coverage_enabled, worker_count, share_global_assets)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$7,$8,$9,$10,$11,$12)
|
||||
RETURNING id, status, paused, created_at`, opts.Name, opts.Remark, opts.CategoryID, description, goal, expID, active, opts.TimeoutSeconds, opts.PlanHeartbeatSeconds, coverageEnabled, opts.WorkerCount, opts.ShareGlobalAssets).Scan(&t.ID, &t.Status, &t.Paused, &t.CreatedAt); err != nil {
|
||||
INSERT INTO tasks(name, remark, category_id, description, goal, exploration_id, llm_profile_id, active_llm_profile_id, timeout_seconds, plan_heartbeat_seconds, coverage_enabled, worker_count, share_global_assets, no_result_seconds, no_result_min_findings, no_result_min_severity)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$7,$8,$9,$10,$11,$12,$13,$14,$15)
|
||||
RETURNING id, status, paused, created_at`, opts.Name, opts.Remark, opts.CategoryID, description, goal, expID, active, opts.TimeoutSeconds, opts.PlanHeartbeatSeconds, coverageEnabled, opts.WorkerCount, opts.ShareGlobalAssets, opts.NoResultSeconds, opts.NoResultMinFindings, opts.NoResultMinSeverity).Scan(&t.ID, &t.Status, &t.Paused, &t.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := insertTaskRelations(tx, t.ID, opts.SourceTaskIDs); err != nil {
|
||||
@@ -413,11 +427,11 @@ func insertTaskLLMProfiles(tx *sql.Tx, taskID int64, profileIDs []int64) error {
|
||||
|
||||
const taskCols = `id, COALESCE(name,''), remark, category_id,
|
||||
COALESCE((SELECT category.name FROM task_categories category WHERE category.id=tasks.category_id),''),
|
||||
description, goal, exploration_id, status, paused, COALESCE(pause_reason,''), queued, queued_at, COALESCE(queue_mode,''), llm_profile_id, active_llm_profile_id, COALESCE(parent_ref,''), pinned_at, created_at, completed_at, COALESCE(timeout_seconds,0), COALESCE(plan_heartbeat_seconds,300), COALESCE(coverage_enabled,true), share_global_assets, COALESCE(worker_count,0), first_run_at, deadline_at, COALESCE(active_run_seconds,0), run_segment_started_at`
|
||||
description, goal, exploration_id, status, paused, COALESCE(pause_reason,''), queued, queued_at, COALESCE(queue_mode,''), llm_profile_id, active_llm_profile_id, COALESCE(parent_ref,''), pinned_at, created_at, completed_at, COALESCE(timeout_seconds,0), COALESCE(plan_heartbeat_seconds,300), COALESCE(coverage_enabled,true), share_global_assets, COALESCE(worker_count,0), first_run_at, deadline_at, COALESCE(active_run_seconds,0), run_segment_started_at, no_result_seconds, no_result_min_findings, no_result_min_severity, no_result_base_seconds, no_result_checked_at, stop_reason`
|
||||
|
||||
func scanTask(sc interface{ Scan(...any) error }) (*Task, error) {
|
||||
var t Task
|
||||
if err := sc.Scan(&t.ID, &t.Name, &t.Remark, &t.CategoryID, &t.CategoryName, &t.Description, &t.Goal, &t.ExplorationID, &t.Status, &t.Paused, &t.PauseReason, &t.Queued, &t.QueuedAt, &t.QueueMode, &t.LLMProfileID, &t.ActiveLLMProfileID, &t.ParentRef, &t.PinnedAt, &t.CreatedAt, &t.CompletedAt, &t.TimeoutSeconds, &t.PlanHeartbeatSeconds, &t.CoverageEnabled, &t.ShareGlobalAssets, &t.WorkerCount, &t.FirstRunAt, &t.DeadlineAt, &t.ActiveRunSeconds, &t.RunSegmentStartedAt); err != nil {
|
||||
if err := sc.Scan(&t.ID, &t.Name, &t.Remark, &t.CategoryID, &t.CategoryName, &t.Description, &t.Goal, &t.ExplorationID, &t.Status, &t.Paused, &t.PauseReason, &t.Queued, &t.QueuedAt, &t.QueueMode, &t.LLMProfileID, &t.ActiveLLMProfileID, &t.ParentRef, &t.PinnedAt, &t.CreatedAt, &t.CompletedAt, &t.TimeoutSeconds, &t.PlanHeartbeatSeconds, &t.CoverageEnabled, &t.ShareGlobalAssets, &t.WorkerCount, &t.FirstRunAt, &t.DeadlineAt, &t.ActiveRunSeconds, &t.RunSegmentStartedAt, &t.NoResultSeconds, &t.NoResultMinFindings, &t.NoResultMinSeverity, &t.NoResultBaseSeconds, &t.NoResultCheckedAt, &t.StopReason); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.Pinned = t.PinnedAt != nil
|
||||
@@ -622,6 +636,7 @@ func (d *DB) SetStatusRuntime(id int64, status string) (int64, *time.Time, error
|
||||
err := d.QueryRow(`
|
||||
UPDATE tasks
|
||||
SET status = $1,
|
||||
stop_reason = CASE WHEN $1 IN ('done','failed') OR ($1 NOT IN ('done','failed','timeout') AND status IN ('done','failed','timeout')) THEN '' ELSE stop_reason END,
|
||||
pause_reason = CASE WHEN $1 IN ('done','failed','timeout') THEN '' ELSE pause_reason END,
|
||||
completed_at = CASE WHEN $1 IN ('done','failed','timeout') THEN COALESCE(completed_at, now()) ELSE NULL END,
|
||||
active_run_seconds = active_run_seconds + CASE WHEN $1 IN ('done','failed','timeout') AND run_segment_started_at IS NOT NULL THEN GREATEST(0, FLOOR(EXTRACT(EPOCH FROM (now() - run_segment_started_at)))::bigint) ELSE 0 END,
|
||||
@@ -646,15 +661,25 @@ func (d *DB) SetTerminalStatusGuarded(id int64, status string) (won bool, err er
|
||||
// SetTerminalStatusGuardedRuntime is the runtime-returning form used by the
|
||||
// Manager so it can mirror the terminal clock before any follow-up hydration.
|
||||
func (d *DB) SetTerminalStatusGuardedRuntime(id int64, status string) (active int64, started *time.Time, won bool, err error) {
|
||||
return d.SetTerminalStatusGuardedReasonRuntime(id, status, "")
|
||||
}
|
||||
|
||||
// SetTerminalStatusGuardedReasonRuntime commits the terminal status and its cause together.
|
||||
func (d *DB) SetTerminalStatusGuardedReasonRuntime(id int64, status, reason string) (active int64, started *time.Time, won bool, err error) {
|
||||
if status != "timeout" {
|
||||
reason = ""
|
||||
}
|
||||
|
||||
err = d.QueryRow(`
|
||||
UPDATE tasks
|
||||
SET status = $1,
|
||||
pause_reason = '',
|
||||
stop_reason = $3,
|
||||
completed_at = COALESCE(completed_at, now()),
|
||||
active_run_seconds = active_run_seconds + CASE WHEN run_segment_started_at IS NOT NULL THEN GREATEST(0, FLOOR(EXTRACT(EPOCH FROM (now() - run_segment_started_at)))::bigint) ELSE 0 END,
|
||||
run_segment_started_at = NULL
|
||||
WHERE id = $2 AND status NOT IN ('done','failed','timeout')
|
||||
RETURNING active_run_seconds, run_segment_started_at`, status, id).Scan(&active, &started)
|
||||
RETURNING active_run_seconds, run_segment_started_at`, status, id, reason).Scan(&active, &started)
|
||||
if err == sql.ErrNoRows {
|
||||
// Preserve the authoritative runtime fields for the losing terminal
|
||||
// writer. The guarded transition itself is still a no-op.
|
||||
|
||||
Reference in new issue
Block a user