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
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1087,6 +1087,7 @@ jobs:
tests/integration/test_release_gate_policy_single_active_postgres.py
tests/integration/test_migration_0211_0212_postgres.py
tests/integration/test_release_gate_summary_postgres.py
tests/integration/test_release_decision_analysis_changed_postgres.py
tests/integration/test_releases_list_gate_owner_postgres.py
tests/test_compliance_packs_project_list.py
tests/integration/test_migration_0213_postgres.py
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ contain breaking changes; [UPGRADING.md](UPGRADING.md) lists them).

### Fixed

- Release gate: the quick look (a run with no deep investigation yet) is scored with the project's effective policy (its thresholds, weights, bands, P0 cap and open-defect rule) instead of built-in thresholds with half the policy, and names that one policy; rules it cannot check before a deep investigation are listed as not checked. With no published policy nothing changes (D-142). The gate card shows the thresholds and pass-rate bands the verdict used ("Go under risk 20 and at 90% or more · No-Go at risk 55 or under 63% · Pass-rate bands: No-Go under 90%, Conditional under 95%") and says when a band held the verdict back (D-104), and a stored decision says when a test's category was corrected after it was made, without changing it (D-97).
- Gate policies: a draft that was never published can be deleted (`DELETE /api/v1/release-gate-policies/{policy_id}`, administrators; a published or referenced version is refused with 409); the list shows active policies and drafts first and older versions under **Past versions**, and says when no policy is active (D-141). **New version from this** asks before creating the draft (D-140).
- Run page: a test's attribution badge follows a category that changes while the page is open (D-72). Deep investigation: a root-cause stage answered by more than one engine reads "mixed" and shows the split ("1 model · 3 rules"), also in the decision trail and MCP (D-156).
- Ask AI with a local model: when the model refuses a request that carried tools (HTTP 4xx), the turn is asked again without tools instead of failing; a model whose refusal names tools is remembered as tool-free. A refusal that remains no longer says "Try rephrasing" and is not offered as a retry; an internal error is no longer reported as the provider's refusal (D-143).
- Local models: one model call no longer shares its time limit with the escalation that follows it, a local provider (Ollama) analyses one failure at a time unless `LLM_MAX_CONCURRENT_ANALYSES` is set, and `.env.example` ships the code's 300 s timeout instead of 120 s (D-144).
- Run compare: the narrative says when it covers one suite ("checkout suite only"), and a model summary whose failed/total/pass-rate figures contradict the runs is replaced by the deterministic summary (D-148).
Expand Down
20 changes: 20 additions & 0 deletions UPGRADING.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,26 @@ Existing usernames that contain `@` keep working for sign-in.
| `POST /deep-investigate/{run_id}` in Rules mode | accepted | 422 "requires LLM or Auto mode" |
| `POST /analyze` for a test with a human correction | returns the correction | the engine's answer, replacing the correction |

### Release gate and gate policies (batch 8)

- **The quick look follows a published gate policy whole.** A project with a
published policy can see a different quick-look verdict for the same run:
its thresholds and weights now apply, not only its pass-rate bands and P0
cap. Projects without a policy see no change. Stored decisions are not
re-evaluated. `GET /api/v1/release-readiness/{run_id}` names the policy really
used (`policy_level`, `policy_id`, `policy_version`) and lists the rules a
quick look cannot check in `input_snapshot.rules_not_checked`.
- **The same response gains `analysis_changed_since` and
`analysis_changed_at`** for a stored decision whose run had a category
correction saved after its analyses were read, and `pass_rate_bands` /
`band_held_back` for the pass-rate band applied at read time.
- **`DELETE /api/v1/release-gate-policies/{policy_id}`** (administrators)
deletes a never-published draft and answers 409 for any other version; the
delete is recorded as `policy.updated`.
- **Decision trail stages gain an optional `mode_distribution`**, and a
root-cause stage answered by more than one engine stores `analysis_mode`
`mixed`.

### The local model path (batch 7)

- **`AI_TIMEOUT_SECONDS` in `.env.example` is now 300** (the code default). An
Expand Down
15 changes: 14 additions & 1 deletion backend/app/agents/analysis_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@
# Non-LLM engines and deterministic fallbacks are repeatable; retrying them
# just burns CPU/LLM fallback budget and returns the same low-confidence answer.
_DETERMINISTIC_ANALYSIS_ENGINES = {"rules", "ml", "blocked"}
# D-156 (review F6): the per-test ``mode_used`` values that are an engine
# answering (analysis_router: llm | ml | rules). Not engines: "hint"
# (classification_hint_service), "human_corrected" (analysis_corrections) and
# "unknown" (no engine recorded). Only these count towards a "mixed" stage.
_ANSWERING_ENGINES = frozenset({"llm", "ml", "rules"})
_METADATA_CACHE_TTL_SECONDS = 30
_METADATA_CACHE_MAX_ENTRIES = 64
_METADATA_CACHE: dict[str, tuple[float, dict[str, dict]]] = {}
Expand Down Expand Up @@ -597,6 +602,14 @@ async def run(self, state: dict) -> dict:
if audit.get("fallback_from"):
fallback_count += 1
dominant_mode = max(mode_counts, key=mode_counts.get) if mode_counts else None
# D-156: three rules answers and one model answer used to read "rules".
# When the tests ran on more than one engine the stage says "mixed" and
# the split stays in result_data.mode_distribution (the decision trail
# exposes it per stage). Only an engine that answered counts towards
# "mixed" (_ANSWERING_ENGINES): a QA lead's hint, a replayed human
# correction or an unrecorded engine ("unknown") is not a second engine.
recorded_engines = [m for m in mode_counts if m in _ANSWERING_ENGINES]
stage_mode = "mixed" if len(recorded_engines) > 1 else dominant_mode
stage_fallback_reason = (
f"{fallback_count}/{total_analysed} tests fell back from requested engine"
if fallback_count else None
Expand All @@ -619,7 +632,7 @@ async def run(self, state: dict) -> dict:
"budget_skipped": len(budget_skipped),
"config_skipped": len(threshold_skipped),
},
analysis_mode=dominant_mode,
analysis_mode=stage_mode,
fallback_reason=stage_fallback_reason,
project_id=project_id,
)
Expand Down
16 changes: 16 additions & 0 deletions backend/app/models/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -7110,6 +7110,13 @@ class ReleaseCouncilResponse(BaseModel):
# e.g. ``["p0_defects:2>0"]``.
release_readiness_band: Optional[str] = None
band_downgrades: List[str] = []
# Batch 8 review F1: the band edges the read-time band floor applied
# (``{orange_min, yellow_min, green_min}``, the classifier's defaults filled
# in): under orange is No-Go, orange is Conditional. ``None`` with no
# active policy. ``band_held_back`` is True when the pass-rate band itself
# made the verdict stricter (a hard cap is named in ``band_downgrades``).
pass_rate_bands: Optional[dict] = None
band_held_back: bool = False
# E8.4: the human-review gate on the value CI reads (section 8.2). While
# the gate is enforced, an unreviewed AI decision reads PENDING_REVIEW (or
# ADVISORY_<value> with allow_advisory) and the model's value moves here.
Expand All @@ -7123,6 +7130,12 @@ class ReleaseCouncilResponse(BaseModel):
# quick-look view: no decision has been stored, so there is no time.
created_at: Optional[datetime] = None
updated_at: Optional[datetime] = None
# D-97: a person changed a test's category in this run after the stored
# decision read its analyses. The decision is NOT recomputed (a signed
# decision must not change silently); the gate says "re-evaluate".
# Set by ``GET /release-readiness/{run_id}`` only; False on a quick look.
analysis_changed_since: bool = False
analysis_changed_at: Optional[datetime] = None


class ReleaseCouncilOverrideRequest(BaseModel):
Expand Down Expand Up @@ -9655,6 +9668,9 @@ class StageDecisionSummary(BaseModel):
completed_at: Optional[datetime] = None
duration_seconds: Optional[float] = None
analysis_mode: Optional[str] = None # llm|ml|rules|auto|mixed
# D-156: tests per engine for a stage that analysed tests (root cause);
# "mixed" above means more than one key here. None for other stages.
mode_distribution: Optional[Dict[str, int]] = None
fallback_used: Optional[bool] = None
fallback_reason: Optional[str] = None
route_rationale: Optional[str] = None
Expand Down
114 changes: 103 additions & 11 deletions backend/app/routers/release_gate_policies.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
import uuid
from typing import Optional, Sequence

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi import APIRouter, Depends, HTTPException, Response, status
from sqlalchemy import func, or_, select, text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.exc import IntegrityError, InvalidRequestError
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm.exc import StaleDataError

from app.core.deps import (
_api_key_bound_project,
Expand All @@ -16,7 +17,14 @@
require_role,
)
from app.db.postgres import get_db
from app.models.postgres import ReleaseDecision, ReleaseGatePolicy, TestRun, User, UserRole
from app.models.postgres import (
ReleaseDecision,
ReleaseGateDecision,
ReleaseGatePolicy,
TestRun,
User,
UserRole,
)
from app.models.schemas import (
PolicyDocument,
PolicySimulateRequest,
Expand Down Expand Up @@ -49,6 +57,19 @@
"Another policy version was created for this scope at the same moment. Try again."
)
ALREADY_PUBLISHED_DETAIL = "Policy is already published"
#: D-141: what deleting a version that was ever published is told. Past
#: verdicts name the version they were judged by, so it is kept.
DELETE_PUBLISHED_DETAIL = (
"Only a draft that was never published can be deleted. A published version "
"is kept because past verdicts name it; deactivate it instead."
)
#: Batch 8 review F4: what a publish or an edit is told when another admin
#: deleted the draft (D-141) between this request's read and its write.
DRAFT_DELETED_DETAIL = "This draft was deleted."
#: D-141: what deleting a draft a stored decision points at is told.
DELETE_REFERENCED_DETAIL = (
"This draft is named by a stored release decision, so it is kept."
)

#: The indexes whose violation is a scope race (migration 0210, plus the
#: project-scope version constraint of 0032). Any other IntegrityError is a
Expand Down Expand Up @@ -388,13 +409,18 @@ async def update_policy(
changed = [field for field, value in update_data.items() if getattr(policy, field) != value]
for field, value in update_data.items():
setattr(policy, field, value)
if changed:
await _record_policy_event(
db, policy, "policy.updated", current_user,
context={"changed": ", ".join(changed)}, changed_fields=changed,
)

await db.commit()
try:
if changed:
await _record_policy_event(
db, policy, "policy.updated", current_user,
context={"changed": ", ".join(changed)}, changed_fields=changed,
)
await db.commit()
except StaleDataError:
# Review F4: the draft was deleted (D-141) after the read above, so the
# UPDATE matched no row. A plain 404, not a 500; nothing is written.
await db.rollback()
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=DRAFT_DELETED_DETAIL)
await db.refresh(policy)
logger.info("Policy updated: %s v%d by user_id=%s", policy.id, policy.version, current_user.id)
return policy
Expand Down Expand Up @@ -427,7 +453,12 @@ async def publish_policy(
await _lock_scope(db, policy.project_id)
# Re-read under the lock: the same draft published by someone else is no
# longer a draft.
await db.refresh(policy)
try:
await db.refresh(policy)
except InvalidRequestError:
# Review F4: the row is gone -- another admin deleted the draft (D-141)
# while this request waited for the lock. A plain 404, not a 500.
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=DRAFT_DELETED_DETAIL)
if not policy.is_draft:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=ALREADY_PUBLISHED_DETAIL)
current = await _active_ids_in_scope(db, policy.project_id, policy.id)
Expand Down Expand Up @@ -508,6 +539,67 @@ async def deactivate_policy(
return policy


@router.delete("/{policy_id}", status_code=204)
async def delete_policy(
policy_id: uuid.UUID,
# N20: _enforce_policy_binding below confines a project-bound key.
current_user: User = Depends(require_role(UserRole.ADMIN, allow_project_key=True)),
db: AsyncSession = Depends(get_db),
):
"""Delete a draft that was never published (ADMIN only) (D-141).

A version that was ever published stays: past verdicts and the version
history name it, so it is deactivated instead (409). A draft a stored
release decision points at is kept too (409). Records ``policy.updated``
with ``changed: draft deleted`` in the same transaction, the way
deactivate records its edit of the active flag.
"""
result = await db.execute(
select(ReleaseGatePolicy).where(ReleaseGatePolicy.id == policy_id)
)
policy = result.scalar_one_or_none()
if not policy:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Policy not found")
_enforce_policy_binding(current_user, policy.project_id)
if policy.project_id is not None:
# The same scope call create and get make (code review round 4): an
# admin passes by role, a bound key only for its own project.
from app.core.deps import resolve_project_scope # noqa: PLC0415

await resolve_project_scope(db, current_user, str(policy.project_id))

# Serialise against a concurrent publish of this draft in the same scope,
# then re-read it: a publish that committed first makes it a 409 here.
await _lock_scope(db, policy.project_id)
result = await db.execute(
select(ReleaseGatePolicy)
.where(ReleaseGatePolicy.id == policy_id)
.execution_options(populate_existing=True)
)
policy = result.scalar_one_or_none()
if not policy:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Policy not found")
if not policy.is_draft or policy.is_active or policy.activated_at is not None:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=DELETE_PUBLISHED_DETAIL)

for model in (ReleaseDecision, ReleaseGateDecision):
referenced = await db.execute(
select(model.id).where(model.policy_id == policy.id).limit(1)
)
if referenced.scalar_one_or_none() is not None:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=DELETE_REFERENCED_DETAIL)

await _record_policy_event(
db, policy, "policy.updated", current_user,
context={"changed": "draft deleted"}, changed_fields=["deleted"],
before={"is_draft": True}, after={"deleted": True},
)
await db.delete(policy)
await db.commit()
logger.info("Policy draft deleted: %s v%d by user_id=%s", policy.id, policy.version, current_user.id)
return Response(status_code=status.HTTP_204_NO_CONTENT)


@router.post("/simulate", response_model=PolicySimulateResponse)
async def simulate_policy(
payload: PolicySimulateRequest,
Expand Down
18 changes: 17 additions & 1 deletion backend/app/routers/release_readiness.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@
)
from app.services.activity.service import ActorRef, record as record_activity
from app.services.notification import gate_notifications
from app.services.release_council_service import apply_override, get_release_council
from app.services.release_council_service import (
analysis_changed_since,
apply_override,
decision_evaluated_at,
get_release_council,
)

logger = logging.getLogger("routers.release_readiness")

Expand Down Expand Up @@ -99,6 +104,17 @@ async def get_release_decision(
)
if allow_advisory and response.recommendation.startswith("ADVISORY_"):
await db.commit()
# D-97: say when a person changed a test's category after this stored
# decision read the run's analyses. Read-only; the decision is untouched.
decided_at = None if council.synthesized else decision_evaluated_at(council)
if decided_at is not None:
# The decision's pipeline: its root-cause stage start is when the
# analyses and corrections it scored were read (review F3).
changed_at = await analysis_changed_since(db, run_id, decided_at, pipeline_run_id)
if changed_at is not None:
response = response.model_copy(
update={"analysis_changed_since": True, "analysis_changed_at": changed_at}
)
return response


Expand Down
9 changes: 5 additions & 4 deletions backend/app/services/activity/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,10 +368,11 @@ def _spec(
_spec("project.imported", "configuration", "project", "Project {entity_label} was imported from {source}", "outcome"),
_spec("policy.created", "configuration", "policy", "Release gate policy {entity_label} was created"),
_spec("policy.updated", "configuration", "policy", "Release gate policy {entity_label} changed: {changed}"),
# W21 ACT-01: no ``policy.deleted`` -- gate policies are versioned and
# never deleted (a superseded version is deactivated, which records
# ``policy.updated``), so the name was removed rather than left as a
# filter that matches nothing.
# W21 ACT-01: no ``policy.deleted`` -- a published gate policy is never
# deleted (a superseded version is deactivated, which records
# ``policy.updated``). Since D-141 a never-published draft can be deleted;
# that also records ``policy.updated`` ("draft deleted"), so the feed's
# policy filter keeps one name for every change.
_spec("policy.activated", "configuration", "policy", "Release gate policy {entity_label} was activated"),
_spec("agent_config.updated", "configuration", "project", "Agent {entity_label} configuration changed to version {config_version}: {changed}", "outcome", _HUMAN_OR_KEY),
_spec("workflow.created", "configuration", "workflow", "Workflow {entity_label} version {version} was created", "outcome", _HUMAN_OR_KEY),
Expand Down
16 changes: 16 additions & 0 deletions backend/app/services/decision_trail_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,21 @@ async def _load_workflow_events(pipeline_run: AgentPipelineRun) -> list[dict[str
return fallback_events


def _stage_mode_distribution(stage: AgentStageResult) -> Optional[dict[str, int]]:
"""D-156: the per-engine split a stage stored in ``result_data``, or None.

The Root Cause stage records ``analysis_mode="mixed"`` when its tests ran
on more than one engine; this is the split the page prints beside it.
"""
result_data = getattr(stage, "result_data", None)
if not isinstance(result_data, dict):
return None
dist = result_data.get("mode_distribution")
if not isinstance(dist, dict):
return None
return {str(k): int(v) for k, v in dist.items() if isinstance(v, int) and not isinstance(v, bool)}


def _summarize_stage(stage: AgentStageResult) -> dict[str, Any]:
return {
"stage_name": stage.stage_name,
Expand All @@ -173,6 +188,7 @@ def _summarize_stage(stage: AgentStageResult) -> dict[str, Any]:
"completed_at": stage.completed_at,
"duration_seconds": _duration_seconds(stage.started_at, stage.completed_at),
"analysis_mode": getattr(stage, "analysis_mode", None),
"mode_distribution": _stage_mode_distribution(stage),
"fallback_used": bool(stage.fallback_used) if stage.fallback_used is not None else None,
"fallback_reason": getattr(stage, "fallback_reason", None),
"route_rationale": stage.route_rationale,
Expand Down
Loading
Loading