统一AI分析入口及双任务安全确认,采用全量载入的可见行渲染,保留完整原文。 右侧非模态详情固定五项质量字段,清理冗余展示并对齐查询和同步按钮。 默认4并发由数据库准入与逐任务租约保护,保留共享限流冷却、截断归因和有界重试。 兼容真实引用标题字段,不伪造证据或准确率,不修改源生产问答与公司区域规则。 验证:完整make verify退出0,710项Go通过、124项已声明可选跳过且必需0跳过; 另全量mirror隔离PostgreSQL race退出0,AI单元race退出0。 真实本地浏览器通过六项交互、390px内滚动及显式AI部分失败/零缺口故障夹具。 治理原生备份已真实恢复,schema57、72表计数与29张QA内容哈希一致。 候选镜像、精确提交CI与正式上线验收待本次提交后执行,不宣称已部署。
This commit is contained in:
@@ -1,10 +1,13 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"io"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsai"
|
||||
@@ -16,6 +19,7 @@ import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestAIBatchManualRetryKeepsCumulativeAttemptsAndFixedDenominator(t *testing.T) {
|
||||
@@ -228,7 +232,8 @@ func newAIMatrix(t *testing.T, tenant string, handler func(http.ResponseWriter,
|
||||
var body struct {
|
||||
Messages []struct{ Content string } `json:"messages"`
|
||||
}
|
||||
if json.NewDecoder(r.Body).Decode(&body) != nil || len(body.Messages) != 2 {
|
||||
rawBody, readErr := io.ReadAll(r.Body)
|
||||
if readErr != nil || json.Unmarshal(rawBody, &body) != nil || len(body.Messages) != 2 {
|
||||
t.Error("invalid synthetic request")
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
@@ -238,6 +243,7 @@ func newAIMatrix(t *testing.T, tenant string, handler func(http.ResponseWriter,
|
||||
return
|
||||
}
|
||||
calls.Add(1)
|
||||
r.Body = io.NopCloser(bytes.NewReader(rawBody))
|
||||
if handler != nil {
|
||||
handler(w, r)
|
||||
return
|
||||
@@ -279,6 +285,221 @@ func (m aiMatrix) batch(t *testing.T, nonce string) qaopsai.Batch {
|
||||
}
|
||||
return batch
|
||||
}
|
||||
func TestAIRunnerActuallyDispatchesFourConcurrentRequests(t *testing.T) {
|
||||
entered := make(chan struct{}, 8)
|
||||
release := make(chan struct{})
|
||||
var once sync.Once
|
||||
m := newAIMatrix(t, "fixture-ai-runner-slots", func(w http.ResponseWriter, r *http.Request) {
|
||||
entered <- struct{}{}
|
||||
<-release
|
||||
writeAICompletion(w, `{"question_chinese":"MG400 如何连接?"}`)
|
||||
})
|
||||
seedParallelAIWork(t, m)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() { m.ai.Run(ctx, nil); close(done) }()
|
||||
defer func() { once.Do(func() { close(release) }); cancel(); <-done }()
|
||||
count := 0
|
||||
timer := time.NewTimer(2 * time.Second)
|
||||
defer timer.Stop()
|
||||
loop:
|
||||
for count < 4 {
|
||||
select {
|
||||
case <-entered:
|
||||
count++
|
||||
case <-timer.C:
|
||||
break loop
|
||||
}
|
||||
}
|
||||
if count != 4 {
|
||||
t.Fatalf("actual worker runner is still serial: concurrent=%d", count)
|
||||
}
|
||||
}
|
||||
|
||||
func seedParallelAIWork(t *testing.T, m aiMatrix) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
entries := []dobotaiops.MirrorRecord{}
|
||||
ids := []string{}
|
||||
for i, word := range []string{"Alpha", "Bravo", "Charlie", "Delta", "Echo"} {
|
||||
id := fmt.Sprintf("parallel-record-%d", i)
|
||||
entry := fixtureEntry(id, "fixture answer")
|
||||
var wire map[string]any
|
||||
_ = json.Unmarshal(entry.Payload, &wire)
|
||||
wire["question"] = "How do I connect MG400? " + word
|
||||
entry.Payload, _ = json.Marshal(wire)
|
||||
entries = append(entries, entry)
|
||||
ids = append(ids, id)
|
||||
}
|
||||
var seedJob string
|
||||
if m.pool.QueryRow(ctx, `SELECT id FROM jobs WHERE type=$1 AND state='running'`, m.master.SyncJobType()).Scan(&seedJob) != nil {
|
||||
t.Fatal("seed lease unavailable")
|
||||
}
|
||||
if e := pg.NewStore(m.pool).Complete(ctx, seedJob, "fixture-sync-worker", time.Now()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
job := claimMirrorJob(t, m.master, pg.NewStore(m.pool), "parallel-seed")
|
||||
if e := m.master.HandleSync(ctx, *job, func(context.Context) (Source, error) { return &fixtureSource{rows: entries}, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
preview, e := m.ai.Preview(ctx, qaopsai.Scope{Kind: "translation", IDs: ids}, "fixture-admin")
|
||||
if e != nil || preview.Eligible != 5 {
|
||||
t.Fatal("five unique inputs unavailable", e, preview.Eligible)
|
||||
}
|
||||
if _, e = m.ai.Start(ctx, preview.ID, strings.Repeat("parallel", 4), "fixture-admin"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAIParallelClaimsUseFourSlotsWithoutDuplicatingOrExceedingLimit(t *testing.T) {
|
||||
entered := make(chan struct{}, 8)
|
||||
release := make(chan struct{})
|
||||
var once sync.Once
|
||||
m := newAIMatrix(t, "fixture-ai-four-slots", func(w http.ResponseWriter, r *http.Request) {
|
||||
entered <- struct{}{}
|
||||
<-release
|
||||
writeAICompletion(w, `{"question_chinese":"MG400 如何连接?"}`)
|
||||
})
|
||||
defer once.Do(func() { close(release) })
|
||||
ctx := context.Background()
|
||||
seedParallelAIWork(t, m)
|
||||
var group sync.WaitGroup
|
||||
failures := make(chan error, 5)
|
||||
for i := 0; i < 5; i++ {
|
||||
group.Add(1)
|
||||
go func() {
|
||||
defer group.Done()
|
||||
_, err := m.ai.ProcessOne(ctx)
|
||||
if err != nil {
|
||||
failures <- err
|
||||
}
|
||||
}()
|
||||
}
|
||||
seen := 0
|
||||
timeout := time.NewTimer(1500 * time.Millisecond)
|
||||
loop:
|
||||
for seen < 4 {
|
||||
select {
|
||||
case <-entered:
|
||||
seen++
|
||||
case <-timeout.C:
|
||||
break loop
|
||||
}
|
||||
}
|
||||
timeout.Stop()
|
||||
if seen != 4 {
|
||||
t.Errorf("wanted four concurrent model requests before any completes; got %d", seen)
|
||||
}
|
||||
select {
|
||||
case <-entered:
|
||||
t.Error("exceeded four global slots")
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
once.Do(func() { close(release) })
|
||||
group.Wait()
|
||||
close(failures)
|
||||
for err := range failures {
|
||||
t.Error(err)
|
||||
}
|
||||
if seen == 4 {
|
||||
var running, queued, outputs int
|
||||
if m.pool.QueryRow(ctx, `SELECT (SELECT count(*)FROM qa_ops_ai_work WHERE tenant_key=$1 AND state='running'),(SELECT count(*)FROM qa_ops_ai_work WHERE tenant_key=$1 AND state='queued'),(SELECT count(*)FROM qa_ops_ai_outputs WHERE tenant_key=$1)`, m.tenant).Scan(&running, &queued, &outputs) != nil || running != 0 || queued != 1 || outputs != 4 {
|
||||
t.Fatal("slot completion lost/duplicated work", running, queued, outputs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAITruncationRetriesExpandBudgetAndStopAfterThreeAttempts(t *testing.T) {
|
||||
budgets := []int{}
|
||||
m := newAIMatrix(t, "fixture-ai-truncation-budget", func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Max int `json:"max_tokens"`
|
||||
}
|
||||
if json.NewDecoder(r.Body).Decode(&req) != nil {
|
||||
t.Error("request decode")
|
||||
}
|
||||
budgets = append(budgets, req.Max)
|
||||
if len(budgets) < 3 {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"model": "fixture", "choices": []any{map[string]any{"finish_reason": "length", "message": map[string]string{"content": ""}}}})
|
||||
return
|
||||
}
|
||||
writeAICompletion(w, `{"question_chinese":"MG400 如何连接?"}`)
|
||||
})
|
||||
batch := m.batch(t, "t")
|
||||
ctx := context.Background()
|
||||
for i := 0; i < 3; i++ {
|
||||
if _, err := m.pool.Exec(ctx, `UPDATE qa_ops_ai_work SET available_at=clock_timestamp()-interval '1 second'WHERE tenant_key=$1`, m.tenant); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if worked, err := m.ai.ProcessOne(ctx); err != nil || !worked {
|
||||
t.Fatal("bounded retry did not execute", err)
|
||||
}
|
||||
}
|
||||
if fmt.Sprint(budgets) != "[4096 8192 16384]" {
|
||||
t.Fatal("truncation budget did not grow", budgets)
|
||||
}
|
||||
current, err := m.ai.GetBatch(ctx, batch.ID)
|
||||
if err != nil || current.Succeeded != 1 || current.Total != 1 || m.calls.Load() != 3 {
|
||||
t.Fatal("retry denominator or completion", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAIParallelSuccessCannotClearAnotherRequestsRateLimit(t *testing.T) {
|
||||
entered := make(chan struct{}, 4)
|
||||
release := make(chan struct{})
|
||||
var once sync.Once
|
||||
var calls atomic.Int32
|
||||
m := newAIMatrix(t, "fixture-ai-shared-cooldown", func(w http.ResponseWriter, r *http.Request) {
|
||||
n := calls.Add(1)
|
||||
entered <- struct{}{}
|
||||
if n == 4 {
|
||||
w.Header().Set("Retry-After", "45")
|
||||
w.WriteHeader(429)
|
||||
return
|
||||
}
|
||||
<-release
|
||||
writeAICompletion(w, `{"question_chinese":"MG400 如何连接?"}`)
|
||||
})
|
||||
defer once.Do(func() { close(release) })
|
||||
seedParallelAIWork(t, m)
|
||||
ctx := context.Background()
|
||||
var group sync.WaitGroup
|
||||
errs := make(chan error, 4)
|
||||
for i := 0; i < 4; i++ {
|
||||
group.Add(1)
|
||||
go func() { defer group.Done(); _, err := m.ai.ProcessOne(ctx); errs <- err }()
|
||||
}
|
||||
for i := 0; i < 4; i++ {
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("four parallel slots not reached")
|
||||
}
|
||||
}
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
remaining := 0.0
|
||||
for time.Now().Before(deadline) {
|
||||
if m.pool.QueryRow(ctx, `SELECT EXTRACT(EPOCH FROM next_request_at-clock_timestamp())::double precision FROM qa_ops_ai_runtime WHERE tenant_key=$1`, m.tenant).Scan(&remaining) == nil && remaining > 40 {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Millisecond * 10)
|
||||
}
|
||||
once.Do(func() { close(release) })
|
||||
group.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if m.pool.QueryRow(ctx, `SELECT EXTRACT(EPOCH FROM next_request_at-clock_timestamp())::double precision FROM qa_ops_ai_runtime WHERE tenant_key=$1`, m.tenant).Scan(&remaining) != nil || remaining < 40 {
|
||||
t.Fatal("success cleared shared provider cooldown", remaining)
|
||||
}
|
||||
if worked, err := m.ai.ProcessOne(ctx); err != nil || worked || calls.Load() != 4 {
|
||||
t.Fatal("new request bypassed shared rate limit", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAIManualBatchPauseResumeKeepsSharedWorkAndActionReplaysSafe(t *testing.T) {
|
||||
m := newAIMatrix(t, "fixture-ai-pause", nil)
|
||||
ctx := context.Background()
|
||||
|
||||
Reference in New Issue
Block a user