Files
ss-tools/backend/src/services/dashboard_testing/execution/capacity.py
busya 65121cac6b feat(logging): self-diagnosing EXPLORE + shared/ absorption + belief analytics (ADR-0021/0022)
T0: absorb shared/ into backend — cot_logger→src/core, CotJsonFormatter→src/core/cot_formatter.py, _llm_http/_llm_health/ssl→src/core/utils; imports rewritten (26 prod + tests, patch targets); run.sh/backend.Dockerfile/requirements/.axiom source_dirs/semantic_health/AGENTS/INSTALL cleaned; ADR-0022 supersedes ADR-0015; fixed latent CI defects (ss_tools ImportError, record.message in logger tests, same-name test-module collision).

ADR-0021 wire enrichment (additive): contract_id/claim/error_code/loc fields; _contract_id ContextVar + resolve_contract_id (explicit > belief_scope > declared-src mirror, derived src never mirrors); EXPLORE auto-loc via single frame walk; facade error auto-fill; 2KB payload cap with payload_truncated/payload_bytes markers; migrated 85 error="CODE" sites to error_code= (12 files); pilot editor/load.py; superset preview payload-bomb inlined bodies removed.

Analytics SSOT src/core/log_stats.py (bond transition matrix, orphan-EXPLORE ratio, REFLECT pairing, intent families, coverage, insufficient-sample flag); pretty_cot.py --stats/--digest/--trajectory/--story over one engine; log_gap_service three-tier ground-truth triangulation (FAILED w/o EXPLORE etc.) + GET /api/reports/log-stats|task-log-gaps (polling-suppressed); scripts/cot_audit.py CLI; enriched fields persisted into task_logs.payload for tier queries.

Frontend: ReportsAnalyticsModel + AnalyticsStatsPanel (Logs tab) + TaskGapPanel and per-row T1/T2/T3 gap badges (Tasks tab); cot-logger.ts ADR-0021 opts; i18n en/ru. Scheduler console spam fixed: apscheduler logger demoted to WARNING via LoggingConfig.scheduler_log_level. .axiom belief patterns -> $OBJ.* (alias undercount). molecular-cot-logging skill updated (fields, decision rules, tie-break, CLI) and synced.

Reviewed orthogonally: F1 cot_span contract pollution, F2 cap boundary accounting, F3 digest over-dedup, F4 trace-state bound, F5 tier metadata — fixed with regression tests. Validation: backend 11287 passed + ruff + compileall; frontend 3446 passed + lint + build; CLI smoke on live app.log.
2026-09-04 20:56:41 +03:00

375 lines
17 KiB
Python

# #region ScenarioExecution.CapacityManager.Service [C:5] [TYPE Module] [SEMANTICS scenario,execution,capacity,quota,lease,admission]
# @ingroup ScenarioExecution
# @BRIEF Atomic environment-scoped capacity admission, heartbeat, release and expiry reconciliation.
# @RELATION IMPLEMENTS -> [ScenarioExecution.CapacityManager]
# @RELATION DEPENDS_ON -> [ScenarioExecution.ProviderRuntime.Engine]
# @PRE The claim carries environment identity/class, workload class, provider identity, run/step refs
# and a server-owned TTL; limits are server policy, never caller input.
# @POST claim_capacity returns an admitted lease or raises CapacityUnavailable("CAPACITY_UNAVAILABLE");
# heartbeat extends a claimed lease; release and expiry reconciliation are idempotent and durable.
# @INVARIANT No provider I/O without a valid claimed lease; admission is one CAS statement on the quota
# counter, so concurrent claims can never overbook; retries claim a new lease.
# @INVARIANT Release/expiry decrement is idempotent with a zero floor; released/expired leases are
# terminal for admission and never resurrected.
# @SIDE_EFFECT Durable quota counter and lease rows in provider_capacity_quotas/provider_capacity_leases.
# @REJECTED Counting active lease rows at claim time was rejected — the count races concurrent claims
# and overbooks; a per-quota counter CAS is the single serialization point.
# @REJECTED Independent per-feature concurrency limits were rejected — they permit cross-workload
# starvation and bypass the environment-scoped allocator.
from __future__ import annotations
import uuid
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import update
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from src.core.logger import logger
from src.models.provider_capacity import CapacityLease, CapacityQuota
_SRC = "ScenarioExecution.CapacityManager.Service"
_DEFAULT_TTL_SECONDS = 300
_MAX_UNITS_PER_CLAIM = 4
_RECONCILE_BATCH = 200
# Pinned defaults (amended 044 ProviderRuntime contract): browser/screenshot 1 context in PROD,
# 2 elsewhere. Remaining classes are server-owned conservative policies, not per-feature limits.
DEFAULT_WORKLOAD_LIMITS: dict[str, dict[str, int]] = {
"browser": {"PROD": 1, "default": 2},
"screenshot": {"PROD": 1, "default": 2},
"superset_api": {"PROD": 8, "default": 8},
"sql_evidence": {"PROD": 8, "default": 8},
"xlsx": {"PROD": 4, "default": 4},
"agent_evaluation": {"PROD": 2, "default": 2},
}
_LEASE_WORKLOAD_CLASSES = tuple(DEFAULT_WORKLOAD_LIMITS)
# #region ScenarioExecution.CapacityManager.Service.Unavailable [C:2] [TYPE Class] [SEMANTICS capacity,admission,error]
# @ingroup ScenarioExecution
# @BRIEF Typed admission failure carrying a stable taxonomy code.
class CapacityUnavailable(RuntimeError):
pass
# #endregion ScenarioExecution.CapacityManager.Service.Unavailable
def _now() -> datetime:
return datetime.now(UTC)
def _db_now() -> datetime:
return datetime.now(UTC).replace(tzinfo=None)
def _as_aware(value: datetime) -> datetime:
return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
def _default_limit(workload_class: str, environment_class: str) -> int:
policy = DEFAULT_WORKLOAD_LIMITS.get(workload_class)
if policy is None:
logger.explore(
"Unknown workload class rejected", src=_SRC,
payload={"workload_class": workload_class},
error_code="CAPACITY_UNKNOWN_WORKLOAD_CLASS",
)
raise ValueError("CAPACITY_UNKNOWN_WORKLOAD_CLASS")
if environment_class == "PROD":
return policy["PROD"]
return policy["default"]
# #region ScenarioExecution.CapacityManager.Service.Quota [C:4] [TYPE Function] [SEMANTICS capacity,quota,upsert]
# @ingroup ScenarioExecution
# @BRIEF Get or create the server-owned quota row for one (environment, workload_class) pair.
# @POST The returned quota has a positive limit; a concurrent creation race resolves to one row.
def _get_or_create_quota(db: Session, *, environment_id: str, workload_class: str, environment_class: str) -> CapacityQuota:
quota = (
db.query(CapacityQuota)
.filter(CapacityQuota.environment_id == environment_id, CapacityQuota.workload_class == workload_class)
.one_or_none()
)
if quota is not None:
return quota
quota = CapacityQuota(
environment_id=environment_id,
workload_class=workload_class,
limit_units=_default_limit(workload_class, environment_class),
active_units=0,
created_at=_now(),
updated_at=_now(),
)
db.add(quota)
try:
db.flush()
return quota
except IntegrityError:
db.rollback()
existing = (
db.query(CapacityQuota)
.filter(CapacityQuota.environment_id == environment_id, CapacityQuota.workload_class == workload_class)
.one_or_none()
)
if existing is None:
logger.explore(
"Quota creation race lost without a recoverable row", src=_SRC,
payload={"environment_id": environment_id, "workload_class": workload_class},
error_code="CAPACITY_QUOTA_RACE_LOST",
)
raise CapacityUnavailable("CAPACITY_QUOTA_RACE_LOST") from None
logger.reflect("Quota creation race resolved to existing row", src=_SRC, payload={"workload_class": workload_class})
return existing
# #endregion ScenarioExecution.CapacityManager.Service.Quota
def _decrement_quota(db: Session, quota_id: str, *, units: int) -> None:
claimed = db.execute(
update(CapacityQuota)
.where(CapacityQuota.id == quota_id, CapacityQuota.active_units >= units)
.values(active_units=CapacityQuota.active_units - units, updated_at=_now())
)
if claimed.rowcount == 0:
db.execute(update(CapacityQuota).where(CapacityQuota.id == quota_id).values(active_units=0, updated_at=_now()))
logger.reflect("Quota decrement floored at zero", src=_SRC, payload={"quota_id": quota_id, "units": units})
# #region ScenarioExecution.CapacityManager.Service.Claim [C:5] [TYPE Function] [SEMANTICS capacity,admission,claim,lease]
# @ingroup ScenarioExecution
# @BRIEF Atomically admit one provider workload or refuse with a typed capacity code.
# @PRE workload_class is a registered class; 1 <= requested_units <= 4; ttl_seconds > 0.
# @POST On admission a claimed lease exists with expires_at/heartbeat_at set and the quota counter
# reflects the units; on refusal the counter is unchanged and CapacityUnavailable is raised.
def claim_capacity(
db: Session,
*,
environment_id: str,
environment_class: str,
workload_class: str,
provider_id: str,
provider_version: str = "unset",
run_id: str | None = None,
logical_step_id: str | None = None,
requested_units: int = 1,
priority: str = "normal",
ttl_seconds: int = _DEFAULT_TTL_SECONDS,
) -> dict[str, Any]:
if not environment_id.strip() or not provider_id.strip():
logger.explore("Claim rejected: missing environment or provider identity", src=_SRC, error_code="CAPACITY_IDENTITY_INVALID")
raise ValueError("CAPACITY_IDENTITY_INVALID")
if workload_class not in _LEASE_WORKLOAD_CLASSES:
logger.explore("Claim rejected: unknown workload class", src=_SRC, payload={"workload_class": workload_class}, error_code="CAPACITY_UNKNOWN_WORKLOAD_CLASS")
raise ValueError("CAPACITY_UNKNOWN_WORKLOAD_CLASS")
if not isinstance(requested_units, int) or requested_units < 1 or requested_units > _MAX_UNITS_PER_CLAIM:
logger.explore("Claim rejected: units out of range", src=_SRC, payload={"requested_units": requested_units}, error_code="CAPACITY_UNITS_INVALID")
raise ValueError("CAPACITY_UNITS_INVALID")
if ttl_seconds <= 0:
logger.explore("Claim rejected: non-positive ttl", src=_SRC, payload={"ttl_seconds": ttl_seconds}, error_code="CAPACITY_TTL_INVALID")
raise ValueError("CAPACITY_TTL_INVALID")
logger.reason(
"Claim capacity for provider workload", src=_SRC,
payload={"environment_id": environment_id, "workload_class": workload_class, "units": requested_units, "run_id": run_id},
)
quota = _get_or_create_quota(
db,
environment_id=environment_id,
workload_class=workload_class,
environment_class=environment_class,
)
admitted = db.execute(
update(CapacityQuota)
.where(
CapacityQuota.id == quota.id,
CapacityQuota.active_units + requested_units <= CapacityQuota.limit_units,
)
.values(active_units=CapacityQuota.active_units + requested_units, updated_at=_now())
)
if admitted.rowcount != 1:
db.flush()
logger.explore(
"Capacity exhausted for environment/workload pair", src=_SRC,
payload={"environment_id": environment_id, "workload_class": workload_class, "active_units": quota.active_units, "limit_units": quota.limit_units},
error_code="CAPACITY_UNAVAILABLE",
)
raise CapacityUnavailable("CAPACITY_UNAVAILABLE")
now = _db_now()
lease = CapacityLease(
id=str(uuid.uuid4()),
environment_id=environment_id,
workload_class=workload_class,
provider_id=provider_id,
provider_version=provider_version,
run_id=run_id,
logical_step_id=logical_step_id,
requested_units=requested_units,
priority=priority,
status="claimed",
expires_at=now + timedelta(seconds=ttl_seconds),
heartbeat_at=now,
created_at=now,
)
db.add(lease)
db.flush()
db.refresh(quota)
logger.reflect(
"Capacity lease admitted", src=_SRC,
payload={"lease_id": lease.id, "active_units": quota.active_units, "limit_units": quota.limit_units},
)
return {
"lease_id": lease.id,
"environment_id": environment_id,
"workload_class": workload_class,
"requested_units": requested_units,
"status": "claimed",
"expires_at": _as_aware(lease.expires_at).isoformat(),
"active_units": quota.active_units,
"limit_units": quota.limit_units,
}
# #endregion ScenarioExecution.CapacityManager.Service.Claim
# #region ScenarioExecution.CapacityManager.Service.Heartbeat [C:4] [TYPE Function] [SEMANTICS capacity,lease,heartbeat]
# @ingroup ScenarioExecution
# @BRIEF Extend the expiry of one claimed lease; expired or released leases never revive.
# @POST A claimed lease has a later expires_at and a touched heartbeat_at; any other status raises
# CapacityUnavailable("CAPACITY_LEASE_NOT_ACTIVE") and the caller must claim anew.
def heartbeat_capacity(db: Session, lease_id: str, *, ttl_seconds: int = _DEFAULT_TTL_SECONDS) -> dict[str, Any]:
if ttl_seconds <= 0:
raise ValueError("CAPACITY_TTL_INVALID")
lease = db.query(CapacityLease).filter(CapacityLease.id == lease_id).one_or_none()
if lease is None:
logger.explore("Heartbeat for unknown lease", src=_SRC, payload={"lease_id": lease_id}, error_code="CAPACITY_LEASE_NOT_ACTIVE")
raise CapacityUnavailable("CAPACITY_LEASE_NOT_ACTIVE")
if lease.status != "claimed":
logger.explore(
"Heartbeat for a non-claimed lease", src=_SRC,
payload={"lease_id": lease_id, "status": lease.status},
error_code="CAPACITY_LEASE_NOT_ACTIVE",
)
raise CapacityUnavailable("CAPACITY_LEASE_NOT_ACTIVE")
now = _now()
if _as_aware(lease.expires_at) <= now:
_expire_lease_and_free(db, lease, now=_db_now())
db.flush()
logger.explore("Heartbeat arrived after lease expiry", src=_SRC, payload={"lease_id": lease_id}, error_code="CAPACITY_LEASE_NOT_ACTIVE")
raise CapacityUnavailable("CAPACITY_LEASE_NOT_ACTIVE")
lease.expires_at = _db_now() + timedelta(seconds=ttl_seconds)
lease.heartbeat_at = _db_now()
db.flush()
logger.reflect("Lease heartbeat applied", src=_SRC, payload={"lease_id": lease_id, "expires_at": _as_aware(lease.expires_at).isoformat()})
return {"lease_id": lease_id, "status": "claimed", "expires_at": _as_aware(lease.expires_at).isoformat()}
# #endregion ScenarioExecution.CapacityManager.Service.Heartbeat
# #region ScenarioExecution.CapacityManager.Service.Release [C:4] [TYPE Function] [SEMANTICS capacity,lease,release]
# @ingroup ScenarioExecution
# @BRIEF Idempotently release a claimed lease and free its quota units with a zero floor.
# @POST The lease is terminal (released|expired|reconciled) and its units are no longer active;
# repeated releases and release-after-expiry are accepted reflects, not errors.
def release_capacity(db: Session, lease_id: str) -> dict[str, Any]:
lease = db.query(CapacityLease).filter(CapacityLease.id == lease_id).one_or_none()
if lease is None:
logger.explore("Release for unknown lease", src=_SRC, payload={"lease_id": lease_id}, error_code="CAPACITY_LEASE_UNKNOWN")
raise CapacityUnavailable("CAPACITY_LEASE_UNKNOWN")
if lease.status != "claimed":
logger.reflect("Release is idempotent for a terminal lease", src=_SRC, payload={"lease_id": lease_id, "status": lease.status})
return {"lease_id": lease_id, "status": lease.status}
quota = (
db.query(CapacityQuota)
.filter(CapacityQuota.environment_id == lease.environment_id, CapacityQuota.workload_class == lease.workload_class)
.one_or_none()
)
lease.status = "released"
lease.released_at = _db_now()
if quota is not None:
_decrement_quota(db, quota.id, units=lease.requested_units)
db.flush()
logger.reflect("Lease released", src=_SRC, payload={"lease_id": lease_id, "workload_class": lease.workload_class})
return {"lease_id": lease_id, "status": "released"}
# #endregion ScenarioExecution.CapacityManager.Service.Release
# #region ScenarioExecution.CapacityManager.Service.Expire [C:4] [TYPE Function] [SEMANTICS capacity,lease,expiry,reconcile]
# @ingroup ScenarioExecution
# @BRIEF Mark expired claimed leases and free their quota units in a bounded idempotent pass.
# @POST Every claimed lease past expiry becomes expired exactly once and its units are freed;
# repeated reconciliations over the same window are no-ops.
def reconcile_expired_leases(db: Session, *, limit: int = _RECONCILE_BATCH) -> dict[str, Any]:
now = _db_now()
if limit <= 0:
raise ValueError("CAPACITY_RECONCILE_LIMIT_INVALID")
leases = (
db.query(CapacityLease)
.filter(CapacityLease.status == "claimed", CapacityLease.expires_at <= now)
.limit(limit)
.all()
)
freed_by_quota: dict[str, int] = {}
for lease in leases:
quota_id = _expire_lease_and_free(db, lease, now=now)
if quota_id is not None:
freed_by_quota[quota_id] = freed_by_quota.get(quota_id, 0) + lease.requested_units
db.flush()
if leases:
logger.reflect(
"Expired leases reconciled", src=_SRC,
payload={"expired": len(leases), "quota_ids": sorted(freed_by_quota)},
)
return {"expired": len(leases), "by_quota": freed_by_quota, "reconciled_at": _as_aware(now).isoformat()}
# #region ScenarioExecution.CapacityManager.Service.ExpireOne [C:3] [TYPE Function] [SEMANTICS capacity,lease,expiry]
# @ingroup ScenarioExecution
# @BRIEF CAS-expire one claimed lease and free its quota units exactly once.
# @POST Returns the quota id when this call performed the expiry; None when the lease was already
# terminal (concurrent expiry/release), so units are never double-freed.
def _expire_lease_and_free(db: Session, lease: CapacityLease, *, now: datetime) -> str | None:
expired = db.execute(
update(CapacityLease)
.where(CapacityLease.id == lease.id, CapacityLease.status == "claimed")
.values(status="expired", released_at=now)
)
if expired.rowcount != 1:
return None
logger.explore(
"Lease expired without release", src=_SRC,
payload={"lease_id": lease.id, "workload_class": lease.workload_class},
error_code="CAPACITY_LEASE_EXPIRED",
)
quota = (
db.query(CapacityQuota)
.filter(CapacityQuota.environment_id == lease.environment_id, CapacityQuota.workload_class == lease.workload_class)
.one_or_none()
)
if quota is not None:
_decrement_quota(db, quota.id, units=lease.requested_units)
return quota.id
return None
# #endregion ScenarioExecution.CapacityManager.Service.ExpireOne
# #endregion ScenarioExecution.CapacityManager.Service.Expire
# #region ScenarioExecution.CapacityManager.Service.Snapshot [C:2] [TYPE Function] [SEMANTICS capacity,health,telemetry]
# @ingroup ScenarioExecution
# @BRIEF Read-only quota snapshot for health and admission telemetry; never includes secrets.
def capacity_snapshot(db: Session, *, environment_id: str, workload_class: str) -> dict[str, Any]:
quota = (
db.query(CapacityQuota)
.filter(CapacityQuota.environment_id == environment_id, CapacityQuota.workload_class == workload_class)
.one_or_none()
)
if quota is None:
return {"environment_id": environment_id, "workload_class": workload_class, "limit_units": None, "active_units": 0}
return {
"environment_id": environment_id,
"workload_class": workload_class,
"limit_units": quota.limit_units,
"active_units": quota.active_units,
}
# #endregion ScenarioExecution.CapacityManager.Service.Snapshot
# #endregion ScenarioExecution.CapacityManager.Service