Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
b6823c2
feat(slm): roll back to a chosen earlier commit through the updater (…
mrveiss Nov 2, 2026
45c517c
fix(slm): the rollback's audit error has its own name (#20214)
mrveiss Nov 2, 2026
fa7a80d
fix(slm): rollback refuses pre-support targets and the service key, a…
mrveiss Nov 2, 2026
46b8733
chore(tests): repin the floors this branch's own files moved (#20214)
mrveiss Nov 2, 2026
1bf9285
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 2, 2026
62e7a04
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 2, 2026
fdfe07c
Merge remote-tracking branch 'origin/main' into issue-20214-rollback
mrveiss Nov 3, 2026
69be72c
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 3, 2026
443c2a0
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 3, 2026
82d8198
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 3, 2026
6a25359
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 3, 2026
f10b854
Merge main into issue-20214-rollback (#20214)
mrveiss Nov 5, 2026
c40c7ba
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 5, 2026
e3d8741
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 5, 2026
41cf135
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 5, 2026
0dc0abf
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 6, 2026
693018e
fix(rollback): bounded env read, shared git fixtures, muted-text toke…
mrveiss Nov 6, 2026
8a61482
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 6, 2026
70cace1
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 6, 2026
9af9247
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 6, 2026
e2c3b3f
Merge remote-tracking branch into issue-20214-rollback
mrveiss Nov 6, 2026
2f2d555
Merge main into issue-20214-rollback
mrveiss Nov 6, 2026
f7cb4ed
fix(rollback): code rollback tests restore sys.modules after their st…
mrveiss Nov 6, 2026
b92c15d
fix(rollback): scope leak-guard owner reuse to the owner's tree and k…
mrveiss Nov 6, 2026
e7961de
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 6, 2026
390a32e
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 6, 2026
d882bed
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 7, 2026
353f31a
Merge #20596 @ d882bedf44 into the merge train
mrveiss Nov 7, 2026
c8df616
fix(train): regenerate SLM openapi.json and generated types for the r…
mrveiss Nov 7, 2026
cc88121
fix(train): reach floors return to mid-window on the merged tree (#17…
mrveiss Nov 7, 2026
1de8310
fix(train): code rollback composable takes its logger from the kit (#…
mrveiss Nov 7, 2026
626f1db
fix(train): SLM conftest real-loads the code rollback services (#20214)
mrveiss Nov 7, 2026
894ecb3
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 7, 2026
a43d2bc
Merge main into the merge train
mrveiss Nov 7, 2026
720fd85
fix(train): SLM conftest stays under the 600-line cap — real-loaded m…
mrveiss Nov 7, 2026
759509b
fix(train): inline-lazy-singleton floor follows the merged tree's pyt…
mrveiss Nov 7, 2026
1e85124
Merge main into issue-20214-rollback (auto-sync) [skip ci]
github-actions[bot] Nov 7, 2026
d2d8346
Merge remote-tracking branch 'origin/main' into train-2026-11-07-t88a
mrveiss Nov 7, 2026
6e462b4
fix(train): real-loaded SLM schemas live under testkit; inline-lazy-s…
mrveiss Nov 7, 2026
1cc261b
fix(slm): code rollback review fixes (#20214)
mrveiss Nov 7, 2026
d273b89
fix(slm): rollback statement-timeout test uses a DB-API mock, not a h…
mrveiss Nov 7, 2026
b553e06
Merge #20596 @ d273b89965 into the merge train
mrveiss Nov 7, 2026
64d9f51
fix(train): inline-lazy-singleton floor follows the rebuilt train's t…
mrveiss Nov 7, 2026
8cf728b
Merge remote-tracking branch 'origin/main' into train-2026-11-07-t88a
mrveiss Nov 7, 2026
8c14c9d
fix(train): inline-lazy-singleton floor follows the merged tree (#21026)
mrveiss Nov 7, 2026
019b45c
fix(train): T88a red CI — rollback node call through the shared clien…
mrveiss Nov 7, 2026
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
1 change: 1 addition & 0 deletions autobot-backend/services/audit/taxonomy.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ class AuditAction(str, Enum):
ROLE_DELETE = "role.delete"
API_KEY_USE = "api_key.use" # pragma: allowlist secret -- an action name, not a key
SECURITY_SUSPICIOUS_ACTIVITY = "security.suspicious_activity"
CODE_ROLLBACK = "code.rollback" # #20214: the SLM updater deploys an earlier commit the operator chose
CONVERSATION_FILE_CLEANUP = "conversation_file.cleanup"
CONVERSATION_FILE_CLEANUP_RESET = "conversation_file.cleanup_reset"
BUDGET_CHAT_REFUSED = "budget.chat_refused" # #20589 chat over a budget
Expand Down
12 changes: 12 additions & 0 deletions autobot-slm-backend/_slm_stub_lifetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@
from pathlib import Path
from typing import Any, Dict

import pytest

PLUGIN_NAME = "slm-backend-stub-lifetime"


Expand Down Expand Up @@ -80,6 +82,16 @@ def pytest_collectstart(self, collector: Any) -> None:
def pytest_runtest_setup(self, item: Any) -> None:
self._apply(item)

@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_protocol(self, item: Any, nextitem: Any):
"""Withdraw before the leak guard's own protocol check (registered earlier, so this wraps it).

Collection can end inside this directory, leaving the stubs live when the first item of
another tree starts; ``pytest_runtest_setup`` is too late, the guard has already looked.
"""
self._apply(item)
yield
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved


def register_stub_lifetime(config: Any, root: Path, stubs: Dict[str, Any]) -> None:
"""Register the lifetime manager once, globally."""
Expand Down
7 changes: 7 additions & 0 deletions autobot-slm-backend/ansible/playbooks/update-all-nodes.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@
# `autobot.services` stops carrying unrendered templates (#15731).
git_repo_root: "{{ code_source_dir | default(autobot.base_dir ~ '/code_source') }}"
deploy_ref: "main"
# #20214: a rollback sets this and a full commit id as `deploy_ref` (services/rollback_target.py). The id
# was validated as an ancestor of the branch head before it got here, so the branch allow-list does not
# apply; and the commit is NOT announced to /code-source/notify below, which would record it as the
# latest commit and make every node read as current at an old commit.
deploy_is_rollback: false
allowed_branches:
- main
- release
Expand Down Expand Up @@ -153,6 +158,7 @@
Override: -e skip_branch_check=true
when:
- not skip_branch_check | bool
- not deploy_is_rollback | bool
- deploy_ref not in allowed_branches

- name: "[PRE-FLIGHT] Create deploy archive directory"
Expand Down Expand Up @@ -357,6 +363,7 @@
validate_certs: false
status_code: [200, 404]
ignore_errors: true
when: not deploy_is_rollback | bool

# =============================================================================
# PLAY 1: Update SLM Server First
Expand Down
2 changes: 2 additions & 0 deletions autobot-slm-backend/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from .blue_green import router as blue_green_router
from .browser import router as browser_router
from .capability_profile import router as capability_profile_router
from .code_rollback import router as code_rollback_router
from .code_sync import router as code_sync_router
from .config import node_config_router
from .config import router as config_router
Expand Down Expand Up @@ -90,6 +91,7 @@
nodes_router.include_router(node_post_sync_router)
code_sync_router.include_router(post_sync_runs_router)
code_sync_router.include_router(update_report_router)
code_sync_router.include_router(code_rollback_router) # #20214: rollback to a chosen commit

__all__ = [
"agents_router",
Expand Down
3 changes: 3 additions & 0 deletions autobot-slm-backend/api/_resume_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from api.code_sync import UpdateAllJob

from autobot_shared.logging_manager import get_logger
from services.rollback_target import current_rollback_ref, resume_ref, resumed_scope # noqa: F401 - re-exported

logger = get_logger(__name__)

Expand Down Expand Up @@ -73,6 +74,8 @@ async def _persist_resume_plan(
"remaining_node_ids": remaining_node_ids,
"target_commit": target_commit, # C1
"created_at": job.created_at,
"deploy_ref": current_rollback_ref(), # #20214: set only for a rollback; the resume hook reads it once
"is_rollback": current_rollback_ref() is not None,
# #15881: `_stage_log` writes to `stage.log_lines`, which lives in the
# process the self-update is about to restart. Without this the operator
# watching the GUI sees the log stop at "Firing Ansible self-update
Expand Down
178 changes: 178 additions & 0 deletions autobot-slm-backend/api/code_rollback.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
# AutoBot - AI-Powered Automation Platform
# Author: mrveiss
"""Roll back to an earlier commit through the builtin updater (#20214).

GET /code-sync/rollback/candidates the commits that may be chosen
GET /code-sync/rollback/preview what choosing one would do, and whether a migration is in the way
POST /code-sync/rollback start it (202, the update-all job; poll /update-all/status)

Mounted on the code-sync router (``api/__init__.py``), so it carries the include-level auth of
Update Everything, and takes the same per-request dependency (``get_current_user``). The work is in
``services/code_rollback.py``; this module is the HTTP edge only.
"""

from __future__ import annotations

from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
from sqlalchemy.ext.asyncio import AsyncSession

from api import code_sync as cs
from autobot_shared import node_proxy
from autobot_shared.logging_manager import get_logger
from models.rollback_schemas import (
RollbackCandidates,
RollbackCommit,
RollbackDatabaseCheck,
RollbackPreview,
RollbackRequest,
)
from services import rollback_audit
from services.auth import get_current_user, verify_internal_api_key
from services.code_rollback import Preflight, orchestrator, preflight, rollback_enabled
from services.database import get_db
from services.rollback_commits import CommitInfo, RollbackRefused, list_candidates

logger = get_logger(__name__)

_NOT_ENABLED = "Rollback is not enabled on this SLM (SLM_ROLLBACK_ENABLED is off)."
#: Machine-readable marker the screen keys on: only this 403 hides the panel; any other 403 is a denial to show.
FEATURE_DISABLED_CODE = "rollback_feature_disabled"
_PERSON_ONLY = "A person must do this: the service key cannot roll back."


def require_rollback_enabled() -> None:
"""Router gate: every rollback route answers 403 while the feature is off (pending a host test, #20214)."""
if not rollback_enabled():
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail={"code": FEATURE_DISABLED_CODE, "message": _NOT_ENABLED}
)


router = APIRouter(prefix="/rollback", tags=["code-sync"], dependencies=[Depends(require_rollback_enabled)])

_AUDIT_DOWN = "The audit trail is unavailable, so the rollback was not started."


def _commit_model(info: CommitInfo, deployed: str | None) -> RollbackCommit:
return RollbackCommit(
commit=info.commit, short=info.short, date=info.date, subject=info.subject, is_deployed=info.commit == deployed
)


def _actor(user: dict) -> str | None:
value = user.get("sub") or user.get("username")
return str(value) if value else None


def _named_person(request: Request, user: dict) -> str:
"""The person acting. The internal service key passes the router gate; it must not start a rollback."""
actor = _actor(user)
if actor is None or verify_internal_api_key(request.headers.get(node_proxy.INTERNAL_KEY_HEADER)):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=_PERSON_ONLY)
return actor


def _bad_request(exc: RollbackRefused) -> HTTPException:
return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=exc.reason)


async def _source(db: AsyncSession):
tracker = await cs._get_tracker_for_db(db)
return tracker.repo_path, tracker.remote, tracker.branch


@router.get("/candidates")
async def rollback_candidates(
db: Annotated[AsyncSession, Depends(get_db)],
_: Annotated[dict, Depends(get_current_user)],
) -> RollbackCandidates:
"""The newest commits of the tracked branch, with dates and subjects, for the picker."""
repo, remote, branch = await _source(db)
deployed = await cs._get_slm_deployed_commit()
try:
commits = await list_candidates(repo, remote, branch, deployed)
except RollbackRefused as exc:
raise _bad_request(exc) from exc
return RollbackCandidates(
branch=branch, deployed_commit=deployed, commits=[_commit_model(c, deployed) for c in commits]
)


def _preview(result: Preflight) -> RollbackPreview:
return RollbackPreview(
commit=_commit_model(result.target, result.deployed),
allowed=result.refusal is None,
refusal=result.refusal,
checks=[RollbackDatabaseCheck(**vars(c)) for c in result.checks],
)


@router.get("/preview")
async def rollback_preview(
commit: Annotated[str, Query(max_length=200)],
db: Annotated[AsyncSession, Depends(get_db)],
_: Annotated[dict, Depends(get_current_user)],
) -> RollbackPreview:
"""Validate one commit and say whether a database migration is in the way."""
repo, remote, branch = await _source(db)
try:
return _preview(await preflight(repo, remote, branch, commit))
except RollbackRefused as exc:
raise _bad_request(exc) from exc


async def _refuse(user: dict, commit: str | None, reason: str, code: int) -> HTTPException:
"""Record a refusal (best effort: it stands either way) and build the response.

``commit`` is only ever a validated commit id; client text that failed validation is never stored.
"""
try:
await rollback_audit.record_rollback(
actor=_actor(user),
commit=commit,
outcome=rollback_audit.DENIED,
phase=rollback_audit.PHASE_REQUESTED,
reason=reason,
)
except rollback_audit.RollbackAuditUnavailable:
pass
return HTTPException(status_code=code, detail=reason)


async def _start_after_audit(user: dict, result: Preflight) -> cs.UpdateAllJob:
"""Make the request durable, then start through the same gate Update Everything uses."""
commit = result.target.commit
try:
await rollback_audit.record_rollback(
actor=_actor(user), commit=commit, outcome=rollback_audit.SUCCESS, phase=rollback_audit.PHASE_REQUESTED
)
except rollback_audit.RollbackAuditUnavailable as exc:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=_AUDIT_DOWN) from exc
try:
async with cs._update_all_start_lock:
return await cs._start_update_all_locked(orchestrate=orchestrator(result.target, _actor(user)))
except HTTPException as exc:
raise await _refuse(user, commit, str(exc.detail), exc.status_code) from exc


@router.post("", status_code=status.HTTP_202_ACCEPTED)
async def start_rollback(
body: RollbackRequest,
request: Request,
db: Annotated[AsyncSession, Depends(get_db)],
user: Annotated[dict, Depends(get_current_user)],
) -> cs.UpdateAllJob:
"""Deploy the chosen earlier commit. Refused while an update runs or when a migration is in the way."""
_named_person(request, user)
repo, remote, branch = await _source(db)
try:
result = await preflight(repo, remote, branch, body.commit)
except RollbackRefused as exc:
raise await _refuse(user, None, exc.reason, status.HTTP_400_BAD_REQUEST) from exc
if result.refusal is not None:
raise await _refuse(user, result.target.commit, result.refusal, status.HTTP_409_CONFLICT)
return await _start_after_audit(user, result)
Comment thread
mrveiss marked this conversation as resolved.
Resolved
Loading
Loading