Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
9444e97
fix(slm): database URLs encode their credentials, in one helper (#19812)
mrveiss Nov 1, 2026
2d9fef8
chore(guards): re-pin the reach floors main's growth left stale (#19812)
mrveiss Nov 1, 2026
ede6e36
fix(ansible): every database URL encodes its credentials, and pg_dump…
mrveiss Nov 1, 2026
ea73398
fix(slm): the migration runner decodes the URL's credentials (#19812)
mrveiss Nov 1, 2026
3ba7afc
fix(kb): an unavailable claim registry neither masks a start error no…
mrveiss Nov 1, 2026
cecf555
guard(ansible): a marked verify-after-install may not have a reader t…
mrveiss Nov 1, 2026
b7b5dc7
fix(slm): a limited ansible run proves every host it names, not just …
mrveiss Nov 1, 2026
bf11b8d
fix(guard): bare is-defined guards nothing against a skipped task, an…
mrveiss Nov 1, 2026
a7e2789
fix(slm): self-update requires only its own node to have run, and rep…
mrveiss Nov 1, 2026
019237a
feat(org): drop the unused tier column only through the approval queu…
mrveiss Nov 1, 2026
301e5c0
chore(tests): repin the reach floors the new files move (#19997)
mrveiss Nov 1, 2026
541273d
fix(org): the tier column drop is server-only, four-eyes, and audited…
mrveiss Nov 1, 2026
51556ba
fix(org): the proposer is identified the way the approve route identi…
mrveiss Nov 1, 2026
bf84fac
security(kb): hard user and organisation deletes bump the membership …
mrveiss Nov 1, 2026
770ec5c
security(auth): void the tokens of a deactivated or deleted user thro…
mrveiss Nov 1, 2026
cbe30cb
Merge remote-tracking branch 'origin/issue-19670-membership-epoch' in…
mrveiss Nov 1, 2026
6eb68be
test(auth): the token and cache tests use a user both deletes can rea…
mrveiss Nov 1, 2026
629b2da
security(auth): RS256 authority tokens honour the user revocation mar…
mrveiss Nov 1, 2026
ce614d8
Merge main into issue-19881-switch-claims (auto-sync) [skip ci]
github-actions[bot] Nov 1, 2026
2195b9a
Merge main into issue-19883-marker-readers (auto-sync) [skip ci]
github-actions[bot] Nov 1, 2026
f624472
Merge main into issue-19766-limit-proof (auto-sync) [skip ci]
github-actions[bot] Nov 1, 2026
d33e429
Merge main into issue-19670-membership-epoch (auto-sync) [skip ci]
github-actions[bot] Nov 1, 2026
11e5bbc
docs(threat-model): the authority token anchor follows its symbol (#2…
mrveiss Nov 1, 2026
dfa2386
Merge remote-tracking branch 'origin/main' into issue-20446-token-kinds
mrveiss Nov 1, 2026
c47a660
security(auth): write the revocation marker after commit, outlive ref…
mrveiss Nov 1, 2026
19bb611
Merge remote-tracking branch 'origin/main' into issue-19670-membershi…
mrveiss Nov 1, 2026
11519a3
Merge remote-tracking branch 'origin/issue-19670-membership-epoch' in…
mrveiss Nov 1, 2026
ee901a1
chore(guards): re-pin the reach floors the pre-push gate reported sta…
mrveiss Nov 1, 2026
c65b634
test(auth): the failed-commit test uses the shared fake session (#20443)
mrveiss Nov 1, 2026
fe6d50e
security(auth): cap a session's life, retry and surface a failed revo…
mrveiss Nov 1, 2026
29479d4
security(auth): authority tokens read the backend's Redis markers and…
mrveiss Nov 1, 2026
c1042bf
Merge main into issue-19812-dsn-encoding (auto-sync) [skip ci]
github-actions[bot] Nov 1, 2026
74dcb75
Merge main into issue-19881-switch-claims (auto-sync) [skip ci]
github-actions[bot] Nov 1, 2026
90f1361
Merge main into issue-19883-marker-readers (auto-sync) [skip ci]
github-actions[bot] Nov 1, 2026
937ce49
Merge main into issue-19766-limit-proof (auto-sync) [skip ci]
github-actions[bot] Nov 1, 2026
387fea9
Merge main into issue-20446-token-kinds (auto-sync) [skip ci]
github-actions[bot] Nov 1, 2026
3cfae3f
Merge remote-tracking branch 'origin/main' into issue-20446-token-kinds
mrveiss Nov 1, 2026
e0b63bc
Merge remote-tracking branch 'origin/main' into issue-19670-membershi…
mrveiss Nov 1, 2026
b1fc3d1
Merge remote-tracking branch 'origin/issue-20446-token-kinds' into is…
mrveiss Nov 1, 2026
079cb39
chore(guards): re-pin the reach floors the pre-push gate reported sta…
mrveiss Nov 1, 2026
869a4d1
Merge #20444 @ 079cb396d7 into the merge train
mrveiss Nov 1, 2026
c31c735
Merge #20452 @ b1fc3d1edd into the merge train
mrveiss Nov 1, 2026
a7405db
Merge #20441 @ 51556baa36 into the merge train
mrveiss Nov 1, 2026
910c382
Merge #20424 @ c1042bf8e5 into the merge train
mrveiss Nov 1, 2026
a29d9b6
Merge #20432 @ 74dcb7593f into the merge train
mrveiss Nov 1, 2026
5f6383d
Merge #20433 @ 90f1361419 into the merge train
mrveiss Nov 1, 2026
f763e68
Merge #20434 @ 937ce4991e into the merge train
mrveiss Nov 1, 2026
8e17b72
fix(train): reach floors return to mid-window on the merged tree (#20…
mrveiss Nov 1, 2026
5a1d452
fix(train): the bare cast reach floor returns to mid-window, by hand …
mrveiss Nov 1, 2026
848fb75
fix(auth): one user service per file, a revocation time is not a clai…
mrveiss Nov 1, 2026
4175d4c
fix(org): the tier drop audits a declared action, and its admin count…
mrveiss Nov 1, 2026
0e1a43a
chore(tests): repin the reach floors main moved (#19997)
mrveiss Nov 1, 2026
ac845f6
Merge main into the merge train (#20458)
mrveiss Nov 1, 2026
a0b8ddb
Merge #20444 @ 848fb75f51 into the merge train
mrveiss Nov 1, 2026
4545b02
Merge #20441 @ 0e1a43a710 into the merge train
mrveiss Nov 1, 2026
5686eb3
fix(train): generated types follow the merged API (#20458)
mrveiss Nov 1, 2026
12fc12c
fix(train): reach floors return to mid-window on the merged tree (#20…
mrveiss Nov 1, 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
61 changes: 61 additions & 0 deletions autobot-backend/api/admin_org_tier_column.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
# AutoBot - AI-Powered Automation Platform
# Author: mrveiss
"""Admin API: PROPOSE dropping ``organizations.subscription_tier`` (#19997).

Endpoints:
GET /api/admin/org-tier-column whether this database still holds the column
POST /api/admin/org-tier-column/requests PROPOSE the drop -- creates a PENDING approval

Neither route changes the schema. Nothing runs until a human approves it in the Approvals inbox, and
it is never auto-approved (#17038). The executor lives in ``services.org_tier_column_action``.
"""

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

from api.schemas_org_tier_column import OrgTierColumnRequestResponse, OrgTierColumnStatus
from api.user_management.dependencies import get_db_session
from auth_middleware import get_current_user
from auth_rbac import require_role
from models.approval import ApprovalType
from services.approval_gate_service import ApprovalGateService
from services.org_tier_column_action import ACTION, column_present, register_tier_column_action

router = APIRouter(prefix="/admin", dependencies=[Depends(require_role("admin", "superadmin"))])

# Registered at this router's import time so the executor exists before any approve().
register_tier_column_action()


@router.get("/org-tier-column", response_model=OrgTierColumnStatus)
async def org_tier_column_status(session: AsyncSession = Depends(get_db_session)) -> OrgTierColumnStatus:
"""Read only: whether there is anything to propose."""
return OrgTierColumnStatus(present=await column_present(session))


@router.post(
"/org-tier-column/requests", response_model=OrgTierColumnRequestResponse, status_code=status.HTTP_201_CREATED
)
async def propose_org_tier_column_drop(
current_user: dict = Depends(get_current_user),
session: AsyncSession = Depends(get_db_session),
) -> OrgTierColumnRequestResponse:
"""Propose the drop -- a request, not an execution. Refused when the column is already gone."""
requester = current_user.get("id") or current_user.get("user_id") # as the approve route reads the decider
if not requester:
raise HTTPException(status.HTTP_403_FORBIDDEN, "The proposal cannot be attributed to a verified user")
if not await column_present(session):
raise HTTPException(status.HTTP_409_CONFLICT, "organizations.subscription_tier is not in this database")
approval = await ApprovalGateService(session).create_approval(
title="Drop the unused organizations.subscription_tier column",
approval_type=ApprovalType.DESTRUCTIVE_ACTION.value,
description=(
"AutoBot has no paid tiers and nothing reads this column (#19984). Approving deletes every stored value "
"in it for good: back up the database first if you may want them."
),
requested_by_agent=f"org-tier-column:{requester}",
context={"action": ACTION},
)
return OrgTierColumnRequestResponse(approval_id=str(approval.id), status=approval.status, action=ACTION)
40 changes: 3 additions & 37 deletions autobot-backend/api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
Provides login, logout, and session management functionality
"""

import datetime
from typing import Dict, List

from fastapi import APIRouter, Depends, HTTPException, Request
Expand All @@ -33,6 +32,8 @@
from api.schemas_common import DataResponse
from api.schemas_system import AuthLogoutData, AuthRefreshData
from auth_middleware import check_admin_permission, get_auth_middleware, get_current_user, resolve_human_user
from auth_refresh import decode_refresh_token as _decode_refresh_token # tests patch this name here
from auth_refresh import reject_if_account_not_live
from auth_revocation import reject_if_revoked_by_password_change, revoked_by_password_change_for_introspection
from autobot_shared.auth.jwt_core import JWTDecodeError, _peek_alg, decode_jwt_no_verify_exp
from autobot_shared.auth.permissions import ROLE_PERMISSIONS, Role, is_admin_role, role_value
Expand Down Expand Up @@ -484,42 +485,6 @@ async def signup(request: Request, signup_data: SignupRequest):
raise HTTPException(status_code=500, detail="Registration failed. Please try again.")


def _decode_refresh_token(token: str) -> Dict:
"""Decode JWT for refresh, allowing recently expired tokens (1h grace).

Helper for refresh_token (#827).
Accepts both RS256 (new) and HS256 (legacy) tokens (#10196).
"""
mw = get_auth_middleware()
token_alg = _peek_alg(token)
try:
if token_alg == "RS256": # nosec B105 # JWT algorithm identifier, not a credential
payload = decode_jwt_no_verify_exp(
token,
public_key=mw.jwt_public_key,
algorithms=["RS256"],
)
else:
payload = decode_jwt_no_verify_exp(
token,
secret=mw.jwt_secret,
algorithms=["HS256"],
)
except JWTDecodeError as exc:
raise HTTPException(status_code=401, detail=ERR_INVALID_TOKEN) from exc

exp = payload.get("exp")
if exp:
exp_time = datetime.datetime.fromtimestamp(exp, tz=datetime.timezone.utc)
now = datetime.datetime.now(tz=datetime.timezone.utc)
if now > exp_time + datetime.timedelta(hours=1):
raise HTTPException(
status_code=401,
detail="Token expired beyond refresh window",
)
return payload


@router.post("/refresh", response_model=AuthRefreshData)
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
Expand All @@ -539,6 +504,7 @@ async def refresh_token(request: Request):
token = auth_header.split(" ")[1]
payload = _decode_refresh_token(token)
await reject_if_revoked_by_password_change(payload) # a pre-password-change token cannot be refreshed (#18688)
await reject_if_account_not_live(payload) # nor can one of a closed account, marker or not (#20443)
if _is_session_revoked(payload): # a logged-out session cannot be refreshed; an unreadable store reads as gone
raise HTTPException(status_code=401, detail=ERR_INVALID_TOKEN)

Expand Down
3 changes: 2 additions & 1 deletion autobot-backend/api/auth_refresh_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
JWT. The fix declares response_model=AuthRefreshData directly.
"""

from unittest.mock import MagicMock, patch
from unittest.mock import AsyncMock, MagicMock, patch

from fastapi import FastAPI
from fastapi.testclient import TestClient
Expand Down Expand Up @@ -39,6 +39,7 @@ def test_refresh_returns_the_new_jwt_and_expiry_on_the_wire(self):
return_value={"username": "alice", "role": "admin", "email": "alice@example.com"},
),
patch("api.auth.get_auth_middleware", return_value=mock_middleware),
patch("api.auth.reject_if_account_not_live", AsyncMock()), # #20443: tested in its own file
):
response = client.post(
"/api/auth/refresh",
Expand Down
4 changes: 3 additions & 1 deletion autobot-backend/api/schemas_embeddings.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ class EmbeddingSwitchData(BaseModel):
"""The current or last switch.

``state``: idle, building, settling, completed, completed_with_warnings, failed, cancelled, or
stale (an active build whose heartbeat stopped). ``previous_vectors`` is the active collection's
stale (an active build whose heartbeat stopped). ``lock_unknown``: the claim registry could not
be read, so an active state may be a build that has stopped. ``previous_vectors`` is the active collection's
count when the build started; the rebuild writes one vector per fact.
"""

Expand All @@ -53,3 +54,4 @@ class EmbeddingSwitchData(BaseModel):
started: str | None = None
heartbeat: str | None = None
finished: str | None = None
lock_unknown: bool = False
21 changes: 21 additions & 0 deletions autobot-backend/api/schemas_org_tier_column.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
# AutoBot - AI-Powered Automation Platform
# Author: mrveiss
"""Schemas for the org tier column admin routes (#19997)."""

from pydantic import BaseModel


class OrgTierColumnStatus(BaseModel):
"""Whether the column is still in this database."""

present: bool


class OrgTierColumnRequestResponse(BaseModel):
"""The approval a proposal created."""

approval_id: str
status: str
action: str
10 changes: 5 additions & 5 deletions autobot-backend/auth_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

from fastapi import HTTPException, Request, status

from auth_revocation import resolve_human_user_via, token_passes_revocation
from auth_revocation import resolve_human_user_via, token_passes_revocation, with_session_issue_time
from autobot_shared.auth.interactive_principal import LOGIN_TOKEN_TYPE, is_login_token, is_purpose_bound
from autobot_shared.auth.internal_api_key import verify_internal_api_key
from autobot_shared.auth.jwt_core import (
Expand All @@ -32,6 +32,7 @@
from autobot_shared.singleton_factory import lazy_singleton
from autobot_shared.ssot_config import config as ssot_config
from autobot_shared.time_utils import parse_utc_iso
from autobot_shared.user_management.password_epoch import LOGIN_TOKEN_LIFETIME_SECONDS
from autobot_shared.websocket_subprotocol import resolve_ws_token
from config.manager import get_config_manager
from security_layer import SecurityLayer
Expand All @@ -49,7 +50,7 @@ def __init__(self):
self.security_config = config.get("security_config", {})
self.enable_auth = self.security_config.get("enable_auth", True)
self.jwt_secret = self._get_jwt_secret()
self.jwt_expiry_hours = 24
self.jwt_expiry_hours = LOGIN_TOKEN_LIFETIME_SECONDS // 3600 # the epoch marker outlives it (#20443)
self.session_timeout_minutes = self.security_config.get("session_timeout_minutes", 30)
self.max_failed_attempts = self.security_config.get("max_failed_attempts", 3)
self.lockout_duration_minutes = self.security_config.get("lockout_duration_minutes", 15)
Expand Down Expand Up @@ -623,9 +624,8 @@ def _extract_user_from_session(self, request: Request) -> Dict | None:
if not session or not session.get("user_data"):
return None

user_data = session["user_data"].copy()
user_data["auth_method"] = "session"
return user_data
user_data = {**session["user_data"], "auth_method": "session"}
return with_session_issue_time(user_data, session)

def _extract_user_from_dev_header(self, request: Request) -> Dict | None:
"""
Expand Down
72 changes: 72 additions & 0 deletions autobot-backend/auth_refresh.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
# AutoBot - AI-Powered Automation Platform
# Author: mrveiss
"""What ``POST /auth/refresh`` checks before it mints a token from an old one (#827, #20443).

A refresh accepts a token up to ``REFRESH_GRACE_SECONDS`` past its ``exp`` and returns a fresh one, so
a token that stays refreshable would renew for ever. The password-epoch marker revokes it, but a
marker can be lost (store outage while writing it, eviction), so the account itself is checked
too: a deactivated or deleted user cannot refresh, whatever the marker says.
"""

import datetime
from typing import Dict

from fastapi import HTTPException

from auth_middleware import get_auth_middleware
from autobot_shared.auth.jwt_core import JWTDecodeError, _peek_alg, decode_jwt_no_verify_exp
from autobot_shared.auth.revocation_unavailable import revocation_unavailable_error
from autobot_shared.logging_manager import get_logger
from autobot_shared.user_management.login_eligibility import login_refusal
from autobot_shared.user_management.password_epoch import REFRESH_GRACE_SECONDS
from constants.error_constants import ERR_INVALID_TOKEN
from user_management.database import db_session_context
from user_management.services.user_service import UserService

logger = get_logger(__name__)


def decode_refresh_token(token: str) -> Dict:
"""Decode JWT for refresh, allowing recently expired tokens (``REFRESH_GRACE_SECONDS``).

Helper for refresh_token (#827).
Accepts both RS256 (new) and HS256 (legacy) tokens (#10196).
"""
mw = get_auth_middleware()
try:
if _peek_alg(token) == "RS256": # nosec B105 # JWT algorithm identifier, not a credential
payload = decode_jwt_no_verify_exp(token, public_key=mw.jwt_public_key, algorithms=["RS256"])
else:
payload = decode_jwt_no_verify_exp(token, secret=mw.jwt_secret, algorithms=["HS256"])
except JWTDecodeError as exc:
raise HTTPException(status_code=401, detail=ERR_INVALID_TOKEN) from exc

exp = payload.get("exp")
if exp:
exp_time = datetime.datetime.fromtimestamp(exp, tz=datetime.timezone.utc)
now = datetime.datetime.now(tz=datetime.timezone.utc)
if now > exp_time + datetime.timedelta(seconds=REFRESH_GRACE_SECONDS):
raise HTTPException(status_code=401, detail="Token expired beyond refresh window")
return payload


async def reject_if_account_not_live(payload: Dict) -> None:
"""401 unless *payload*'s user exists, is active and is not deleted; 503 when that cannot be read.

Fails closed: a token that may belong to a closed account is never renewed.
"""
username = payload.get("username")
if not username:
raise HTTPException(status_code=401, detail=ERR_INVALID_TOKEN)
try:
async with db_session_context() as session:
user = await UserService(session).get_user_by_username(username)
except Exception as exc:
logger.error("refresh could not read the account state (%s); denying", type(exc).__name__)
raise revocation_unavailable_error() from exc
refusal = login_refusal(user) if user is not None else "account_not_found"
if refusal:
logger.warning("refresh refused for subject=%s: %s", username, refusal)
raise HTTPException(status_code=401, detail=ERR_INVALID_TOKEN)
28 changes: 27 additions & 1 deletion autobot-backend/auth_revocation.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,16 @@
The owner accepted the cost on 2026-09-12 -- a Redis outage takes backend login down with it.
"""

import time
from typing import Dict

from fastapi import HTTPException, Request, status

from autobot_shared.auth.revocation_unavailable import revocation_unavailable_error
from autobot_shared.logging_manager import get_logger
from autobot_shared.time_utils import parse_utc_iso
from autobot_shared.user_management.password_epoch import (
LOGIN_TOKEN_LIFETIME_SECONDS,
MalformedTokenClaims,
RevocationCheckUnavailable,
is_token_revoked_by_password_change,
Expand All @@ -29,6 +32,9 @@

_BEARER_CHALLENGE = {"WWW-Authenticate": "Bearer"}

#: Credentials the epoch can place in time: a JWT by its ``iat``, an ``X-Session-ID`` session by its creation (#20443).
_EPOCH_GATED_METHODS = ("jwt", "session")


async def reject_if_revoked_by_password_change(user_data: Dict) -> None:
"""Raise a 503 (check cannot run) or 401 (revoked) unless the password-epoch check clears *user_data*'s token."""
Expand Down Expand Up @@ -93,6 +99,26 @@ async def resolve_human_user_via(middleware, request: Request) -> Dict | None:
status_code=status.HTTP_403_FORBIDDEN,
detail="Device tokens not permitted on this endpoint. Use mobile-specific API.",
)
if user_data.get("auth_method") == "jwt": # #12924, #16411: a token minted before a password change is void
if user_data.get("auth_method") in _EPOCH_GATED_METHODS: # #12924, #16411: minted before a password change: void
await reject_if_revoked_by_password_change(user_data)
return user_data


def with_session_issue_time(user_data: Dict, session: Dict) -> Dict | None:
"""*user_data* with the session's creation time as ``iat``, so the password-epoch gate covers it (#20443).

A session whose creation time cannot be read cannot be placed against an epoch: None, refused.
So is one older than a login token's lifetime: ``get_session`` extends the TTL on every use, so
polling would otherwise keep a session alive past the epoch marker, which is kept for a token's
lifetime plus a margin, and the voided session would be admitted again once the marker expired.
"""
try:
user_data["iat"] = int(parse_utc_iso(session["created_at"]).timestamp())
except (KeyError, TypeError, ValueError):
logger.warning("Session refused: its creation time is unreadable")
return None
if time.time() - user_data["iat"] > LOGIN_TOKEN_LIFETIME_SECONDS:
logger.info("Session refused: it is older than a login's lifetime")
return None
user_data["sub"] = user_data.get("sub") or user_data.get("username")
return user_data
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from api.adapters import router as adapters_router # Issue #1403
from api.admin_event_logs import router as admin_event_logs_router # Issue #4461
from api.admin_oauth_bundle_strip import router as admin_oauth_bundle_strip_router # #13630
from api.admin_org_tier_column import router as admin_org_tier_column_router # #19997
from api.admin_orphan_repair import router as admin_orphan_repair_router # #15779, #16927
from api.admin_orphan_storage import router as admin_orphan_storage_router # #17038, #17039
from api.admin_pricing import router as admin_pricing_router # GH#6480
Expand Down Expand Up @@ -530,9 +531,10 @@ def _get_canvas_routers() -> list:


def _get_credential_admin_routers() -> list:
"""Admin routers that PROPOSE credential rewrites; execution needs human approval (#13630, #17038)."""
"""Admin routers that PROPOSE rewriting stored data; execution needs human approval (#13630, #17038, #19997)."""
return [
(admin_oauth_bundle_strip_router, "", ["admin", "oauth-bundle-strip"], "admin_oauth_bundle_strip"),
(admin_org_tier_column_router, "", ["admin", "org-tier-column"], "admin_org_tier_column"),
]


Expand Down
16 changes: 14 additions & 2 deletions autobot-backend/knowledge/embedding_switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,16 @@ async def switch_status() -> Dict[str, Any]:
status[key] = int(status[key])
status["failed_ids"] = json.loads(status.get("failed_ids", "[]"))
status.setdefault("state", "idle")
if status["state"] in _ACTIVE and client is not None and await lock.holder() is None:
if status["state"] not in _ACTIVE or client is None:
return status
try:
holder = await lock.holder()
except ClaimUnavailable as exc:
# Neither stale nor known alive: the record is all there is to report (#19881).
logger.warning("embedding switch status: the claim registry is not available: %s", exc)
status["lock_unknown"] = True
return status
if holder is None:
status["state"] = "stale"
status["reason"] = "the build stopped heartbeating; its worker is presumed gone"
return status
Expand Down Expand Up @@ -167,7 +176,10 @@ async def start_switch(kb, model: str, actor: str = "unknown") -> Dict[str, Any]
_audit(actor, "switch_start", model, collection)
fire_and_forget(run_switch(kb, run), name=f"embedding-switch:{model}")
except BaseException:
await lock.release(owner) # a start that failed must not block the next one
try:
await lock.release(owner) # a start that failed must not block the next one
except Exception as exc: # the claim expires by TTL; the start's own error is the one to raise (#19881)
logger.warning("embedding switch %s: could not release its claim: %s", owner, exc)
raise
return await switch_status()

Expand Down
Loading
Loading