Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions .github/scripts/ai-ops-screenshot.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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');},
Expand Down Expand Up @@ -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))
Expand Down
66 changes: 65 additions & 1 deletion .github/workflows/ai-ops.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -57,3 +57,67 @@ 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'
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
30 changes: 30 additions & 0 deletions backend/internal/handler/admin/ops_ai_control_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
32 changes: 32 additions & 0 deletions backend/internal/handler/admin/ops_ai_control_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down Expand Up @@ -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")
}
}
48 changes: 48 additions & 0 deletions backend/internal/repository/ai_ops.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
87 changes: 87 additions & 0 deletions backend/internal/repository/ai_ops_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
Loading
Loading