From e4f79999a15ab32bad41780b75028d7ed0431efb Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 8 Nov 2026 21:17:25 +0800 Subject: [PATCH 1/4] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=E5=8F=96?= =?UTF-8?q?=E6=B6=88=E5=B0=9A=E6=9C=AA=E6=89=A7=E8=A1=8C=E7=9A=84=20AI=20?= =?UTF-8?q?=E8=BF=90=E7=BB=B4=E5=86=BB=E7=BB=93=E6=8F=90=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/ai-ops-screenshot.mjs | 23 ++++- .github/workflows/ai-ops.yml | 21 ++++- .../handler/admin/ops_ai_control_handler.go | 30 +++++++ .../admin/ops_ai_control_handler_test.go | 32 +++++++ backend/internal/repository/ai_ops.go | 48 ++++++++++ .../repository/ai_ops_integration_test.go | 87 +++++++++++++++++++ backend/internal/repository/ai_ops_test.go | 63 ++++++++++++++ backend/internal/server/routes/admin.go | 1 + backend/internal/service/ai_ops_types.go | 3 + .../migrations/337_ai_ops_proposal_cancel.sql | 5 ++ docs/ai-ops-codex.md | 15 +++- .../api/admin/__tests__/aiOpsControl.spec.ts | 7 ++ frontend/src/api/admin/aiOpsControl.ts | 7 +- .../admin/operations/AIOpsControls.vue | 25 +++++- .../__tests__/AIOpsControls.spec.ts | 27 +++++- .../common/__tests__/NewFeatureBadge.spec.ts | 1 + frontend/src/constants/newFeatureNotices.ts | 1 + frontend/src/i18n/locales/en/aiOpsControl.ts | 3 + frontend/src/i18n/locales/zh/aiOpsControl.ts | 3 + 19 files changed, 393 insertions(+), 9 deletions(-) create mode 100644 backend/migrations/337_ai_ops_proposal_cancel.sql diff --git a/.github/scripts/ai-ops-screenshot.mjs b/.github/scripts/ai-ops-screenshot.mjs index 35a7e725e653..dc3217e784a6 100644 --- a/.github/scripts/ai-ops-screenshot.mjs +++ b/.github/scripts/ai-ops-screenshot.mjs @@ -41,7 +41,8 @@ export const aiOpsControlAPI = { async actions(){record('actions',[]);return {items:copy(records),total:records.length};}, async probes(){record('probes',[]);return {items:[],total:0};}, async preview(id,index){record('preview',[id,index]);if(id!==run.id||index!==0)throw new Error('wrong_candidate');return copy(proposal);}, - async apply(id,digest){if(id!==proposal.id||digest!==proposal.digest)throw new Error('wrong_digest');globalThis.__aiOpsFixture.mutations.push({kind:'apply',id,digest});const action={id:'synthetic-action-a',proposal_id:id,run_id:run.id,action:'set_concurrency',account_id:3,before_value:10,after_value:9,status:'propagation_pending',created_at:now,updated_at:now,observe_until:until,owner_revision:9,target_revision:8,reason_code:'',auto:false};records.push(action);return copy(action);}, + async cancel(id,digest){if(id!==proposal.id||digest!==proposal.digest)throw new Error('wrong_digest');proposal.status='cancelled';globalThis.__aiOpsFixture.mutations.push({kind:'cancel',id,digest});return copy(proposal);}, + async apply(id,digest){if(proposal.status!=='ready'||id!==proposal.id||digest!==proposal.digest)throw new Error('wrong_digest');globalThis.__aiOpsFixture.mutations.push({kind:'apply',id,digest});const action={id:'synthetic-action-a',proposal_id:id,run_id:run.id,action:'set_concurrency',account_id:3,before_value:10,after_value:9,status:'propagation_pending',created_at:now,updated_at:now,observe_until:until,owner_revision:9,target_revision:8,reason_code:'',auto:false};records.push(action);return copy(action);}, async savePolicy(){globalThis.__aiOpsFixture.mutations.push({kind:'save'});throw new Error('unexpected_policy_write');}, async halt(){globalThis.__aiOpsFixture.mutations.push({kind:'halt'});return {...copy(policy),halted:true,revision:6};}, async rollback(){globalThis.__aiOpsFixture.mutations.push({kind:'rollback'});throw new Error('unexpected_rollback');}, @@ -168,12 +169,30 @@ try { const verification = await page.evaluate(() => globalThis.__aiOpsFixture) if (verification.mutations.length !== 1 || verification.mutations[0].kind !== 'apply' || verification.mutations[0].digest !== 'd'.repeat(64)) throw new Error('invalid_explicit_approval') if (verification.paidCalls.length || blocked.length || errors.length) throw new Error('unexpected_paid_or_network_calls_or_browser_error') + await page.goto('http://127.0.0.1:4185/admin/ai-ops?scenario=cancel', { waitUntil: 'networkidle' }) + await page.getByTestId('ai-ops-summary').waitFor() + await page.getByTestId('ai-control-advanced').locator(':scope > summary').click() + await page.getByTestId('ai-control-preview-0').click() + await page.getByTestId('ai-control-frozen').waitFor() + await page.getByTestId('ai-control-cancel').click() + await page.getByTestId('ai-control-cancel').waitFor({ state: 'hidden' }) + if (!(await page.getByTestId('ai-control-apply').isDisabled())) throw new Error('cancelled_proposal_can_apply') + await page.screenshot({ path: path.join(output, 'cancelled-mobile-synthetic.png'), fullPage: true }) + await recordMobileWidth(page) + await page.setViewportSize({ width: 1440, height: 1100 }) + await page.screenshot({ path: path.join(output, 'cancelled-desktop-synthetic.png'), fullPage: true }) + await page.getByTestId('ai-control-preview-0').click() + await page.getByTestId('ai-control-frozen').waitFor() + if (await page.getByTestId('ai-control-cancel').count() || !(await page.getByTestId('ai-control-apply').isDisabled())) throw new Error('repreview_revived_cancelled_proposal') + const cancellation = await page.evaluate(() => globalThis.__aiOpsFixture) + if (cancellation.mutations.length !== 1 || cancellation.mutations[0].kind !== 'cancel' || cancellation.mutations[0].digest !== 'd'.repeat(64) || cancellation.paidCalls.length) throw new Error('invalid_proposal_cancellation') + if (blocked.length || errors.length) throw new Error('unexpected_cancellation_network_or_browser_error') await fs.writeFile(path.join(output, 'verification.json'), JSON.stringify({ commit: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim(), synthetic: true, actualComponents: ['AIOpsView.vue', 'AIOpsReport.vue', 'AIOpsControls.vue', 'AIOpsRecoveryProbes.vue', 'SmartOpsNav.vue'], defaultDetailsCollapsed: ['ai-ops-history', 'ai-control-advanced', 'ai-ops-report-details'], activeEmergencyHaltVisible: true, disabledExecutionHaltHidden: true, cooldownBlocksConsentedSubmission: true, - frozenPreviewPreservedAcrossCollapse: true, + frozenPreviewPreservedAcrossCollapse: true, cancelledProposalCannotApplyOrRevive: true, cancellationMutations: cancellation.mutations, disabledSideEffects: 0, observeSideEffects: 0, cooldownSideEffects: 0, unapprovedWrites: 0, confirmedSyntheticMutations: verification.mutations, paidRequests: 0, productionApiCalls: 0, browserErrors: errors, blockedRequests: blocked, mobileWidths: widths, }, null, 2)) diff --git a/.github/workflows/ai-ops.yml b/.github/workflows/ai-ops.yml index 4216abe74384..d7344e22e0b2 100644 --- a/.github/workflows/ai-ops.yml +++ b/.github/workflows/ai-ops.yml @@ -39,7 +39,7 @@ jobs: - run: pnpm --dir frontend install --frozen-lockfile - name: AI operations component and API boundaries working-directory: frontend - run: pnpm exec vitest run src/views/admin/__tests__/AIOpsView.spec.ts src/components/admin/operations/__tests__/AIOpsControls.spec.ts src/components/admin/operations/__tests__/AIOpsRecoveryProbes.spec.ts src/api/admin/__tests__/aiOps.spec.ts src/api/admin/__tests__/aiOpsControl.spec.ts src/components/admin/operations/__tests__/SmartOpsNav.spec.ts --maxWorkers=1 --minWorkers=1 --no-file-parallelism + run: pnpm exec vitest run src/views/admin/__tests__/AIOpsView.spec.ts src/components/admin/operations/__tests__/AIOpsControls.spec.ts src/components/admin/operations/__tests__/AIOpsRecoveryProbes.spec.ts src/api/admin/__tests__/aiOps.spec.ts src/api/admin/__tests__/aiOpsControl.spec.ts src/components/admin/operations/__tests__/SmartOpsNav.spec.ts src/components/common/__tests__/NewFeatureBadge.spec.ts --maxWorkers=1 --minWorkers=1 --no-file-parallelism - name: Frontend typecheck run: pnpm --dir frontend run typecheck - name: Install isolated synthetic browser @@ -57,3 +57,22 @@ jobs: name: ai-ops-ui-${{ github.event.pull_request.head.sha || github.sha }} path: ${{ runner.temp }}/ai-ops-screenshots if-no-files-found: warn + proposal-cancellation: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Cancellation authorization and ledger boundaries + working-directory: backend + run: go test -race -tags=unit ./internal/repository ./internal/handler/admin -run '^TestAIOpsCancel' -count=1 -v -timeout=5m + - name: PostgreSQL cancellation, replay and concurrent execution + working-directory: backend + env: + CI: 'true' + run: go test -race -tags=integration ./internal/repository -run '^TestAIOpsPostgres(Cancel|ConcurrentCancel)' -count=1 -v -timeout=10m diff --git a/backend/internal/handler/admin/ops_ai_control_handler.go b/backend/internal/handler/admin/ops_ai_control_handler.go index 3e34c72db5a6..6a03663d8c34 100644 --- a/backend/internal/handler/admin/ops_ai_control_handler.go +++ b/backend/internal/handler/admin/ops_ai_control_handler.go @@ -207,6 +207,36 @@ func (h *OpsHandler) ApplyAIOpsProposal(c *gin.Context) { response.Success(c, action) } +func (h *OpsHandler) CancelAIOpsProposal(c *gin.Context) { + // Revoking an unapplied proposal remains available while execution is disabled. + repo, ok := h.aiOpsControl(c, false) + if !ok { + return + } + id, err := uuid.Parse(c.Param("id")) + if err != nil || id.String() != c.Param("id") { + response.BadRequest(c, "Invalid proposal ID") + return + } + var input struct { + Digest string `json:"digest"` + } + if !aiOpsDecode(c, &input, 1024) { + return + } + if !aiOpsDigestPattern.MatchString(input.Digest) { + response.BadRequest(c, "Confirm the exact frozen proposal digest") + return + } + proposal, err := repo.CancelAIOpsProposal(c.Request.Context(), id.String(), input.Digest, aiOpsActor(c)) + if err != nil { + aiOpsControlError(c, err) + return + } + middleware.SetAuditExtra(c, map[string]any{"source": "human_cancelled_ai_ops", "event_id": proposal.ID}) + response.Success(c, proposal) +} + func (h *OpsHandler) ListAIOpsActions(c *gin.Context) { repo, ok := h.aiOpsControl(c, false) if !ok { diff --git a/backend/internal/handler/admin/ops_ai_control_handler_test.go b/backend/internal/handler/admin/ops_ai_control_handler_test.go index 977d58efca05..96b8d957bc62 100644 --- a/backend/internal/handler/admin/ops_ai_control_handler_test.go +++ b/backend/internal/handler/admin/ops_ai_control_handler_test.go @@ -40,6 +40,7 @@ func newAIOpsControlRouter(repo *aiOpsControlRepoStub) (*gin.Engine, *OpsHandler router := aiOpsTestRouter(h, "admin", nil) router.POST("/preview", h.PreviewAIOpsProposal) router.POST("/apply/:id", h.ApplyAIOpsProposal) + router.POST("/cancel/:id", h.CancelAIOpsProposal) return router, h } @@ -115,3 +116,34 @@ func TestAIOpsControlRoutesRequireFullAdmin(t *testing.T) { } } } + +func (r *aiOpsControlRepoStub) CancelAIOpsProposal(context.Context, string, string, int64) (service.AIOpsProposal, error) { + r.calls++ + return service.AIOpsProposal{ID: aiOpsTestID, Status: "cancelled"}, nil +} + +func TestAIOpsCancelNeedsFullAdminAndExactDigestButNotExecutionGate(t *testing.T) { + t.Setenv("SUB2API_AI_OPS_CONTROL_ENABLED", "false") + repo := &aiOpsControlRepoStub{} + router, h := newAIOpsControlRouter(repo) + for _, body := range []string{`{}`, `{"digest":"bad"}`, `{"digest":"` + strings.Repeat("a", 64) + `","account_id":1}`} { + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/cancel/"+aiOpsTestID, strings.NewReader(body))) + if w.Code != http.StatusBadRequest || repo.calls != 0 { + t.Fatal("malformed cancellation reached repository") + } + } + body := `{"digest":"` + strings.Repeat("a", 64) + `"}` + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/cancel/"+aiOpsTestID, strings.NewReader(body))) + if w.Code != http.StatusOK || repo.calls != 1 { + t.Fatal("execution gate blocked safe proposal cancellation") + } + observer := aiOpsTestRouter(h, "observer", nil) + observer.POST("/cancel/:id", h.CancelAIOpsProposal) + w = httptest.NewRecorder() + observer.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/cancel/"+aiOpsTestID, strings.NewReader(body))) + if w.Code != http.StatusForbidden || repo.calls != 1 { + t.Fatal("observer cancelled a proposal") + } +} diff --git a/backend/internal/repository/ai_ops.go b/backend/internal/repository/ai_ops.go index b74dda3ec5a3..1324e97a4065 100644 --- a/backend/internal/repository/ai_ops.go +++ b/backend/internal/repository/ai_ops.go @@ -592,6 +592,54 @@ func saveAIOpsAction(ctx context.Context, tx *sql.Tx, a service.AIOpsAction) err return err } +// Cancellation uses the same global transaction and proposal row lock as apply. +// It only revokes a frozen proposal; an existing action requires its own rollback. +func (r *accountRepository) CancelAIOpsProposal(ctx context.Context, id, digest string, actorID int64) (service.AIOpsProposal, error) { + if _, err := uuid.Parse(id); err != nil { + return service.AIOpsProposal{}, service.ErrAIOpsBlocked + } + ctx, cancel := context.WithTimeout(ctx, 6*time.Second) + defer cancel() + tx, err := r.aiOpsTx(ctx) + if err != nil { + return service.AIOpsProposal{}, err + } + defer func() { _ = tx.Rollback() }() + proposal, err := readAIOpsProposal(ctx, tx, id) + if errors.Is(err, sql.ErrNoRows) { + return proposal, service.ErrAIOpsConflict + } + if err != nil { + return proposal, err + } + if digest == "" || proposal.Digest != digest { + return proposal, service.ErrAIOpsConflict + } + if proposal.Status == "cancelled" { + return proposal, tx.Commit() + } + if proposal.Status != "ready" && proposal.Status != "blocked" { + return proposal, service.ErrAIOpsConflict + } + var applied bool + if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM ai_ops_actions WHERE proposal_id=$1)`, id).Scan(&applied); err != nil { + return proposal, err + } + if applied { + return proposal, service.ErrAIOpsConflict + } + now := time.Now().UTC() + proposal.Status, proposal.CancelledAt, proposal.CancelledBy = "cancelled", &now, actorID + raw, err := json.Marshal(proposal) + if err != nil { + return proposal, err + } + if _, err = tx.ExecContext(ctx, `UPDATE ai_ops_proposals SET status='cancelled',data=$2 WHERE id=$1`, id, string(raw)); err != nil { + return proposal, err + } + return proposal, tx.Commit() +} + func (r *accountRepository) ApplyAIOps(ctx context.Context, id, digest string, actorID int64, automatic bool) (service.AIOpsAction, error) { if _, err := uuid.Parse(id); err != nil { return service.AIOpsAction{}, service.ErrAIOpsBlocked diff --git a/backend/internal/repository/ai_ops_integration_test.go b/backend/internal/repository/ai_ops_integration_test.go index aea505211374..8d249ee20e68 100644 --- a/backend/internal/repository/ai_ops_integration_test.go +++ b/backend/internal/repository/ai_ops_integration_test.go @@ -476,3 +476,90 @@ func TestAIOpsPostgresApprovalRejectsChangedRequestBuckets(t *testing.T) { }) } } + +func TestAIOpsPostgresCancelledProposalCannotBeRevivedOrApplied(t *testing.T) { + f := aiOpsFullPGFixture(t) + ctx := context.Background() + in := service.AIOpsPreviewInput{RunID: uuid.NewString(), Action: "set_concurrency", AccountID: f.target, ProposedValue: aiOpsFloat(18), EvidenceObservedAt: time.Now().UTC()} + p, err := f.repo.PreviewAIOps(ctx, in, f.actor) + require.NoError(t, err) + require.Equal(t, "ready", p.Status) + cancelled, err := f.repo.CancelAIOpsProposal(ctx, p.ID, p.Digest, f.actor) + require.NoError(t, err) + require.Equal(t, "cancelled", cancelled.Status) + require.NotNil(t, cancelled.CancelledAt) + _, err = f.repo.ApplyAIOps(ctx, p.ID, p.Digest, f.actor, false) + require.ErrorIs(t, err, service.ErrAIOpsConflict) + _, err = f.repo.ApplyAIOps(ctx, p.ID, p.Digest, 0, true) + require.ErrorIs(t, err, service.ErrAIOpsConflict) + repeated, err := f.repo.CancelAIOpsProposal(ctx, p.ID, p.Digest, f.actor+1) + require.NoError(t, err) + require.Equal(t, cancelled.CancelledBy, repeated.CancelledBy) + require.Equal(t, cancelled.CancelledAt, repeated.CancelledAt) + repreview, err := f.repo.PreviewAIOps(ctx, in, f.actor) + require.NoError(t, err) + require.Equal(t, p.ID, repreview.ID) + require.Equal(t, "cancelled", repreview.Status) + var concurrency, actions int + require.NoError(t, integrationDB.QueryRow(`SELECT concurrency FROM accounts WHERE id=$1`, f.target).Scan(&concurrency)) + require.Equal(t, 20, concurrency) + require.NoError(t, integrationDB.QueryRow(`SELECT count(*) FROM ai_ops_actions WHERE proposal_id=$1`, p.ID).Scan(&actions)) + require.Zero(t, actions) +} + +func TestAIOpsPostgresCancellationCannotUndoAnAppliedAction(t *testing.T) { + f := aiOpsFullPGFixture(t) + ctx := context.Background() + p, err := f.repo.PreviewAIOps(ctx, service.AIOpsPreviewInput{RunID: uuid.NewString(), Action: "set_concurrency", AccountID: f.target, ProposedValue: aiOpsFloat(18), EvidenceObservedAt: time.Now().UTC()}, f.actor) + require.NoError(t, err) + action, err := f.repo.ApplyAIOps(ctx, p.ID, p.Digest, f.actor, false) + require.NoError(t, err) + _, err = f.repo.CancelAIOpsProposal(ctx, p.ID, p.Digest, f.actor) + require.ErrorIs(t, err, service.ErrAIOpsConflict) + var concurrency int + require.NoError(t, integrationDB.QueryRow(`SELECT concurrency FROM accounts WHERE id=$1`, f.target).Scan(&concurrency)) + require.Equal(t, 18, concurrency) + repeated, err := f.repo.ApplyAIOps(ctx, p.ID, p.Digest, f.actor, false) + require.NoError(t, err) + require.Equal(t, action.ID, repeated.ID) +} + +func TestAIOpsPostgresConcurrentCancelAndApplyHaveOneWinner(t *testing.T) { + f := aiOpsFullPGFixture(t) + ctx := context.Background() + p, err := f.repo.PreviewAIOps(ctx, service.AIOpsPreviewInput{RunID: uuid.NewString(), Action: "set_concurrency", AccountID: f.target, ProposedValue: aiOpsFloat(18), EvidenceObservedAt: time.Now().UTC()}, f.actor) + require.NoError(t, err) + require.Equal(t, "ready", p.Status) + // Separate repositories have no in-process synchronization; the shared SQL + // transaction/row locks must decide which operation can persist. + other := &accountRepository{sql: integrationDB} + start := make(chan struct{}) + cancelResult, applyResult := make(chan error, 1), make(chan error, 1) + go func() { + <-start + _, cancelErr := f.repo.CancelAIOpsProposal(ctx, p.ID, p.Digest, f.actor) + cancelResult <- cancelErr + }() + go func() { + <-start + _, applyErr := other.ApplyAIOps(ctx, p.ID, p.Digest, f.actor, false) + applyResult <- applyErr + }() + close(start) + cancelErr, applyErr := <-cancelResult, <-applyResult + require.NotEqual(t, cancelErr == nil, applyErr == nil, "exactly one operation must commit: cancel=%v apply=%v", cancelErr, applyErr) + var status string + var count, concurrency int + require.NoError(t, integrationDB.QueryRow(`SELECT status FROM ai_ops_proposals WHERE id=$1`, p.ID).Scan(&status)) + require.NoError(t, integrationDB.QueryRow(`SELECT count(*) FROM ai_ops_actions WHERE proposal_id=$1`, p.ID).Scan(&count)) + require.NoError(t, integrationDB.QueryRow(`SELECT concurrency FROM accounts WHERE id=$1`, f.target).Scan(&concurrency)) + if cancelErr == nil { + require.Equal(t, "cancelled", status) + require.Zero(t, count) + require.Equal(t, 20, concurrency) + } else { + require.Equal(t, "applied", status) + require.Equal(t, 1, count) + require.Equal(t, 18, concurrency) + } +} diff --git a/backend/internal/repository/ai_ops_test.go b/backend/internal/repository/ai_ops_test.go index 1e49ec665219..09e5759e6872 100644 --- a/backend/internal/repository/ai_ops_test.go +++ b/backend/internal/repository/ai_ops_test.go @@ -257,3 +257,66 @@ func TestAIOpsEligibilityRejectsTransportsRecoveryCannotProbe(t *testing.T) { require.NoError(t, m.ExpectationsWereMet()) } } + +func TestAIOpsCancelIsIdempotentAndDoesNotMutateAnAccount(t *testing.T) { + for _, status := range []string{"ready", "blocked", "cancelled", "applied", "expired", "conflict"} { + t.Run(status, func(t *testing.T) { + db, m, err := sqlmock.New() + require.NoError(t, err) + defer func() { _ = db.Close() }() + p := service.AIOpsProposal{ID: "4447dc20-c3eb-4f5a-87ba-adfc91509b8c", Digest: "fixed", Status: status} + if status == "cancelled" { + now := time.Now().UTC() + p.CancelledAt, p.CancelledBy = &now, 41 + } + aiOpsExpectTx(m) + m.ExpectQuery("SELECT data FROM ai_ops_proposals.*FOR UPDATE").WithArgs(p.ID).WillReturnRows(sqlmock.NewRows([]string{"data"}).AddRow(aiOpsJSON(p))) + switch status { + case "ready", "blocked": + m.ExpectQuery("SELECT EXISTS.*ai_ops_actions").WithArgs(p.ID).WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false)) + m.ExpectExec("UPDATE ai_ops_proposals SET status='cancelled'").WithArgs(p.ID, sqlmock.AnyArg()).WillReturnResult(sqlmock.NewResult(0, 1)) + m.ExpectCommit() + case "cancelled": + m.ExpectCommit() + default: + m.ExpectRollback() + } + r := &accountRepository{sql: db} + got, err := r.CancelAIOpsProposal(context.Background(), p.ID, p.Digest, 9) + if status == "ready" || status == "blocked" { + require.NoError(t, err) + require.Equal(t, "cancelled", got.Status) + require.Equal(t, int64(9), got.CancelledBy) + require.NotNil(t, got.CancelledAt) + } else if status == "cancelled" { + require.NoError(t, err) + require.Equal(t, int64(41), got.CancelledBy, "retry preserves original audit actor") + require.WithinDuration(t, *p.CancelledAt, *got.CancelledAt, time.Microsecond) + } else { + require.ErrorIs(t, err, service.ErrAIOpsConflict) + } + require.NoError(t, m.ExpectationsWereMet()) + }) + } +} + +func TestAIOpsCancelRejectsAnotherDigestAndExistingAction(t *testing.T) { + for _, wrongDigest := range []bool{true, false} { + db, m, err := sqlmock.New() + require.NoError(t, err) + r := &accountRepository{sql: db} + p := service.AIOpsProposal{ID: "4447dc20-c3eb-4f5a-87ba-adfc91509b8c", Digest: "fixed", Status: "ready"} + aiOpsExpectTx(m) + m.ExpectQuery("SELECT data FROM ai_ops_proposals.*FOR UPDATE").WithArgs(p.ID).WillReturnRows(sqlmock.NewRows([]string{"data"}).AddRow(aiOpsJSON(p))) + digest := "other" + if !wrongDigest { + digest = p.Digest + m.ExpectQuery("SELECT EXISTS.*ai_ops_actions").WithArgs(p.ID).WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true)) + } + m.ExpectRollback() + _, err = r.CancelAIOpsProposal(context.Background(), p.ID, digest, 9) + require.ErrorIs(t, err, service.ErrAIOpsConflict) + require.NoError(t, m.ExpectationsWereMet()) + require.NoError(t, db.Close()) + } +} diff --git a/backend/internal/server/routes/admin.go b/backend/internal/server/routes/admin.go index 115bf9c23eb5..71a46b69c09c 100644 --- a/backend/internal/server/routes/admin.go +++ b/backend/internal/server/routes/admin.go @@ -266,6 +266,7 @@ func registerOpsRoutes(admin *gin.RouterGroup, h *handler.Handlers) { ops.POST("/ai/halt", h.Admin.Ops.HaltAIOps) ops.POST("/ai/proposals/preview", h.Admin.Ops.PreviewAIOpsProposal) ops.POST("/ai/proposals/:id/apply", h.Admin.Ops.ApplyAIOpsProposal) + ops.POST("/ai/proposals/:id/cancel", h.Admin.Ops.CancelAIOpsProposal) ops.GET("/ai/actions", h.Admin.Ops.ListAIOpsActions) ops.POST("/ai/actions/:id/rollback", h.Admin.Ops.RollbackAIOpsAction) ops.GET("/ai/probes", h.Admin.Ops.ListAIOpsProbes) diff --git a/backend/internal/service/ai_ops_types.go b/backend/internal/service/ai_ops_types.go index 1ac580394202..754920930f01 100644 --- a/backend/internal/service/ai_ops_types.go +++ b/backend/internal/service/ai_ops_types.go @@ -92,6 +92,8 @@ type AIOpsProposal struct { ExpiresAt time.Time `json:"expires_at"` CreatedAt time.Time `json:"created_at"` Status string `json:"status"` + CancelledAt *time.Time `json:"cancelled_at,omitempty"` + CancelledBy int64 `json:"cancelled_by,omitempty"` BlockedReasons []string `json:"blocked_reasons"` Evidence AIOpsEvidenceSnapshot `json:"evidence"` ImpactGroupIDs []int64 `json:"impact_group_ids"` @@ -144,6 +146,7 @@ type AIOpsRepository interface { HaltAIOps(context.Context, int64) (AIOpsPolicy, error) PreviewAIOps(context.Context, AIOpsPreviewInput, int64) (AIOpsProposal, error) ApplyAIOps(context.Context, string, string, int64, bool) (AIOpsAction, error) + CancelAIOpsProposal(context.Context, string, string, int64) (AIOpsProposal, error) RollbackAIOps(context.Context, string, int64, int64) (AIOpsAction, error) ListAIOpsActions(context.Context) ([]AIOpsAction, error) ReconcileAIOps(context.Context) error diff --git a/backend/migrations/337_ai_ops_proposal_cancel.sql b/backend/migrations/337_ai_ops_proposal_cancel.sql new file mode 100644 index 000000000000..beefdac73587 --- /dev/null +++ b/backend/migrations/337_ai_ops_proposal_cancel.sql @@ -0,0 +1,5 @@ +-- Cancellation revokes only an unapplied frozen proposal. Old binaries already +-- reject every status other than ready, so cancelled proposals remain fenced. +ALTER TABLE ai_ops_proposals DROP CONSTRAINT ai_ops_proposals_status_check; +ALTER TABLE ai_ops_proposals ADD CONSTRAINT ai_ops_proposals_status_check + CHECK(status IN ('ready','blocked','applied','expired','conflict','cancelled')); diff --git a/docs/ai-ops-codex.md b/docs/ai-ops-codex.md index 6eab87781b21..c840c4299270 100644 --- a/docs/ai-ops-codex.md +++ b/docs/ai-ops-codex.md @@ -68,7 +68,7 @@ AI暂停不会随重启、模型失联或时限到期自动解除。普通usage - 迁移333新增策略、提案、动作、暂停所有权和探针记录,以及账号配置revision触发器;用量/额度/票据等观测更新不应无故令配置revision失效。 - 生产操作仅full管理员,观察员、普通用户和受限管理密钥无权批准、执行、探针或回滚。Node采集身份仍只有读取权限。 -- 控制API位于 `/api/v1/admin/ops/ai/`:`policy`、`halt`、`proposals/preview`、`proposals/:id/apply`、`actions`、`actions/:id/rollback`、`probes`;写接口拒绝未知字段,不接受通用URL/指令/SQL。 +- 控制API位于 `/api/v1/admin/ops/ai/`:`policy`、`halt`、`proposals/preview`、`proposals/:id/apply`、`proposals/:id/cancel`、`actions`、`actions/:id/rollback`、`probes`;写接口拒绝未知字段,不接受通用URL/指令/SQL。 - 模型推理、真实探针、数据库及控制器的资源成本分别有预算;次数上限不能承诺供应商账单金额硬上限。 - 新功能提示共用 `ai-ops-codex-observe-initial-announcement`,不会因追加控制能力反复重置已关闭提示。 @@ -83,3 +83,16 @@ AI暂停不会随重启、模型失联或时限到期自动解除。普通usage 冻结证据同时记录模型、effort、协议、输入长度桶、缓存桶及输出长度桶。批准执行及效果比较要求前后这些条件一致;观察窗口不得包含传播确认前的请求。不同分桶、样本不足,或旧记录缺少分桶/传播确认时间,均显示效果未知,不能据此宣称成功或触发自动回滚。旧的未执行提案需重新预览;本次只扩充已有 JSON 数据,不增加数据库迁移。 当前比较仍是账号错误率检查,尚未实现 Issue #662 要求的全局 SLO、对照流量和 TTFT/TPS 联合验收;跨实例执行覆盖、实际隔离与真实模型验证也仍待完成。此处的保护不能作为开放自动执行的完整验收结论。 + + +### 取消冻结提案 + +人工预览后可以点击「取消冻结提案」。后端要求 full 管理员和本提案准确 digest,使用与执行相同的全局事务锁及提案行锁,持久标记 `cancelled` 并记录取消时间与操作人。取消本身只写 AI 运维元数据,控制开关关闭或策略急停时仍可调用;不会改账号、释放已执行动作预算或解除暂停。 + +同一提案取消可按原 ID/digest 幂等核对,刷新或再次预览同一 `run_id/proposal_index` 仍返回取消态。执行与取消并发时,只有一方可以提交;执行先完成则取消返回 conflict,必须按现有动作的所有权规则单独回滚。取消先完成则人工和自动执行都拒绝该提案。网络结果未知时不自动重试,先刷新,再按原诊断重新预览核对。 + +取消只作用于本次冻结提案,不取消诊断、不停止自动策略,也不禁止其他诊断或未来提案。需要停止全部新动作时使用急停。新增提示 ID 为 `ai-ops-proposal-cancel-initial-announcement`,与原 AI 运维公告独立,沿用当前管理员/浏览器本地隐藏规则。 + +迁移 337 仅扩展提案状态约束,取消审计保存在已有 JSON 数据中。旧二进制已有 `status != ready` 保护,回退后仍拒绝已取消提案;不要撤销状态约束或把取消态改回 ready。控制面混用旧版本时,旧节点可能显示原始状态文本且没有取消入口,升级所有管理节点后再使用新入口。 + +这是 #662 的部分交付。全局 SLO/对照流量/TTFT/TPS、累计参数与金额预算、单账号/参数锁定、真实 SDK 与隔离/跨节点验收仍未完成;取消提案不能作为开放自动执行或关闭整个提案的依据。 diff --git a/frontend/src/api/admin/__tests__/aiOpsControl.spec.ts b/frontend/src/api/admin/__tests__/aiOpsControl.spec.ts index 428f457245f5..9ad1797ee01e 100644 --- a/frontend/src/api/admin/__tests__/aiOpsControl.spec.ts +++ b/frontend/src/api/admin/__tests__/aiOpsControl.spec.ts @@ -15,6 +15,13 @@ describe('AI operations control API boundary', () => { ['/admin/ops/ai/proposals/proposal%2Fwith%3Fsegments/apply', { digest: 'digest', confirm: true }, { signal }], ]) }) + it('cancels only an exact frozen proposal without submitting an action', async () => { + const signal = new AbortController().signal + await aiOpsControlAPI.cancel('proposal/1', 'frozen-digest', signal) + expect(client.post.mock.calls).toEqual([ + ['/admin/ops/ai/proposals/proposal%2F1/cancel', { digest: 'frozen-digest' }, { signal }], + ]) + }) it('binds rollback to ownership revision and keeps halt body empty', async () => { const signal = new AbortController().signal await aiOpsControlAPI.rollback('action/1', 9, signal) diff --git a/frontend/src/api/admin/aiOpsControl.ts b/frontend/src/api/admin/aiOpsControl.ts index 98b6cc21d195..8457a07aa324 100644 --- a/frontend/src/api/admin/aiOpsControl.ts +++ b/frontend/src/api/admin/aiOpsControl.ts @@ -38,7 +38,9 @@ export interface AIOpsFrozenProposal { digest: string expires_at: string created_at: string - status: 'ready' | 'blocked' | 'applied' | 'expired' | 'conflict' + status: 'ready' | 'blocked' | 'applied' | 'expired' | 'conflict' | 'cancelled' + cancelled_at?: string + cancelled_by?: number blocked_reasons: string[] evidence: { observed_at: string @@ -115,6 +117,9 @@ export const aiOpsControlAPI = { async apply(id: string, digest: string, signal?: AbortSignal): Promise { return (await apiClient.post(`${root}/proposals/${encodeURIComponent(id)}/apply`, { digest, confirm: true }, { signal })).data }, + async cancel(id: string, digest: string, signal?: AbortSignal): Promise { + return (await apiClient.post(`${root}/proposals/${encodeURIComponent(id)}/cancel`, { digest }, { signal })).data + }, async rollback(id: string, revision: number, signal?: AbortSignal): Promise { return (await apiClient.post(`${root}/actions/${encodeURIComponent(id)}/rollback`, { expected_revision: revision, confirm: true }, { signal })).data }, diff --git a/frontend/src/components/admin/operations/AIOpsControls.vue b/frontend/src/components/admin/operations/AIOpsControls.vue index c7abedfce44e..be39a79c9745 100644 --- a/frontend/src/components/admin/operations/AIOpsControls.vue +++ b/frontend/src/components/admin/operations/AIOpsControls.vue @@ -65,7 +65,7 @@
-

{{ t('aiOpsControl.preview') }}

+

{{ t('aiOpsControl.preview') }}

{{ t('aiOpsControl.chooseHint') }}

{{ t('aiOpsControl.noRecommendations') }}

@@ -88,10 +88,14 @@

{{ t('aiOpsControl.reason') }}:{{ frozenReason }}

{{ t('aiOpsControl.evidenceRefs') }}:{{ frozenEvidenceIds.join(', ') || '—' }}

{{ t('aiOpsControl.digest') }}{{ frozen.digest }}
- + - +
+ + +
+

{{ t('aiOpsControl.cancelHint') }}

@@ -176,6 +180,7 @@ const canPreview = computed(() => auth.isAdmin && policy.value?.control_enabled const previewExpired = computed(() => !!frozen.value && (!Number.isFinite(Date.parse(frozen.value.expires_at)) || Date.parse(frozen.value.expires_at) <= clock.value)) const previewReady = computed(() => !!frozen.value && frozen.value.status === 'ready' && !frozen.value.blocked_reasons.length && frozen.value.policy_revision === policy.value?.revision && frozen.value.run_id === props.run?.id && !!frozen.value.digest && !previewExpired.value) const frozenAfterValue = computed(() => frozen.value ? changeValue(frozen.value.action, frozen.value.action === 'pause_account' ? 1 : frozen.value.action === 'resume_account' ? 0 : frozen.value.proposed_value) : '—') +const canCancel = computed(() => auth.isAdmin && !!frozen.value?.digest && ['ready', 'blocked'].includes(frozen.value.status) && !busy.value && !halting.value && !loading.value && !needsRefresh.value) const canApply = computed(() => canPreview.value && previewReady.value && applyConsent.value) let alive = true, readGeneration = 0, previewGeneration = 0, mutationGeneration = 0 @@ -299,6 +304,20 @@ async function apply(): Promise { finally { if (alive && generation === mutationGeneration) busy.value = false } } +async function cancelProposal(): Promise { + if (!canCancel.value || !frozen.value) return + const proposal = frozen.value, generation = ++mutationGeneration + mutationController = new AbortController() + busy.value = true; error.value = ''; notice.value = ''; applyConsent.value = false + try { + const cancelled = await aiOpsControlAPI.cancel(proposal.id, proposal.digest, mutationController.signal) + if (!alive || generation !== mutationGeneration) return + if (frozen.value?.id === proposal.id) frozen.value = cancelled + notice.value = t('aiOpsControl.proposalCancelled') + } catch (value) { if (alive && generation === mutationGeneration) operationError(value) } + finally { if (alive && generation === mutationGeneration) busy.value = false } +} + function rememberAction(action: AIOpsActionRecord): void { if (!actions.value.some(item => item.id === action.id)) total.value++ actions.value = [action, ...actions.value.filter(item => item.id !== action.id)] diff --git a/frontend/src/components/admin/operations/__tests__/AIOpsControls.spec.ts b/frontend/src/components/admin/operations/__tests__/AIOpsControls.spec.ts index 037fd529df4f..94c402b78479 100644 --- a/frontend/src/components/admin/operations/__tests__/AIOpsControls.spec.ts +++ b/frontend/src/components/admin/operations/__tests__/AIOpsControls.spec.ts @@ -11,7 +11,7 @@ import enOps from '@/i18n/locales/en/aiOps' import zhOps from '@/i18n/locales/zh/aiOps' const { api, auth } = vi.hoisted(() => ({ - api: { policy: vi.fn(), savePolicy: vi.fn(), actions: vi.fn(), halt: vi.fn(), preview: vi.fn(), apply: vi.fn(), rollback: vi.fn() }, + api: { policy: vi.fn(), savePolicy: vi.fn(), actions: vi.fn(), halt: vi.fn(), preview: vi.fn(), cancel: vi.fn(), apply: vi.fn(), rollback: vi.fn() }, auth: { isAdmin: true, user: { id: 41 } }, })) vi.mock('@/api/admin/aiOpsControl', () => ({ aiOpsControlAPI: api })) @@ -51,6 +51,7 @@ beforeEach(() => { api.actions.mockResolvedValue({ items: [], total: 0 }) api.savePolicy.mockImplementation(async (value: AIOpsPolicy) => ({ ...value, revision: value.revision + 1 })) api.preview.mockResolvedValue(frozen()) + api.cancel.mockResolvedValue({ ...frozen(), status: 'cancelled' }) api.apply.mockResolvedValue(action()) api.rollback.mockResolvedValue({ ...action(), status: 'rolled_back' }) api.halt.mockResolvedValue({ ...policy(), halted: true, revision: 6 }) @@ -156,6 +157,30 @@ describe('AI operations controlled execution', () => { expect(wrapper.get('[data-testid="ai-control-action"]').text()).toContain(en.status.propagation_pending) }) + it.each(['en', 'zh'] as const)('cancels the exact frozen proposal and blocks later approval in %s', async locale => { + wrapper = mountControls(locale); await flushPromises() + await wrapper.get('[data-testid="ai-control-preview-0"]').trigger('click'); await flushPromises() + await wrapper.get('[data-testid="ai-control-apply-consent"]').setValue(true) + await wrapper.get('[data-testid="ai-control-cancel"]').trigger('click'); await flushPromises() + expect(api.cancel).toHaveBeenCalledWith('proposal-1', 'd'.repeat(64), expect.any(AbortSignal)) + expect(api.cancel).toHaveBeenCalledOnce() + expect(api.apply).not.toHaveBeenCalled() + expect(wrapper.find('[data-testid="ai-control-cancel"]').exists()).toBe(false) + expect(wrapper.get('[data-testid="ai-control-apply"]').attributes('disabled')).toBeDefined() + expect(wrapper.text()).toContain((locale === 'zh' ? zh : en).proposalCancelled) + }) + + it('does not replay cancellation when its response is unknown', async () => { + api.cancel.mockRejectedValue(new Error('unknown outcome')) + wrapper = mountControls(); await flushPromises() + await wrapper.get('[data-testid="ai-control-preview-0"]').trigger('click'); await flushPromises() + await wrapper.get('[data-testid="ai-control-cancel"]').trigger('click'); await flushPromises() + expect(api.cancel).toHaveBeenCalledOnce() + expect(wrapper.find('[data-testid="ai-control-frozen"]').exists()).toBe(false) + expect(wrapper.get('[data-testid="ai-control-preview-0"]').attributes('disabled')).toBeDefined() + expect(api.apply).not.toHaveBeenCalled() + }) + it('expires a preview and clears it when the selected diagnostic changes', async () => { api.preview.mockResolvedValue({ ...frozen(), expires_at: '2026-11-05T00:00:01Z' }) wrapper = mountControls(); await flushPromises() diff --git a/frontend/src/components/common/__tests__/NewFeatureBadge.spec.ts b/frontend/src/components/common/__tests__/NewFeatureBadge.spec.ts index 6336192f14f1..8e6f73b6d17b 100644 --- a/frontend/src/components/common/__tests__/NewFeatureBadge.spec.ts +++ b/frontend/src/components/common/__tests__/NewFeatureBadge.spec.ts @@ -30,6 +30,7 @@ describe('NewFeatureBadge', () => { ['image header timeout groups', NEW_FEATURE_NOTICES.openaiImageHeaderTimeoutGroups], ['profit operations time ranges', NEW_FEATURE_NOTICES.profitOperationsTimeRanges], ['quality retest rest', NEW_FEATURE_NOTICES.qualityRetestRest], + ['AI operations proposal cancellation', NEW_FEATURE_NOTICES.aiOpsProposalCancel], ])('keeps %s dismissal shared and persistent across feature announcements', async (_feature, noticeId) => { const pinia = createPinia() setActivePinia(pinia) diff --git a/frontend/src/constants/newFeatureNotices.ts b/frontend/src/constants/newFeatureNotices.ts index 684cfe5d9d46..3a8ccddfd23d 100644 --- a/frontend/src/constants/newFeatureNotices.ts +++ b/frontend/src/constants/newFeatureNotices.ts @@ -23,6 +23,7 @@ export const NEW_FEATURE_NOTICES = { profitOperationsTimeRanges: 'profit-operations-time-ranges-initial-announcement', vipAutoCredit: 'vip-auto-credit-initial-announcement', oauthInitialTOTPRotation429: 'oauth-initial-totp-rotation-on-429-initial-announcement', + aiOpsProposalCancel: 'ai-ops-proposal-cancel-initial-announcement', aiOpsCodex: 'ai-ops-codex-observe-initial-announcement', bepusdtPayment: 'bepusdt-embedded-payment-initial-announcement', accountDailyScheduling: 'account-daily-schedulable-timers-initial-announcement', diff --git a/frontend/src/i18n/locales/en/aiOpsControl.ts b/frontend/src/i18n/locales/en/aiOpsControl.ts index 5d7b74c6438f..9402bbeea8cb 100644 --- a/frontend/src/i18n/locales/en/aiOpsControl.ts +++ b/frontend/src/i18n/locales/en/aiOpsControl.ts @@ -1,4 +1,7 @@ export default { + cancelProposal: 'Cancel frozen proposal', + cancelHint: 'Cancels only this frozen proposal. Existing actions require rollback; automatic policy and future proposals remain unchanged.', + proposalCancelled: 'Proposal cancelled. This proposal can no longer be applied.', title: 'Controlled execution', description: 'Diagnostic reports remain suggestions. Production changes use a saved policy, fresh evidence and an explicit approval, or separately authorized automatic rules.', compactDescription: 'Production changes require separate authorization. Read-only diagnosis works independently.', diff --git a/frontend/src/i18n/locales/zh/aiOpsControl.ts b/frontend/src/i18n/locales/zh/aiOpsControl.ts index b7e3a235eb48..d44b9decc8fb 100644 --- a/frontend/src/i18n/locales/zh/aiOpsControl.ts +++ b/frontend/src/i18n/locales/zh/aiOpsControl.ts @@ -1,4 +1,7 @@ export default { + cancelProposal: '取消冻结提案', + cancelHint: '仅取消本次冻结提案;已执行动作需单独回滚,自动策略和未来提案继续按原规则运行。', + proposalCancelled: '提案已取消,不能再执行本提案。', title: '受控执行', description: '诊断报告保留为建议。生产变更须符合已保存策略和新鲜证据,并逐次审批,或另行授权自动规则执行。', compactDescription: '生产变更须另行授权,只读诊断可独立使用。', From 81f94d71da9696d106ee1cbed9e6abff81a1d4f2 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 8 Nov 2026 21:40:01 +0800 Subject: [PATCH 2/4] =?UTF-8?q?test:=20=E4=BF=AE=E5=A4=8D=E6=8F=90?= =?UTF-8?q?=E6=A1=88=E5=8F=96=E6=B6=88=E5=9B=9E=E5=BD=92=E7=9A=84=E5=85=B3?= =?UTF-8?q?=E9=97=AD=E9=A2=84=E6=9C=9F=E4=B8=8E=E7=8A=B6=E6=80=81=E5=88=86?= =?UTF-8?q?=E6=94=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/repository/ai_ops_test.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/backend/internal/repository/ai_ops_test.go b/backend/internal/repository/ai_ops_test.go index 09e5759e6872..484730df4481 100644 --- a/backend/internal/repository/ai_ops_test.go +++ b/backend/internal/repository/ai_ops_test.go @@ -283,16 +283,17 @@ func TestAIOpsCancelIsIdempotentAndDoesNotMutateAnAccount(t *testing.T) { } r := &accountRepository{sql: db} got, err := r.CancelAIOpsProposal(context.Background(), p.ID, p.Digest, 9) - if status == "ready" || status == "blocked" { + switch status { + case "ready", "blocked": require.NoError(t, err) require.Equal(t, "cancelled", got.Status) require.Equal(t, int64(9), got.CancelledBy) require.NotNil(t, got.CancelledAt) - } else if status == "cancelled" { + case "cancelled": require.NoError(t, err) require.Equal(t, int64(41), got.CancelledBy, "retry preserves original audit actor") require.WithinDuration(t, *p.CancelledAt, *got.CancelledAt, time.Microsecond) - } else { + default: require.ErrorIs(t, err, service.ErrAIOpsConflict) } require.NoError(t, m.ExpectationsWereMet()) @@ -314,9 +315,10 @@ func TestAIOpsCancelRejectsAnotherDigestAndExistingAction(t *testing.T) { m.ExpectQuery("SELECT EXISTS.*ai_ops_actions").WithArgs(p.ID).WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(true)) } m.ExpectRollback() + m.ExpectClose() _, err = r.CancelAIOpsProposal(context.Background(), p.ID, digest, 9) require.ErrorIs(t, err, service.ErrAIOpsConflict) - require.NoError(t, m.ExpectationsWereMet()) require.NoError(t, db.Close()) + require.NoError(t, m.ExpectationsWereMet()) } } From 4a56e0e37b816a6e20a5fe724c61216fe9f1be24 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 8 Nov 2026 21:46:17 +0800 Subject: [PATCH 3/4] =?UTF-8?q?ci:=20=E7=95=99=E5=AD=98=E6=8F=90=E6=A1=88?= =?UTF-8?q?=E5=8F=96=E6=B6=88=20PG=20race=20=E5=B4=A9=E6=BA=83=E8=AF=8A?= =?UTF-8?q?=E6=96=AD=E5=B9=B6=E8=A6=81=E6=B1=82=E7=9C=9F=E5=AE=9E=E7=94=A8?= =?UTF-8?q?=E4=BE=8B=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ai-ops.yml | 47 +++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ai-ops.yml b/.github/workflows/ai-ops.yml index d7344e22e0b2..961e5903daac 100644 --- a/.github/workflows/ai-ops.yml +++ b/.github/workflows/ai-ops.yml @@ -75,4 +75,49 @@ jobs: working-directory: backend env: CI: 'true' - run: go test -race -tags=integration ./internal/repository -run '^TestAIOpsPostgres(Cancel|ConcurrentCancel)' -count=1 -v -timeout=10m + GOTRACEBACK: crash + shell: bash + run: | + set -euo pipefail + mkdir -p ../evidence + uname -a > ../evidence/kernel.txt + go version > ../evidence/toolchain.txt + go env GOOS GOARCH CGO_ENABLED GOTOOLCHAIN >> ../evidence/toolchain.txt + docker version > ../evidence/docker-version.txt + docker info > ../evidence/docker-info.txt + if ! command -v gdb >/dev/null; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends gdb + fi + ulimit -c unlimited + sudo sysctl -w "kernel.core_pattern=$RUNNER_TEMP/ai-ops-cancel.core.%p" > ../evidence/core-pattern.txt + export GORACE="log_path=$PWD/../evidence/race history_size=4" + binary="$RUNNER_TEMP/ai-ops-cancel.test" + go test -c -race -tags=integration ./internal/repository -o "$binary" + set +e + "$binary" -test.run '^TestAIOpsPostgres(Cancel|ConcurrentCancel)' -test.count=1 -test.v=true -test.timeout=10m > ../evidence/integration.log 2>&1 + result=$? + set -e + cat ../evidence/integration.log + printf '%s\n' "$result" > ../evidence/exit.txt + if [ "$result" -ne 0 ]; then + for core in "$RUNNER_TEMP"/ai-ops-cancel.core.*; do + [ -f "$core" ] || continue + # Never upload raw core files or argument/local values. + gdb -batch -ex 'set print frame-arguments none' -ex 'thread apply all bt' \ + "$binary" "$core" > "../evidence/backtrace-$(basename "$core").txt" 2>&1 || true + done + exit "$result" + fi + ! grep -Eq 'no tests to run|--- SKIP:|WARNING: DATA RACE|race detected during execution' ../evidence/integration.log + for regression in CancelledProposalCannotBeRevivedOrApplied CancellationCannotUndoAnAppliedAction ConcurrentCancelAndApplyHaveOneWinner; do + grep -q -- "=== RUN TestAIOpsPostgres$regression$" ../evidence/integration.log + grep -q -- "--- PASS: TestAIOpsPostgres$regression " ../evidence/integration.log + done + - uses: actions/upload-artifact@v7 + if: always() + with: + name: ai-ops-cancellation-${{ github.event.pull_request.head.sha || github.sha }} + path: evidence/ + if-no-files-found: warn + retention-days: 14 From 4a591a176660d764d633135085d7b7fbe6b706b7 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 8 Nov 2026 21:50:02 +0800 Subject: [PATCH 4/4] =?UTF-8?q?chore:=20=E8=B0=83=E6=95=B4=E5=8F=96?= =?UTF-8?q?=E6=B6=88=E6=8F=90=E6=A1=88=E5=85=AC=E5=91=8A=E4=BD=8D=E7=BD=AE?= =?UTF-8?q?=E4=BB=A5=E5=85=BC=E5=AE=B9=E5=B9=B6=E8=A1=8C=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=E7=99=BB=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/constants/newFeatureNotices.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/constants/newFeatureNotices.ts b/frontend/src/constants/newFeatureNotices.ts index 3a8ccddfd23d..38fbf2624bb7 100644 --- a/frontend/src/constants/newFeatureNotices.ts +++ b/frontend/src/constants/newFeatureNotices.ts @@ -23,8 +23,8 @@ export const NEW_FEATURE_NOTICES = { profitOperationsTimeRanges: 'profit-operations-time-ranges-initial-announcement', vipAutoCredit: 'vip-auto-credit-initial-announcement', oauthInitialTOTPRotation429: 'oauth-initial-totp-rotation-on-429-initial-announcement', - aiOpsProposalCancel: 'ai-ops-proposal-cancel-initial-announcement', aiOpsCodex: 'ai-ops-codex-observe-initial-announcement', + aiOpsProposalCancel: 'ai-ops-proposal-cancel-initial-announcement', bepusdtPayment: 'bepusdt-embedded-payment-initial-announcement', accountDailyScheduling: 'account-daily-schedulable-timers-initial-announcement', accountAutoRefreshUpstreamModels: 'account-auto-refresh-upstream-models-initial-announcement',