diff --git a/.secrets.baseline b/.secrets.baseline index adf1d6cf..7a817447 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -1504,7 +1504,7 @@ "filename": "tests/test_llm.py", "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", "is_verified": false, - "line_number": 625 + "line_number": 623 } ] }, diff --git a/docs/agent-denial-recovery.md b/docs/agent-denial-recovery.md index 895b6ebc..73dec8be 100644 --- a/docs/agent-denial-recovery.md +++ b/docs/agent-denial-recovery.md @@ -14,8 +14,8 @@ an operation without approval. Completed decisions, including Council and OPA approvals/denials, omit `retryable`. Other responses with no affirmative overload retry hint omit it -too. The Python models retain their `False` default for existing callers, but -serialization omits only that field when false; other defaults remain intact. +too. The Python models retain their `False` default for existing callers, and +serialization omits the field when false. Clients should use `response.get("retryable", False)` and check `status`, not assume the field is present or treat its absence as authorization. The field remains optional in the output schema. @@ -24,9 +24,27 @@ For `status: denied`, the response's `guidance` starts with a deterministic note that safer revisions within the user's authorized goal need fresh authorization, followed by the original Council or OPA guidance. This reaches clients that read tool results without consulting the -output schema. Member votes and reasoning remain unchanged. Approved and error -responses retain their existing guidance, except for the clearer overload -instruction described above. +output schema. Member votes and reasoning remain unchanged. + +When a packaged-file review fails, a deterministic native policy denial +takes precedence. `council_authorize` returns `status: denied`, omits +`error_code`, and issues no Writ. Follow the normal denial guidance. If the +request fails admission, for example due to missing required justification or +a full pending queue, the response reports the admission error without +`review_failed`. + +An unavailable reviewer or invalid model decision contributes no vote. When the +valid votes reach the configured quorum, the Council returns the resulting +approval or denial without an `error_code`. + +For an admitted request whose required review cannot complete, +`council_authorize` returns `status: error` and +`error_code: review_failed`, without a Writ. `council_propose_intent` returns +`success: false` and `state: failed` with the same error code. Any member +votes in the response are the valid results that arrived before the review +ended. Handle the failure before retrying. The error code does not grant +permission to execute or carry the admission-control retry hint. Monitoring +counts this outcome as a review error. An agent may use the guidance to propose a safer operation within the user's authorized goal. Every revised request requires a new authorization decision; diff --git a/nomos/level_2/quorum/manager.py b/nomos/level_2/quorum/manager.py index b51d9ecb..aaf55b0c 100644 --- a/nomos/level_2/quorum/manager.py +++ b/nomos/level_2/quorum/manager.py @@ -43,6 +43,7 @@ class QuorumResult: status: QuorumStatus record: VoteRecord message: str + recorded: bool = False class QuorumManager: @@ -203,12 +204,13 @@ def cast_vote( ) if auto_close and record.is_decided(): - return self._close_vote(record) + return self._close_vote(record, recorded=True) return QuorumResult( status=QuorumStatus.PENDING, record=record, message=f"Vote recorded. Approve: {record.approve_weight}/{record.required_weight}", + recorded=True, ) def revise_vote( @@ -284,16 +286,23 @@ def revise_vote( ) if auto_close and record.is_decided(): - return self._close_vote(record) + return self._close_vote(record, recorded=True) return QuorumResult( status=QuorumStatus.PENDING, record=record, message=f"Vote revised (round {debate_round}). " f"Approve: {record.approve_weight}/{record.required_weight}", + recorded=True, ) - def finalize_vote(self, intent_id: str, *, allow_pending: bool = False) -> QuorumResult: + def finalize_vote( + self, + intent_id: str, + *, + allow_pending: bool = False, + partial_voters: set[str] | None = None, + ) -> QuorumResult: """Finalize a vote after a batch of ballots has been recorded.""" record = self._records.get(intent_id) if record is None: @@ -316,12 +325,20 @@ def finalize_vote(self, intent_id: str, *, allow_pending: bool = False) -> Quoru message=f"Approve: {record.approve_weight}/{record.required_weight}", ) + if partial_voters is not None: + # A missing debate ballot must not leave an earlier ballot in the tally. + record.votes = { + voter_id: vote + for voter_id, vote in record.votes.items() + if voter_id in partial_voters + } + if record.is_decided(): return self._close_vote(record) active_member_ids = {member.member_id for member in self.get_active_members()} all_active_members_voted = active_member_ids.issubset(record.votes.keys()) - if all_active_members_voted and not allow_pending: + if partial_voters is None and all_active_members_voted: return self._close_vote(record, outcome=VoteType.DENY) return QuorumResult( @@ -330,7 +347,9 @@ def finalize_vote(self, intent_id: str, *, allow_pending: bool = False) -> Quoru message=f"Approve: {record.approve_weight}/{record.required_weight}", ) - def _close_vote(self, record: VoteRecord, outcome: VoteType | None = None) -> QuorumResult: + def _close_vote( + self, record: VoteRecord, outcome: VoteType | None = None, *, recorded: bool = False + ) -> QuorumResult: """Close a vote and record the outcome.""" record.closed_at = self._clock.now() record.outcome = outcome or record.get_outcome() @@ -356,6 +375,7 @@ def _close_vote(self, record: VoteRecord, outcome: VoteType | None = None) -> Qu status=status, record=record, message=f"Vote closed: {status.value}", + recorded=recorded, ) def forget_closed_vote(self, intent_id: str) -> bool: diff --git a/nomos/level_4/council/council.py b/nomos/level_4/council/council.py index 2c777dff..6a766c3e 100644 --- a/nomos/level_4/council/council.py +++ b/nomos/level_4/council/council.py @@ -813,6 +813,9 @@ def cast_member_vote( auto_close=finalize, ) + if not finalize and not result.recorded: + return SubmitResult(success=False, workflow=workflow, error=result.message) + workflow.vote_record = result.record self._apply_quorum_result(workflow, result.status, reason) return SubmitResult(success=True, workflow=workflow) @@ -857,12 +860,19 @@ def revise_vote( auto_close=finalize, ) + if not finalize and not result.recorded: + return SubmitResult(success=False, workflow=workflow, error=result.message) + workflow.vote_record = result.record self._apply_quorum_result(workflow, result.status, reason) return SubmitResult(success=True, workflow=workflow) def finalize_intent_review( - self, intent_id: str, *, allow_pending: bool = False + self, + intent_id: str, + *, + allow_pending: bool = False, + partial_voters: set[str] | None = None, ) -> SubmitResult: """Finalize a batched council review round and sync workflow state.""" self._prune_terminal_workflows() @@ -873,7 +883,12 @@ def finalize_intent_review( if workflow.state != WorkflowState.AWAITING_APPROVAL: return SubmitResult(success=True, workflow=workflow) - result = self._quorum_manager.finalize_vote(intent_id, allow_pending=allow_pending) + if partial_voters is None: + result = self._quorum_manager.finalize_vote(intent_id, allow_pending=allow_pending) + else: + result = self._quorum_manager.finalize_vote( + intent_id, allow_pending=allow_pending, partial_voters=partial_voters + ) workflow.vote_record = result.record self._apply_quorum_result(workflow, result.status, workflow.denial_reason) return SubmitResult(success=True, workflow=workflow) @@ -889,10 +904,13 @@ def abort_intent_review(self, intent_id: str, reason: str) -> bool: releases that capacity and stops a half-written review from being mistaken for work still in flight. - Idempotent: unknown or already-terminal intents return False. + Idempotent: closed ballots are left alone. An expired or evicted workflow + may still have an open ballot; discard it without changing the workflow. """ workflow = self._workflows.get(intent_id) - if workflow is None or workflow.is_terminal: + if workflow is None or workflow.state == WorkflowState.EXPIRED: + return self._quorum_manager.abort_vote(intent_id) + if workflow.is_terminal: return False try: diff --git a/nomos/llm/council_agent.py b/nomos/llm/council_agent.py index fc77d924..7b51b4d7 100644 --- a/nomos/llm/council_agent.py +++ b/nomos/llm/council_agent.py @@ -15,9 +15,10 @@ import math import re import time +from dataclasses import dataclass from typing import TYPE_CHECKING, Any, TypeVar -from pydantic import BaseModel, Field, ValidationError, field_validator +from pydantic import BaseModel, Field, field_validator from nomos.config.settings import CouncilMemberConfig, LLMBackendConfig, LLMProvider from nomos.level_0.types import AttestationVector, Intent @@ -87,6 +88,15 @@ def _token_count(usage: dict[str, Any]) -> int: return int(input_tokens or 0) + int(output_tokens or 0) +@dataclass(frozen=True) +class ReviewFailure: + """An operational failure with call metadata and no review decision.""" + + reasoning: str + timing: dict[str, float] + execution: LLMExecution | None + + class IntentEvaluation(BaseModel): """Structured evaluation result from an LLM council member.""" @@ -575,16 +585,7 @@ def format_code_review_result_json(review: IntentEvaluation) -> str: def _describe_failure(error: Exception) -> str: - """Name the failure kind, not just its text. - - A member that cannot evaluate reports its reason to an operator who has to - decide what to do about it, and the remedies differ: wait out a rate limit, - raise a timeout budget, or change a model that is refusing requests. - `str(error)` alone loses that distinction -- an SDK timeout renders as - "Request timed out." with no indication of which provider produced it, so the - same sentence appears whether the endpoint is slow, throttled, or rejecting. - """ - detail = str(error).strip() or error.__class__.__name__ + """Describe a failure without retaining provider or parser payloads.""" if isinstance(error, LLMTimeoutError): kind = "provider timeout" elif isinstance(error, LLMRateLimitError): @@ -594,7 +595,7 @@ def _describe_failure(error: Exception) -> str: status = getattr(error, "status_code", None) if status is None: status = getattr(getattr(error, "response", None), "status_code", None) - return f"{kind} (HTTP {status}): {detail}" if status is not None else f"{kind}: {detail}" + return f"{kind} (HTTP {status})" if type(status) is int and 100 <= status <= 599 else kind class _RetryExhaustedError(Exception): @@ -609,7 +610,7 @@ def __init__( output_tokens: int | None = None, execution: LLMExecution | None = None, ): - super().__init__(str(last_error)) + super().__init__(_describe_failure(last_error)) self.attempts = attempts self.last_error = last_error self.input_tokens = input_tokens @@ -626,6 +627,16 @@ def provider(self, backend: LLMBackend) -> str: return self.execution.attempts[-1].provider return backend.provider_name() + def as_review_failure(self, backend: LLMBackend) -> ReviewFailure: + return ReviewFailure( + reasoning=( + f"Review failed after {self.attempts} attempts via {self.provider(backend)}: " + f"{self.failure_description()}." + ), + timing=self.timing(), + execution=self.execution, + ) + def timing(self) -> dict[str, float]: """Telemetry for the failed call: only the tokens its attempts were billed. @@ -952,26 +963,14 @@ async def _complete_with_retry( # attempt timing out says little about the second. # The shared budget check below still bounds total time. if attempt >= max_retries or time.monotonic() - start > retry_budget_seconds: - logger.error( - "%s timed out after %d attempts: %s (cause=%s)", - log_ctx, - attempt + 1, - e, - type(e.__cause__).__name__, - ) + logger.error("%s timed out after %d attempts", log_ctx, attempt + 1) raise _RetryExhaustedError( attempt + 1, e, input_tokens=input_tokens if responded else None, output_tokens=output_tokens if responded else None, ) from e - logger.warning( - "%s timed out on attempt %d, retrying: %s (cause=%s)", - log_ctx, - attempt + 1, - e, - type(e.__cause__).__name__, - ) + logger.warning("%s timed out on attempt %d, retrying", log_ctx, attempt + 1) attempt += 1 continue except Exception as e: @@ -987,7 +986,7 @@ async def _complete_with_retry( log_ctx, attempt + 1, " (retry budget exhausted)" if out_of_budget and attempt < max_retries else "", - e, + _describe_failure(e), ) raise _RetryExhaustedError( attempt + 1, @@ -1000,7 +999,7 @@ async def _complete_with_retry( log_ctx, attempt + 1, 1 + max_retries, - e, + _describe_failure(e), ) await asyncio.sleep(delay) attempt += 1 @@ -1054,7 +1053,7 @@ def display_name(self) -> str: def provider_name(self) -> str: return self._backend.provider_name() - async def evaluate_intent(self, intent: Intent) -> IntentEvaluation: + async def evaluate_intent(self, intent: Intent) -> IntentEvaluation | ReviewFailure: """ Evaluate an intent and return a structured decision. @@ -1084,7 +1083,7 @@ async def evaluate_intent(self, intent: Intent) -> IntentEvaluation: messages, temperature=self._temperature, max_tokens=self._max_tokens, - parse=lambda content: _parse_evaluation(content, raise_on_parse_error=True), + parse=_parse_evaluation, log_ctx=f"Council member {self.member_id} evaluating {intent.intent_id}", max_retries=self._max_retries, retry_budget_seconds=self._retry_budget_seconds, @@ -1092,17 +1091,7 @@ async def evaluate_intent(self, intent: Intent) -> IntentEvaluation: call_candidates=self._call_candidates, ) except _RetryExhaustedError as e: - return IntentEvaluation( - decision="deny", - reasoning=( - f"Evaluation failed after {e.attempts} attempts via" - f" {e.provider(self._backend)}:" - f" {e.failure_description()}. Defaulting to deny." - ), - risk_concerns=["LLM evaluation failure"], - timing=e.timing(), - execution=e.execution, - ) + return e.as_review_failure(self._backend) logger.info( "llm_latency role=council_member member=%s provider=%s intent=%s attempt=%d " @@ -1123,7 +1112,7 @@ async def debate_evaluate( self, intent: Intent, debate_context: str, - ) -> IntentEvaluation: + ) -> IntentEvaluation | ReviewFailure: """ Re-evaluate an intent with debate context using this member's own backend. @@ -1163,7 +1152,7 @@ async def debate_evaluate( messages, temperature=self._temperature, max_tokens=self._max_tokens, - parse=lambda content: _parse_evaluation(content, raise_on_parse_error=True), + parse=_parse_evaluation, log_ctx=f"Council member {self.member_id} debating {intent.intent_id}", max_retries=self._max_retries, retry_budget_seconds=self._retry_budget_seconds, @@ -1171,17 +1160,7 @@ async def debate_evaluate( call_candidates=self._call_candidates, ) except _RetryExhaustedError as e: - return IntentEvaluation( - decision="deny", - reasoning=( - f"Debate evaluation failed after {e.attempts} attempts via" - f" {e.provider(self._backend)}:" - f" {e.failure_description()}. Defaulting to deny." - ), - risk_concerns=["LLM debate evaluation failure"], - timing=e.timing(), - execution=e.execution, - ) + return e.as_review_failure(self._backend) logger.info( "llm_latency role=council_member_debate member=%s provider=%s intent=%s " @@ -1303,7 +1282,7 @@ def _default_system_prompt() -> str: ] ) - async def review_intent_files(self, intent: Intent) -> IntentEvaluation: + async def review_intent_files(self, intent: Intent) -> IntentEvaluation | ReviewFailure: """Review packaged files and return advisory analysis.""" if not intent.packaged_files: return IntentEvaluation( @@ -1331,15 +1310,7 @@ async def review_intent_files(self, intent: Intent) -> IntentEvaluation: call_candidates=self._call_candidates, ) except _RetryExhaustedError as e: - failed = _failed_code_review_evaluation( - intent, - f"Code review failed after {e.attempts} attempts via" - f" {e.provider(self._backend)}:" - f" {e.failure_description()}.", - ) - failed.timing = e.timing() - failed.execution = e.execution - return failed + return e.as_review_failure(self._backend) logger.info( "llm_latency role=code_review provider=%s intent=%s attempt=%d " @@ -1366,13 +1337,8 @@ def _parse_code_review_evaluation(content: str, intent: Intent) -> CodeReviewEva data = _load_json_object(content) data.pop("execution", None) evaluation = CodeReviewEvaluation.model_validate(data) - except (json.JSONDecodeError, TypeError, ValidationError, ValueError) as e: - logger.warning( - "Failed to parse Code Review response: %s — raw content: %r", - e, - content[:500], - ) - raise _CodeReviewFormatError(str(e)) from e + except (TypeError, ValueError): + raise _CodeReviewFormatError("Code Review response did not match its schema") from None expected = {packaged_file.path: packaged_file for packaged_file in intent.packaged_files} returned_paths = {file.path for file in evaluation.files} @@ -1399,37 +1365,6 @@ def _parse_code_review_evaluation(content: str, intent: Intent) -> CodeReviewEva return evaluation -def _failed_code_review_evaluation(intent: Intent, reason: str) -> CodeReviewEvaluation: - """Build a schema-complete denial when Code Review itself fails.""" - files = [ - CodeReviewFileAssessment( - path=packaged_file.path, - sha256=packaged_file.sha256, - mode=packaged_file.mode, - review_status="inconclusive", - matches_claimed_behavior="unclear", - observed_operations=["Code Review did not complete successfully."], - risk_findings=[reason], - evidence=["No validated Code Review JSON result was produced."], - ) - for packaged_file in intent.packaged_files - ] - return CodeReviewEvaluation( - decision="deny", - reviewed_all_content=False, - claim_match="unclear", - overall_risk="high", - reasoning=( - f"{reason} Defaulting to deny because voting members require a " - "schema-valid Code Review result for packaged-file execution." - ), - files=files, - risk_concerns=["Code review failure"], - conditions=[], - guidance="Retry with a valid Code Review JSON result covering every packaged file.", - ) - - def format_debate_context( member_votes: list[dict[str, Any]], current_member_id: str, @@ -1557,53 +1492,29 @@ class _EmptyReasoningError(ValueError): """Raised when the LLM returned valid JSON but omitted reasoning.""" -def _parse_evaluation( - content: str, - *, - raise_on_parse_error: bool = False, -) -> IntentEvaluation: - """Parse LLM response into a structured evaluation. - - Raises - ------ - _EmptyReasoningError - When the response parses but reasoning is missing/empty. The caller's - retry loop converts this into a re-ask with the strengthened prompt. - """ +def _parse_evaluation(content: str) -> IntentEvaluation: + """Parse a vote, rejecting responses without a valid decision or reasoning.""" try: data = _load_json_object(content) - except (json.JSONDecodeError, TypeError) as e: - logger.warning( - "Failed to parse LLM evaluation response: %s — raw content: %r", - e, - content[:500], - ) - if raise_on_parse_error: - raise - return IntentEvaluation( - decision="deny", - reasoning=f"Could not parse LLM response: {content[:200]}", - risk_concerns=["Unparseable LLM response"], - ) + except (json.JSONDecodeError, TypeError): + raise ValueError("LLM evaluation was not a JSON object") from None - decision = str(data.get("decision", "deny")).lower().strip() + value = data.get("decision") + decision = value.lower().strip() if isinstance(value, str) else "" if decision not in ("approve", "deny"): - decision = "deny" - reasoning = (data.get("reasoning") or "").strip() - # Reject sentinel placeholders the model sometimes emits instead of - # actual reasoning — treat them as equivalent to empty. - if reasoning.lower() in {"null", "none", "n/a", "na", "see above", "see below"}: - reasoning = "" - if not reasoning: - logger.warning( - "LLM returned decision=%s with empty/missing reasoning — raw: %r", - decision, - content[:500], - ) - raise _EmptyReasoningError( - f"LLM returned decision={decision} but omitted reasoning. " - f"Raw response (first 200 chars): {content[:200]!r}" - ) + raise ValueError("LLM evaluation decision must be approve or deny") + + value = data.get("reasoning") + reasoning = value.strip() if isinstance(value, str) else "" + if not reasoning or reasoning.lower() in { + "null", + "none", + "n/a", + "na", + "see above", + "see below", + }: + raise _EmptyReasoningError("LLM evaluation omitted substantive reasoning") return IntentEvaluation( decision=decision, @@ -1766,13 +1677,13 @@ def _parse_chairman_decision( reasoning=data.get("reasoning", ""), risk_level=data.get("risk_level", "medium"), ) - except (json.JSONDecodeError, KeyError, TypeError) as e: - logger.warning("Failed to parse chairman response: %s — defaulting to unanimous", e) + except (json.JSONDecodeError, KeyError, TypeError): + logger.warning("Failed to parse chairman response") if raise_on_parse_error: raise return ChairmanDecision( threshold="unanimous", - reasoning=f"Could not parse chairman response: {e}. Defaulting to unanimous.", + reasoning="Could not parse chairman response. Defaulting to unanimous.", risk_level="high", ) diff --git a/nomos/nat/functions.py b/nomos/nat/functions.py index 3202b5c5..44da147c 100644 --- a/nomos/nat/functions.py +++ b/nomos/nat/functions.py @@ -96,6 +96,7 @@ CodeReviewAgent, CouncilMemberAgent, IntentEvaluation, + ReviewFailure, _deterministic_threshold_floor, create_backend, format_code_review_analysis, @@ -141,6 +142,7 @@ # request input, so it is clamped to this bound before being used as a loop # limit to prevent an unbounded loop on hostile input (sonar S6680). _MAX_DEBATE_ROUNDS = 25 +_REVIEW_FAILED_MESSAGE = "Council review could not complete" # The decision recorded for each state a collected review can end in. A review # that expired reached no quorum, so it is recorded as "aborted", the value a @@ -150,6 +152,7 @@ WorkflowState.APPROVED: "approve", WorkflowState.DENIED: "deny", WorkflowState.EXPIRED: "aborted", + WorkflowState.FAILED: "aborted", } _EXPIRED_REVIEW_REASON = "Review expired before decision" @@ -161,8 +164,20 @@ class PendingMemberEvaluation: """A member inference result that has not mutated council state.""" agent: CouncilMemberAgent - evaluation: IntentEvaluation - duration_ms: float + evaluation: IntentEvaluation | None + + +@dataclass(frozen=True) +class MemberReviewRound: + votes: list["MemberVote"] + complete: bool = True + + +@dataclass(frozen=True) +class PendingReviewAudit: + workflow: IntentWorkflow + request_type: str + payload: dict[str, Any] | None = None _workflow_request: ContextVar[dict[str, Intent] | None] = ContextVar( @@ -1085,9 +1100,8 @@ def __init__(self, settings: CouncilSettings, limiter_pool: LimiterPool | None = self._council._snapshot_pending = self._workflow_runtime.pending self._council._snapshot_forget = self._workflow_runtime.forget self._workflow_janitor: asyncio.Task | None = None - # Reviews a request left awaiting approval when it ended, with the type - # of that request: only maintenance is left to see them expire. - self._undecided_reviews: dict[str, tuple[IntentWorkflow, str]] = {} + # Reviews left awaiting approval and aborted audits that still owe a record. + self._undecided_reviews: dict[str, PendingReviewAudit] = {} self._init_agents() self._init_code_reviewer() @@ -1585,21 +1599,21 @@ async def _evaluate_opa_filter( ) try: return await self._opa_client.evaluate(input_doc) - except OPAEvaluationError as exc: + except OPAEvaluationError: if self._settings.opa.fail_closed: return OPAPolicyDecision( allow=False, - reasons=[f"OPA evaluation failed: {exc}"], + reasons=["OPA evaluation failed"], guidance=[ "Retry after OPA is healthy, or disable OPA fail-closed only through " "deployment configuration if that is intentional.", ], metadata={"fail_closed": True}, ) - logger.warning("OPA evaluation failed; allowing due to fail_open config: %s", exc) + logger.warning("OPA evaluation failed; allowing due to fail_open config") return OPAPolicyDecision( allow=True, - reasons=[f"OPA unavailable; fail-open allowed by deployment config: {exc}"], + reasons=["OPA unavailable; fail-open allowed by deployment config"], metadata={"fail_closed": False}, ) @@ -1890,11 +1904,18 @@ def _intent_with_code_review(intent: Intent, review: IntentEvaluation) -> Intent } ) - async def _run_code_review(self, intent: Intent) -> tuple[Intent, MemberVote | None]: - """Run the advisory Code Review member before voting members.""" + async def _run_code_review( + self, intent: Intent + ) -> tuple[Intent, MemberVote | ReviewFailure | None]: + """Run the configured Code Review before voting members.""" if not intent.packaged_files or self._code_reviewer is None: return intent, None - review = await self._code_reviewer.review_intent_files(intent) + try: + review = await self._code_reviewer.review_intent_files(intent) + except Exception: + return intent, ReviewFailure("Code Review failed", {}, None) + if isinstance(review, ReviewFailure): + return intent, review return self._intent_with_code_review(intent, review), self._member_vote_from_code_review( review ) @@ -2220,8 +2241,12 @@ async def finish() -> None: # Listed for the maintenance pass: a review still open, and # one that expired here whose record could not be written. unrecorded = expired and not workflow.metadata.get("audit_committed") - if workflow.state == WorkflowState.AWAITING_APPROVAL or unrecorded: - self._undecided_reviews[key] = (workflow, request_type) + if workflow.metadata.get("audit_committed") and key in self._undecided_reviews: + self._forget_undecided_review(key) + elif workflow.state == WorkflowState.AWAITING_APPROVAL or unrecorded: + self._undecided_reviews.setdefault( + key, PendingReviewAudit(workflow, request_type) + ) self._council._record_owed.add(key) try: await self._workflow_runtime.flush(key, workflow.logical_version) @@ -2256,7 +2281,7 @@ async def _maintain_workflows(self) -> None: logger.warning("Workflow cache maintenance failed") async def _record_expired_reviews(self) -> None: - """Record each review that expired after the request that opened it ended. + """Record expired reviews and retry failed appends of aborted audits. Such a review has no request left to record it. A review is listed here only by the process that holds it, and stays listed until its record is @@ -2268,14 +2293,20 @@ async def _record_expired_reviews(self) -> None: A decision another process stored and recorded for the review stands: the review is then not recorded as expired. """ - for key, (workflow, request_type) in list(self._undecided_reviews.items()): + for key, pending in list(self._undecided_reviews.items()): + if key in self._council._active_reviews: + continue + workflow = pending.workflow self._council.expire_workflow(workflow) if workflow.state == WorkflowState.AWAITING_APPROVAL: continue - if workflow.state != WorkflowState.EXPIRED or workflow.metadata.get("audit_committed"): + expired = workflow.state == WorkflowState.EXPIRED + if workflow.metadata.get("audit_committed") or ( + not expired and pending.payload is None + ): self._forget_undecided_review(key) continue - if self._workflow_store is not None: + if expired and self._workflow_store is not None: try: stored = await self._workflow_runtime.read("get_workflow", key) except Exception: @@ -2304,19 +2335,21 @@ async def _record_expired_reviews(self) -> None: try: await self._record_consolidated_review( workflow.intent, - request_type=request_type, - final_state=WorkflowState.EXPIRED.value, - decision=_REVIEW_DECISIONS[WorkflowState.EXPIRED], + request_type=pending.request_type, + final_state=workflow.state.value, + decision="aborted", workflow=workflow, - denial_reason=_EXPIRED_REVIEW_REASON, + denial_reason=_EXPIRED_REVIEW_REASON + if expired + else workflow.error or _REVIEW_FAILED_MESSAGE, ) except _ReviewRecordedDifferentlyError: # The ledger holds a different record for this review, read and # checked: another process decided it. That record stands and no # retry can change it. - logger.exception("Expired review audit failed") + logger.exception("%s review audit failed", "Expired" if expired else "Aborted") except Exception: - logger.exception("Expired review audit failed") + logger.exception("%s review audit failed", "Expired" if expired else "Aborted") # Kept for a later pass, behind the others. The pass ends here: # with the ledger unavailable, every other attempt would fail too. self._undecided_reviews[key] = self._undecided_reviews.pop(key) @@ -2383,6 +2416,31 @@ async def _monitor_loop_lag(interval_s: float = 0.1, report_every_s: float = 10. samples = 0 window_started = time.monotonic() + async def _check_native_policy_after_review_failure( + self, intent: Intent + ) -> tuple[tuple[IntentWorkflow | None, str | None], bool]: + """Resolve admission and commit a native denial on the owning loop.""" + + def check_and_commit() -> tuple[IntentWorkflow | None, str | None]: + result = self._council.preflight_intent(intent) + preflight = result.preflight + if not result.success or preflight is None: + return None, result.error or "Council preflight failed" + try: + if preflight.policy_evaluation.decision.decision != DecisionType.DENY: + return None, None + submission = self._submit_intent(intent, preflight=preflight) + if ( + submission.workflow is not None + and submission.workflow.state == WorkflowState.DENIED + ): + return submission.workflow, None + return None, submission.error or "Council submission failed" + finally: + self._council.release_preflight(preflight) + + return check_and_commit(), False + @staticmethod async def _shield_and_drain( task: asyncio.Future[_TaskResultT], @@ -2632,10 +2690,12 @@ async def _commit_parallel_initial_review( review_threshold: str | None, enable_debate: bool, request_type: str, - ) -> tuple[Any, list[MemberVote], Any | None, float, float, bool]: + ) -> tuple[Any, MemberReviewRound, IntentWorkflow | None, bool, float, float, bool]: """Consume a preflight and atomically record the buffered initial round.""" - async def _commit() -> tuple[Any, list[MemberVote], Any | None, float, float]: + async def _commit() -> tuple[ + Any, MemberReviewRound, IntentWorkflow | None, bool, float, float + ]: submit_started = time.perf_counter() result = self._submit_intent( intent, @@ -2644,17 +2704,17 @@ async def _commit() -> tuple[Any, list[MemberVote], Any | None, float, float]: ) submit_ms = _elapsed_ms(submit_started) - votes: list[MemberVote] = [] + initial_round = MemberReviewRound([]) + review_succeeded = True workflow = result.workflow tally_ms = 0.0 if result.success: tally_started = time.perf_counter() try: - votes = self._record_agent_votes(intent, evaluations, finalize=False) - workflow = self._council.finalize_intent_review( - intent.intent_id, - allow_pending=enable_debate and not self._all_agree(votes), - ).workflow + initial_round = self._record_agent_votes(intent, evaluations) + workflow, review_succeeded = self._finalize_review_round( + intent, initial_round, workflow, allow_debate=enable_debate + ) except BaseException as exc: # BaseException, not Exception: once submit_intent has # consumed the preflight, created the workflow and opened @@ -2701,7 +2761,7 @@ async def _commit() -> tuple[Any, list[MemberVote], Any | None, float, float]: final_state=WorkflowState.FAILED.value, decision="aborted", workflow=aborted, - votes=votes, + votes=initial_round.votes, denial_reason=reason, ) except Exception: @@ -2720,7 +2780,7 @@ async def _commit() -> tuple[Any, list[MemberVote], Any | None, float, float]: raise tally_ms = _elapsed_ms(tally_started) - return result, votes, workflow, submit_ms, tally_ms + return result, initial_round, workflow, review_succeeded, submit_ms, tally_ms committed, cancelled = await self._shield_and_drain(asyncio.create_task(_commit())) return (*committed, cancelled) @@ -2729,41 +2789,82 @@ async def _collect_review_outcome( self, intent: Intent, *, + workflow: IntentWorkflow | None, enable_debate: bool, max_debate_rounds: int, actor_timings: list[dict[str, Any]] | None = None, - ) -> tuple[list[MemberVote], list[DebateRound], int, WorkflowState | None]: + ) -> tuple[list[MemberVote], list[DebateRound], int, IntentWorkflow | None, bool]: """Collect member votes and run any configured debate rounds.""" evaluations = await self._evaluate_agents(intent, actor_timings=actor_timings) - votes = self._record_agent_votes(intent, evaluations, finalize=False) - workflow = self._council.finalize_intent_review( - intent.intent_id, - allow_pending=enable_debate and not self._all_agree(votes), - ).workflow + initial_round = self._record_agent_votes(intent, evaluations) + workflow, review_succeeded = self._finalize_review_round( + intent, initial_round, workflow, allow_debate=enable_debate + ) return await self._continue_review_outcome( intent, - votes, + initial_round, workflow, + review_succeeded=review_succeeded, enable_debate=enable_debate, max_debate_rounds=max_debate_rounds, actor_timings=actor_timings, ) + def _finalize_review_round( + self, + intent: Intent, + review_round: MemberReviewRound, + workflow: IntentWorkflow | None, + *, + allow_debate: bool, + ) -> tuple[IntentWorkflow | None, bool]: + """Commit a complete round or a decision supported by a partial quorum.""" + result = self._council.finalize_intent_review( + intent.intent_id, + allow_pending=review_round.complete + and allow_debate + and not self._all_agree(review_round.votes), + partial_voters=None + if review_round.complete + else {vote.member_id for vote in review_round.votes}, + ) + if result.workflow is not None: + workflow = result.workflow + state = workflow.state + if result.success and ( + state in (WorkflowState.APPROVED, WorkflowState.DENIED) + or (review_round.complete and state == WorkflowState.AWAITING_APPROVAL) + ): + return workflow, True + + self._council.abort_intent_review(intent.intent_id, _REVIEW_FAILED_MESSAGE) + return workflow, False + + def _review_expired_before_decision(self, workflow: IntentWorkflow | None) -> bool: + if workflow is None: + return False + if workflow.state == WorkflowState.AWAITING_APPROVAL: + self._council.expire_workflow(workflow) + return workflow.state == WorkflowState.EXPIRED and workflow.approved_at is None + async def _continue_review_outcome( self, intent: Intent, - votes: list[MemberVote], - workflow: Any | None, + initial_round: MemberReviewRound, + workflow: IntentWorkflow | None, *, + review_succeeded: bool, enable_debate: bool, max_debate_rounds: int, actor_timings: list[dict[str, Any]] | None = None, - ) -> tuple[list[MemberVote], list[DebateRound], int, WorkflowState | None]: + ) -> tuple[list[MemberVote], list[DebateRound], int, IntentWorkflow | None, bool]: """Continue from an already-recorded initial round into dependent debate rounds.""" - debate_history: list[DebateRound] = [DebateRound(round_number=0, votes=list(votes))] + votes = initial_round.votes + debate_history = [DebateRound(round_number=0, votes=list(votes))] debate_rounds_completed = 0 + review_succeeded = review_succeeded and not self._review_expired_before_decision(workflow) # Clamp the (potentially request-supplied) round count to a safe ceiling # before using it as a loop bound (sonar S6680). @@ -2771,6 +2872,8 @@ async def _continue_review_outcome( if ( enable_debate + and review_succeeded + and initial_round.complete and votes and workflow is not None and workflow.state == WorkflowState.AWAITING_APPROVAL @@ -2782,35 +2885,31 @@ async def _continue_review_outcome( round_num, {v.member_id: v.decision for v in votes}, ) - votes = await self._run_debate_round( + debate_round = await self._run_debate_round( intent, votes, round_num, - finalize=False, actor_timings=actor_timings, ) - workflow = self._council.finalize_intent_review( - intent.intent_id, - allow_pending=round_num < bounded_rounds and not self._all_agree(votes), - ).workflow + votes = debate_round.votes debate_history.append(DebateRound(round_number=round_num, votes=list(votes))) + workflow, review_succeeded = self._finalize_review_round( + intent, debate_round, workflow, allow_debate=round_num < bounded_rounds + ) + if not review_succeeded or not debate_round.complete: + break debate_rounds_completed += 1 if workflow is None or workflow.state != WorkflowState.AWAITING_APPROVAL: logger.info( "Intent %s: review resolved after debate round %d (%s)", intent.intent_id, round_num, - workflow.state.value if workflow else "missing-workflow", + workflow.state.value if workflow is not None else "unknown", ) break - final_workflow = self._council.get_workflow(intent.intent_id) - return ( - votes, - debate_history, - debate_rounds_completed, - final_workflow.state if final_workflow else None, - ) + # Keep the result of this request even if terminal cache entries are evicted. + return votes, debate_history, debate_rounds_completed, workflow, review_succeeded async def _record_consolidated_review( self, @@ -2819,7 +2918,7 @@ async def _record_consolidated_review( request_type: str, final_state: str, decision: str, - workflow: Any | None = None, + workflow: IntentWorkflow | None = None, opa_decision: Any | None = None, votes: list[MemberVote] | None = None, chairman: ChairmanInfo | None = None, @@ -2831,7 +2930,7 @@ async def _record_consolidated_review( ) -> None: """Append the single Tier-1b consolidated review record (no-op in legacy mode). - Called exactly once per accepted intent that reaches a final outcome. The + Writes one entry per accepted intent that reaches a final outcome. The intermediate review entries were suppressed in the council/quorum (gated by the same ``consolidated_review_audit`` flag), so this is the lone audit row for the review. Failures propagate like the legacy DECISION_MADE append — @@ -2843,28 +2942,45 @@ async def _record_consolidated_review( in the process, and is awaited: callers still see the entry committed before they go on to mint. A caller cancelled mid-append waits for the append to finish and is then cancelled, so no review ends half-recorded. + A failed append for a managed aborted review keeps its payload for retry. """ if not self._council.config.consolidated_review_audit: return - payload = self._consolidated_review_payload( - intent, - request_type=request_type, - final_state=final_state, - decision=decision, - workflow=workflow, - opa_decision=opa_decision, - votes=votes, - chairman=chairman, - code_review=code_review, - debate_history=debate_history, - denial_reason=denial_reason, - timing=timing, - ) + key = intent.intent_id + pending = self._undecided_reviews.get(key) + payload = pending.payload if pending is not None and decision == "aborted" else None + if payload is None: + payload = self._consolidated_review_payload( + intent, + request_type=request_type, + final_state=final_state, + decision=decision, + workflow=workflow, + opa_decision=opa_decision, + votes=votes, + chairman=chairman, + code_review=code_review, + debate_history=debate_history, + denial_reason=denial_reason, + timing=timing, + ) append_started = time.perf_counter() - append: asyncio.Future[int | None] = asyncio.get_running_loop().run_in_executor( - self._ledger_executor, self._append_review_entry, payload, intent.intent_id - ) - sequence, cancelled = await self._shield_and_drain(append) + try: + append: asyncio.Future[int | None] = asyncio.get_running_loop().run_in_executor( + self._ledger_executor, self._append_review_entry, payload, key + ) + sequence, cancelled = await self._shield_and_drain(append) + except _ReviewRecordedDifferentlyError: + raise + except Exception: + if ( + decision == "aborted" + and workflow is not None + and self._council._workflows.get(key) is workflow + ): + self._undecided_reviews[key] = PendingReviewAudit(workflow, request_type, payload) + self._council._record_owed.add(key) + raise duration_ms = _log_latency( f"council_{request_type}", "ledger_append", append_started, intent_id=intent.intent_id ) @@ -3473,17 +3589,65 @@ async def _propose_intent( member_id=self._code_reviewer.member_id, provider=self._code_reviewer.provider_name, duration_ms=code_review_ms, - decision=code_review_vote.decision, + decision="" + if isinstance(code_review_vote, ReviewFailure) + else code_review_vote.decision, + status="error" if isinstance(code_review_vote, ReviewFailure) else None, timing=getattr(code_review_vote, "timing", None), execution=getattr(code_review_vote, "execution", None), ) ) + if isinstance(code_review_vote, ReviewFailure): + ( + (denied_workflow, submission_error), + cancelled, + ) = await self._check_native_policy_after_review_failure(intent) + final_state = ( + WorkflowState.DENIED if denied_workflow is not None else WorkflowState.FAILED + ) + if submission_error is None: + await self._record_consolidated_review( + intent, + request_type="propose", + final_state=final_state.value, + decision="deny" if denied_workflow is not None else "aborted", + workflow=denied_workflow, + opa_decision=opa_decision, + denial_reason="" if denied_workflow is not None else _REVIEW_FAILED_MESSAGE, + timing=self._review_timing(stages, actors, stage_intervals, timing_model), + ) + _stage(stages, tool, "total", total_start, intent_id=intent.intent_id) + self._publish_latency( + tool=tool, + intent_id=intent.intent_id, + outcome="denied" if denied_workflow is not None else "error", + stages=stages, + actors=actors, + ) + if cancelled: + raise asyncio.CancelledError + return ProposeIntentOutput( + api_version=input_data.api_version, + council_id=effective_council_id, + success=False, + intent_id=intent.intent_id, + state=final_state.value if submission_error is None else "", + error_code="review_failed" + if denied_workflow is None and submission_error is None + else None, + error=( + f"Intent denied: {denied_workflow.denial_reason}" + if denied_workflow is not None + else submission_error or _REVIEW_FAILED_MESSAGE + ), + ) parallel_enabled = bool( self._chairman and self._settings.chairman.parallel_member_evaluation ) - initial_votes: list[MemberVote] = [] - initial_workflow: Any | None = None + initial_round = MemberReviewRound([]) + initial_workflow: IntentWorkflow | None = None + initial_review_succeeded = True deferred_cancellation = False # Chairman decides threshold (if configured) @@ -3532,6 +3696,7 @@ async def _propose_intent( result, _, _, + _, submit_ms, tally_ms, deferred_cancellation, @@ -3623,8 +3788,9 @@ async def _propose_intent( try: ( result, - initial_votes, + initial_round, initial_workflow, + initial_review_succeeded, submit_ms, tally_ms, deferred_cancellation, @@ -3740,28 +3906,36 @@ async def _propose_intent( if parallel_enabled: review_continuation_started = time.perf_counter() - if ( + if not initial_review_succeeded or ( initial_workflow is not None and initial_workflow.state != WorkflowState.AWAITING_APPROVAL ): - votes = initial_votes + votes = initial_round.votes + review_succeeded = initial_review_succeeded debate_history = [DebateRound(round_number=0, votes=list(votes))] debate_rounds_completed = 0 - state = initial_workflow.state + reviewed_workflow = initial_workflow else: continuation, continuation_cancelled = await self._shield_and_drain( asyncio.create_task( self._continue_review_outcome( intent, - initial_votes, + initial_round, initial_workflow, + review_succeeded=initial_review_succeeded, enable_debate=enable_debate, max_debate_rounds=max_debate_rounds, actor_timings=actors, ) ) ) - votes, debate_history, debate_rounds_completed, state = continuation + ( + votes, + debate_history, + debate_rounds_completed, + reviewed_workflow, + review_succeeded, + ) = continuation deferred_cancellation = deferred_cancellation or continuation_cancelled stages["review_collect"] = stages.get("member_evaluation", 0.0) + _elapsed_ms( review_continuation_started @@ -3772,18 +3946,24 @@ async def _propose_intent( votes, debate_history, debate_rounds_completed, - state, + reviewed_workflow, + review_succeeded, ) = await self._collect_review_outcome( intent, + workflow=result.workflow, enable_debate=enable_debate, max_debate_rounds=max_debate_rounds, actor_timings=actors, ) _stage(stages, tool, "review_collect", stage_start, intent_id=intent.intent_id) + review_succeeded = review_succeeded and not self._review_expired_before_decision( + reviewed_workflow + ) + state = reviewed_workflow.state if reviewed_workflow is not None else WorkflowState.FAILED + if not review_succeeded and state != WorkflowState.EXPIRED: + state = WorkflowState.FAILED state_value = state.value if state else "unknown" - # A deadline that passes while the members deliberate ends the review as - # EXPIRED. That is a final outcome too, and gets the same single record. if state in _REVIEW_DECISIONS: await self._record_consolidated_review( intent, @@ -3791,20 +3971,26 @@ async def _propose_intent( request_type="propose", final_state=state_value, decision=_REVIEW_DECISIONS[state], - workflow=self._council.get_workflow(intent.intent_id), + workflow=reviewed_workflow, opa_decision=opa_decision, votes=votes, chairman=chairman_info, code_review=code_review_vote, debate_history=debate_history, - denial_reason=_EXPIRED_REVIEW_REASON if state == WorkflowState.EXPIRED else "", + denial_reason=( + _REVIEW_FAILED_MESSAGE + if state == WorkflowState.FAILED + else _EXPIRED_REVIEW_REASON + if state == WorkflowState.EXPIRED + else "" + ), timing=self._review_timing(stages, actors, stage_intervals, timing_model), ) _stage(stages, tool, "total", total_start, intent_id=intent.intent_id) self._publish_latency( tool=tool, intent_id=intent.intent_id, - outcome=state_value, + outcome="error" if not review_succeeded else state_value, stages=stages, actors=actors, stage_intervals=stage_intervals or None, @@ -3815,9 +4001,11 @@ async def _propose_intent( return ProposeIntentOutput( api_version=input_data.api_version, council_id=effective_council_id, - success=True, + success=review_succeeded, + error_code="review_failed" if not review_succeeded else None, + error=_REVIEW_FAILED_MESSAGE if not review_succeeded else "", intent_id=intent.intent_id, - state=state_value, + state=state_value if review_succeeded else WorkflowState.FAILED.value, requires_approval=state == WorkflowState.AWAITING_APPROVAL, council_members=votes, chairman=chairman_info, @@ -3835,88 +4023,67 @@ async def _evaluate_with_agents( ) -> list[MemberVote]: """Compatibility wrapper that evaluates members and immediately records votes.""" evaluations = await self._evaluate_agents(intent, actor_timings=actor_timings) - return self._record_agent_votes(intent, evaluations, finalize=finalize) + review_round = self._record_agent_votes(intent, evaluations) + if finalize: + self._finalize_review_round(intent, review_round, None, allow_debate=False) + return review_round.votes async def _evaluate_agents( self, intent: Intent, *, actor_timings: list[dict[str, Any]] | None = None, + role: str = "council_member", + evaluate: Callable[[CouncilMemberAgent], Awaitable[IntentEvaluation | ReviewFailure]] + | None = None, ) -> list[PendingMemberEvaluation]: """Evaluate members concurrently without creating workflows or casting votes.""" - if not self._agents: - return [] - async def _evaluate_one( - agent: CouncilMemberAgent, - ) -> PendingMemberEvaluation: + async def _evaluate_one(agent: CouncilMemberAgent) -> PendingMemberEvaluation: started = time.perf_counter() + outcome: IntentEvaluation | ReviewFailure | None try: - evaluation = await agent.evaluate_intent(intent) - duration_ms = _elapsed_ms(started) - if actor_timings is not None: - actor_timings.append( - self._actor_latency( - role="council_member", - member_id=agent.member_id, - provider=agent.provider_name, - duration_ms=duration_ms, - decision=evaluation.decision, - timing=getattr(evaluation, "timing", None), - execution=getattr(evaluation, "execution", None), - ) - ) - return PendingMemberEvaluation( - agent=agent, - evaluation=evaluation, - duration_ms=duration_ms, - ) + outcome = await evaluate(agent) if evaluate else await agent.evaluate_intent(intent) except asyncio.CancelledError as exc: if actor_timings is not None: actor_timings.append( self._actor_latency( - role="council_member", + role=role, member_id=agent.member_id, provider=agent.provider_name, duration_ms=_elapsed_ms(started), - decision="", status="cancelled", execution=getattr(exc, "llm_execution", None), ) ) raise - except Exception as exc: - evaluation = IntentEvaluation( - decision="deny", - reasoning=f"Evaluation error: {exc}", - ) - duration_ms = _elapsed_ms(started) - if actor_timings is not None: - actor_timings.append( - self._actor_latency( - role="council_member", - member_id=agent.member_id, - provider=agent.provider_name, - duration_ms=duration_ms, - decision="deny", - status="error", - ) + except Exception: + outcome = None + + evaluation = ( + outcome + if isinstance(outcome, IntentEvaluation) and outcome.decision in ("approve", "deny") + else None + ) + if actor_timings is not None: + actor_timings.append( + self._actor_latency( + role=role, + member_id=agent.member_id, + provider=agent.provider_name, + duration_ms=_elapsed_ms(started), + decision=evaluation.decision if evaluation else "", + status="error" if evaluation is None else None, + timing=getattr(outcome, "timing", None), + execution=getattr(outcome, "execution", None), ) - return PendingMemberEvaluation( - agent=agent, - evaluation=evaluation, - duration_ms=duration_ms, ) + return PendingMemberEvaluation(agent=agent, evaluation=evaluation) tasks = [asyncio.create_task(_evaluate_one(agent)) for agent in self._agents] try: return list(await asyncio.gather(*tasks)) - except asyncio.CancelledError: - for task in tasks: - task.cancel() - await asyncio.gather(*tasks, return_exceptions=True) - raise - except Exception: + except (asyncio.CancelledError, Exception): for task in tasks: task.cancel() await asyncio.gather(*tasks, return_exceptions=True) @@ -3926,36 +4093,21 @@ def _record_agent_votes( self, intent: Intent, evaluations: list[PendingMemberEvaluation], - *, - finalize: bool = False, - ) -> list[MemberVote]: + ) -> MemberReviewRound: """Cast buffered member evaluations in configured member order.""" votes: list[MemberVote] = [] - for pending in evaluations: agent = pending.agent eval_result = pending.evaluation - votes.append( - MemberVote( - member_id=agent.member_id, - display_name=agent.display_name, - decision=eval_result.decision, - reasoning=eval_result.reasoning, - risk_concerns=eval_result.risk_concerns, - conditions=eval_result.conditions, - execution=eval_result.execution, - timing=eval_result.timing, - guidance=eval_result.guidance, - ) - ) - + if eval_result is None: + continue # Cast the vote in the council vote_result = self._council.cast_member_vote( intent.intent_id, agent.member_id, VoteType.APPROVE if eval_result.decision == "approve" else VoteType.DENY, reason=eval_result.reasoning, - finalize=finalize, + finalize=False, ) if not vote_result.success: logger.warning( @@ -3964,8 +4116,23 @@ def _record_agent_votes( intent.intent_id, vote_result.error, ) + continue + + votes.append( + MemberVote( + member_id=agent.member_id, + display_name=agent.display_name, + decision=eval_result.decision, + reasoning=eval_result.reasoning, + risk_concerns=eval_result.risk_concerns, + conditions=eval_result.conditions, + execution=eval_result.execution, + timing=eval_result.timing, + guidance=eval_result.guidance, + ) + ) - return votes + return MemberReviewRound(votes, len(votes) == len(evaluations)) @staticmethod def _all_agree(votes: list[MemberVote]) -> bool: @@ -4001,9 +4168,8 @@ async def _run_debate_round( previous_votes: list[MemberVote], round_number: int, *, - finalize: bool = True, actor_timings: list[dict[str, Any]] | None = None, - ) -> list[MemberVote]: + ) -> MemberReviewRound: """Run a debate round where each member re-evaluates using its own backend. Each agent receives the debate context (all members' previous @@ -4013,85 +4179,34 @@ async def _run_debate_round( vote_dicts = self._votes_to_dicts(previous_votes) previous_decisions = {v.member_id: v.decision for v in previous_votes} - async def _debate_one( - agent: CouncilMemberAgent, - ) -> tuple[CouncilMemberAgent, IntentEvaluation | Exception, float]: - started = time.perf_counter() - try: - return ( - agent, - await agent.debate_evaluate( - intent, - format_debate_context(vote_dicts, agent.member_id, round_number), - ), - _elapsed_ms(started), - ) - except asyncio.CancelledError as exc: - if actor_timings is not None: - actor_timings.append( - self._actor_latency( - role=f"council_member_debate_{round_number}", - member_id=agent.member_id, - provider=agent.provider_name, - duration_ms=_elapsed_ms(started), - status="cancelled", - execution=getattr(exc, "llm_execution", None), - ) - ) - raise - except Exception as exc: - return agent, exc, _elapsed_ms(started) - - evaluations = await asyncio.gather(*[_debate_one(agent) for agent in self._agents]) + evaluations = await self._evaluate_agents( + intent, + role=f"council_member_debate_{round_number}", + evaluate=lambda agent: agent.debate_evaluate( + intent, format_debate_context(vote_dicts, agent.member_id, round_number) + ), + actor_timings=actor_timings, + ) new_votes: list[MemberVote] = [] - for agent, eval_result, duration_ms in evaluations: - if isinstance(eval_result, Exception): - eval_result = IntentEvaluation( - decision="deny", - reasoning=f"Debate evaluation error: {eval_result}", - ) + for pending in evaluations: + agent, eval_result = pending.agent, pending.evaluation + if eval_result is None: + continue changed = ( agent.member_id in previous_decisions - and previous_decisions[agent.member_id] != eval_result.decision # type: ignore[union-attr] - ) - - new_votes.append( - MemberVote( - member_id=agent.member_id, - display_name=agent.display_name, - decision=eval_result.decision, # type: ignore[union-attr] - reasoning=eval_result.reasoning, # type: ignore[union-attr] - risk_concerns=eval_result.risk_concerns, # type: ignore[union-attr] - conditions=eval_result.conditions, # type: ignore[union-attr] - execution=eval_result.execution, - timing=eval_result.timing, - guidance=eval_result.guidance, # type: ignore[union-attr] - changed_vote=changed, - ) + and previous_decisions[agent.member_id] != eval_result.decision ) - if actor_timings is not None: - actor_timings.append( - self._actor_latency( - role=f"council_member_debate_{round_number}", - member_id=agent.member_id, - provider=agent.provider_name, - duration_ms=duration_ms, - decision=eval_result.decision, - timing=getattr(eval_result, "timing", None), - execution=getattr(eval_result, "execution", None), - ) - ) # Record the revised vote in the council and ledger vote_result = self._council.revise_vote( intent.intent_id, agent.member_id, - vote_type_str=eval_result.decision, # type: ignore[union-attr] - reason=eval_result.reasoning, # type: ignore[union-attr] + vote_type_str=eval_result.decision, + reason=eval_result.reasoning, debate_round=round_number, - finalize=finalize, + finalize=False, ) if not vote_result.success: logger.warning( @@ -4100,8 +4215,24 @@ async def _debate_one( intent.intent_id, vote_result.error, ) + continue - return new_votes + new_votes.append( + MemberVote( + member_id=agent.member_id, + display_name=agent.display_name, + decision=eval_result.decision, + reasoning=eval_result.reasoning, + risk_concerns=eval_result.risk_concerns, + conditions=eval_result.conditions, + execution=eval_result.execution, + timing=eval_result.timing, + guidance=eval_result.guidance, + changed_vote=changed, + ) + ) + + return MemberReviewRound(new_votes, len(new_votes) == len(evaluations)) async def check_intent_status_async(self, input_data: IntentStatusInput) -> IntentStatusOutput: read_error = "" @@ -4496,17 +4627,64 @@ async def _authorize( member_id=self._code_reviewer.member_id, provider=self._code_reviewer.provider_name, duration_ms=code_review_ms, - decision=code_review_vote.decision, + decision="" + if isinstance(code_review_vote, ReviewFailure) + else code_review_vote.decision, + status="error" if isinstance(code_review_vote, ReviewFailure) else None, timing=getattr(code_review_vote, "timing", None), execution=getattr(code_review_vote, "execution", None), ) ) + if isinstance(code_review_vote, ReviewFailure): + ( + (denied_workflow, submission_error), + cancelled, + ) = await self._check_native_policy_after_review_failure(intent) + final_state = ( + WorkflowState.DENIED if denied_workflow is not None else WorkflowState.FAILED + ) + if submission_error is None: + await self._record_consolidated_review( + intent, + request_type="authorize", + final_state=final_state.value, + decision="deny" if denied_workflow is not None else "aborted", + workflow=denied_workflow, + opa_decision=opa_decision, + denial_reason="" if denied_workflow is not None else _REVIEW_FAILED_MESSAGE, + timing=self._review_timing(stages, actors, stage_intervals, timing_model), + ) + _stage(stages, tool, "total", total_start, intent_id=intent.intent_id) + self._publish_latency( + tool=tool, + intent_id=intent.intent_id, + outcome="denied" if denied_workflow is not None else "error", + stages=stages, + actors=actors, + ) + if cancelled: + raise asyncio.CancelledError + return AuthorizeOutput( + api_version=input_data.api_version, + council_id=effective_council_id, + status="denied" if denied_workflow is not None else "error", + error_code="review_failed" + if denied_workflow is None and submission_error is None + else None, + decision_id=intent.intent_id, + error=( + denied_workflow.denial_reason + if denied_workflow is not None + else submission_error or _REVIEW_FAILED_MESSAGE + ), + ) parallel_enabled = bool( self._chairman and self._settings.chairman.parallel_member_evaluation ) - initial_votes: list[MemberVote] = [] - initial_workflow: Any | None = None + initial_round = MemberReviewRound([]) + initial_workflow: IntentWorkflow | None = None + initial_review_succeeded = True deferred_cancellation = False # 4. Chairman pre-auth (if configured and agent is authenticated) @@ -4555,6 +4733,7 @@ async def _authorize( result, _, _, + _, submit_ms, tally_ms, deferred_cancellation, @@ -4697,8 +4876,9 @@ def chairman_authorizes(decision: Any) -> bool: try: ( result, - initial_votes, + initial_round, initial_workflow, + initial_review_succeeded, submit_ms, tally_ms, deferred_cancellation, @@ -4893,28 +5073,36 @@ def chairman_authorizes(decision: Any) -> bool: if parallel_enabled: review_continuation_started = time.perf_counter() - if ( + if not initial_review_succeeded or ( initial_workflow is not None and initial_workflow.state != WorkflowState.AWAITING_APPROVAL ): - votes = initial_votes + votes = initial_round.votes + review_succeeded = initial_review_succeeded debate_history = [DebateRound(round_number=0, votes=list(votes))] debate_rounds_completed = 0 - state = initial_workflow.state + reviewed_workflow = initial_workflow else: continuation, continuation_cancelled = await self._shield_and_drain( asyncio.create_task( self._continue_review_outcome( intent, - initial_votes, + initial_round, initial_workflow, + review_succeeded=initial_review_succeeded, enable_debate=enable_debate, max_debate_rounds=max_debate_rounds, actor_timings=actors, ) ) ) - votes, debate_history, debate_rounds_completed, state = continuation + ( + votes, + debate_history, + debate_rounds_completed, + reviewed_workflow, + review_succeeded, + ) = continuation deferred_cancellation = deferred_cancellation or continuation_cancelled stages["review_collect"] = stages.get("member_evaluation", 0.0) + _elapsed_ms( review_continuation_started @@ -4925,14 +5113,67 @@ def chairman_authorizes(decision: Any) -> bool: votes, debate_history, debate_rounds_completed, - state, + reviewed_workflow, + review_succeeded, ) = await self._collect_review_outcome( intent, + workflow=result.workflow, enable_debate=enable_debate, max_debate_rounds=max_debate_rounds, actor_timings=actors, ) _stage(stages, tool, "review_collect", stage_start, intent_id=intent.intent_id) + review_succeeded = review_succeeded and not self._review_expired_before_decision( + reviewed_workflow + ) + state = reviewed_workflow.state if reviewed_workflow is not None else WorkflowState.FAILED + if not review_succeeded and state != WorkflowState.EXPIRED: + state = WorkflowState.FAILED + if not review_succeeded or state == WorkflowState.FAILED: + await self._record_consolidated_review( + intent, + request_type="authorize", + final_state=state.value, + decision="aborted", + workflow=reviewed_workflow, + opa_decision=opa_decision, + votes=votes, + chairman=chairman_info, + code_review=code_review_vote, + debate_history=debate_history, + denial_reason=( + _EXPIRED_REVIEW_REASON + if state == WorkflowState.EXPIRED + else _REVIEW_FAILED_MESSAGE + ), + timing=self._review_timing(stages, actors, stage_intervals, timing_model), + ) + _stage(stages, tool, "total", total_start, intent_id=intent.intent_id) + self._publish_latency( + tool=tool, + intent_id=intent.intent_id, + outcome="error", + stages=stages, + actors=actors, + stage_intervals=stage_intervals or None, + timing_model=timing_model, + ) + if deferred_cancellation: + raise asyncio.CancelledError + return AuthorizeOutput( + api_version=input_data.api_version, + council_id=effective_council_id, + status="error", + error_code="review_failed", + error=_REVIEW_FAILED_MESSAGE, + decision_id=intent.intent_id, + council_members=votes, + chairman=chairman_info, + code_review=code_review_vote, + debate_rounds=debate_rounds_completed, + debate_history=debate_history, + ) + approved = state == WorkflowState.APPROVED if not approved: @@ -4976,7 +5217,7 @@ async def store_denial() -> None: request_type="authorize", final_state=state.value, decision=_REVIEW_DECISIONS[state], - workflow=self._council.get_workflow(intent.intent_id), + workflow=reviewed_workflow, opa_decision=opa_decision, votes=votes, chairman=chairman_info, @@ -5024,7 +5265,7 @@ async def store_denial() -> None: request_type="authorize", final_state=WorkflowState.APPROVED.value, decision="approve", - workflow=self._council.get_workflow(intent.intent_id), + workflow=reviewed_workflow, opa_decision=opa_decision, votes=votes, chairman=chairman_info, diff --git a/tests/level_4/test_council.py b/tests/level_4/test_council.py index 7f4f13e3..725d73ec 100644 --- a/tests/level_4/test_council.py +++ b/tests/level_4/test_council.py @@ -10,6 +10,7 @@ import pytest from nomos.level_0.types import AgentRole, CouncilMember, Intent +from nomos.level_2.quorum.vote import VoteType from nomos.level_3.executor import LogHandler, NoOpHandler from nomos.level_4.council import CouncilConfig, SecurityCouncil from nomos.level_4.council.workflow import WorkflowState @@ -114,6 +115,29 @@ def test_denial_workflow(self, council, members): workflow = deny_result2.workflow assert workflow.state == WorkflowState.DENIED + def test_finalize_full_review_with_legacy_quorum_adapter(self, council, members, monkeypatch): + intent = Intent.create( + agent_id="agent-1", + action_type="secrets.read", + description="Read deployment API keys", + target_resource="/secrets/api-keys", + justification="Deployment", + ) + assert council.submit_intent(intent).requires_approval + for member in members: + assert council.cast_member_vote( + intent.intent_id, member.member_id, VoteType.APPROVE, finalize=False + ).success + manager = council._quorum_manager + finalize = manager.finalize_vote + + def finalize_full_round(intent_id, *, allow_pending): + return finalize(intent_id, allow_pending=allow_pending) + + monkeypatch.setattr(manager, "finalize_vote", finalize_full_round) + result = council.finalize_intent_review(intent.intent_id) + assert result.success and result.workflow.state == WorkflowState.APPROVED + def test_execute_approved_intent(self, council): intent = Intent.create( agent_id="agent-1", diff --git a/tests/test_approved_fallback_contract.py b/tests/test_approved_fallback_contract.py index 82223797..1717d676 100644 --- a/tests/test_approved_fallback_contract.py +++ b/tests/test_approved_fallback_contract.py @@ -18,6 +18,7 @@ ChairmanAgent, CodeReviewAgent, CouncilMemberAgent, + ReviewFailure, _complete_with_retry, format_code_review_analysis, format_code_review_result_json, @@ -214,7 +215,10 @@ async def test_denial_and_invalid_output_never_select_another_model(text): primary = ScriptBackend("primary", [text]) backup = ScriptBackend("backup", [APPROVE]) result = await member(primary, candidates(primary, backup)).evaluate_intent(intent()) - assert result.decision == "deny", f"F06 {text=!r} must fail closed" + if text == DENY: + assert result.decision == "deny" + else: + assert isinstance(result, ReviewFailure), f"F06 {text=!r} must fail closed" assert len(primary.calls) == 1, f"F06 {text=!r} must not retry same model" assert backup.calls == [], f"F06 {text=!r} must not change model" selected = "primary" if text == DENY else None @@ -229,7 +233,7 @@ async def test_incomplete_code_review_is_terminal_even_if_backup_would_approve() primary = ScriptBackend("primary", [json.dumps(malformed)]) backup = ScriptBackend("backup", [review_json(request)]) result = await invoke("code_review", primary, candidates(primary, backup), request) - assert result.decision == "deny", "F06 files=[] must fail review" + assert isinstance(result, ReviewFailure), "F06 files=[] must fail review" assert backup.calls == [], "F06 files=[] may not select another model" @@ -250,7 +254,7 @@ async def test_exhaustion_never_revisits_candidates_and_retains_strict_policy(ro if role in ("chairman", "pre_auth"): assert (result.threshold, result.risk_level) == ("unanimous", "high"), f"F07 {role=}" else: - assert result.decision == "deny", f"F07 {role=} exhaustion must deny" + assert isinstance(result, ReviewFailure), f"F07 {role=} exhaustion must fail review" @pytest.mark.asyncio @@ -282,7 +286,7 @@ async def slow(_messages): result = await member(route[0].backend, route, retry_budget_seconds=0.05).evaluate_intent( intent() ) - assert result.decision == "deny", "F08 50ms total deadline must deny" + assert isinstance(result, ReviewFailure), "F08 50ms total deadline must stop review" assert [len(c.backend.calls) for c in route] == [1, 0, 0], "F08 no fresh backup budget" assert time.monotonic() - started < 0.4, "F08 50ms deadline plus cleanup tolerance" assert all(c.backend.active == 0 for c in route), "F08 no detached inference" @@ -302,7 +306,10 @@ async def test_retry_after_is_finite_capped_and_consumes_single_deadline(hint, e ).evaluate_intent(intent()) elapsed = time.monotonic() - started assert bool(backup.calls) == expected_backup, f"F08 retry_after={hint!r}, budget=.08" - assert result.decision == ("approve" if expected_backup else "deny"), f"F08 {hint=}" + if expected_backup: + assert result.decision == "approve", f"F08 {hint=}" + else: + assert isinstance(result, ReviewFailure), f"F08 {hint=}" assert elapsed < 0.4, f"F08 {hint=} cannot extend deadline" if hint == 0.03: assert elapsed >= 0.02, "F08 finite Retry-After=.03 must actually be honored" @@ -556,7 +563,7 @@ async def blocked(_messages): if state == "failed": result = await agent.evaluate_intent(intent()) execution = result.execution - assert result.decision == "deny", "F12 primary timeout + unknown backup error denies" + assert isinstance(result, ReviewFailure), "F12 terminal backup error stops review" else: task = asyncio.create_task(agent.evaluate_intent(intent())) try: diff --git a/tests/test_approved_fallback_contract_sdk_service.py b/tests/test_approved_fallback_contract_sdk_service.py index 04657eb5..94a3eb36 100644 --- a/tests/test_approved_fallback_contract_sdk_service.py +++ b/tests/test_approved_fallback_contract_sdk_service.py @@ -15,7 +15,7 @@ from nomos.config.settings import CouncilSettings, LLMBackendConfig, load_config from nomos.llm import limiter as limiter_module from nomos.llm.base import LLMRateLimitError, LLMTimeoutError -from nomos.llm.council_agent import create_backend +from nomos.llm.council_agent import ReviewFailure, create_backend from nomos.llm.limiter import LimitedBackend, LimiterPool from nomos.nat.functions import AuthorizeInput, CouncilService, ProposeIntentInput from tests.test_approved_fallback_contract import ( @@ -161,7 +161,7 @@ async def handler(request): result = await member(primary, candidates(primary, backup, timeout=3)).evaluate_intent( intent() ) - assert result.decision == "deny", f"F06 {provider=} {status=} must deny" + assert isinstance(result, ReviewFailure), f"F06 {provider=} {status=} must fail review" assert [r.url.host for r in wire] == ["primary.invalid"], ( f"F06 {provider=} {status=} zero fallback" ) @@ -213,7 +213,9 @@ async def handler(request): try: primary, backup = sdk_backend(provider, "primary"), sdk_backend(provider, "backup") result = await member(primary, candidates(primary, backup)).evaluate_intent(intent()) - assert result.decision == "deny", f"F14 {provider=} {body=} invalid output fail-closed" + assert isinstance(result, ReviewFailure), ( + f"F14 {provider=} {body=} invalid output fail-closed" + ) assert len(wire) == 1, f"F14 {provider=} {body=} no model change or SDK retry" finally: await close_clients(clients) @@ -300,7 +302,9 @@ class APITimeoutError(Exception): ) backup = ScriptBackend("backup") result = await member(primary, candidates(primary, backup)).evaluate_intent(intent()) - assert result.decision == "deny" and backup.calls == [], "F06 fake APITimeoutError is terminal" + assert isinstance(result, ReviewFailure) and backup.calls == [], ( + "F06 fake APITimeoutError is terminal" + ) def service_data(tmp_path, routes=True): @@ -501,7 +505,15 @@ async def handler(http_request): else: result = await service.authorize(AuthorizeInput(**values)) outcome = result.status - expected = "approved" if mode == "approve" else "denied" + if mode == "malformed": + assert result.model_dump()["error_code"] == "review_failed" + else: + assert "error_code" not in result.model_dump() + if mode == "malformed": + expected = "failed" if tool == "propose" else "error" + assert result.council_members == [] + else: + expected = "approved" if mode == "approve" else "denied" assert outcome == expected, f"F16 {tool=} {mode=} expected {expected}, result={result}" for role in ("member", "chair", "review"): assert wire.count(f"{role}-primary") == wire.count(f"{role}-backup") == 1, ( @@ -594,7 +606,7 @@ class UnknownStatusError(Exception): primary = LimitedBackend(raw, limiter_module.EndpointLimiter(1)) backup = ScriptBackend("backup") result = await member(primary, candidates(primary, backup)).evaluate_intent(intent()) - assert result.decision == "deny", f"F06 {lookalike=} must fail closed" + assert isinstance(result, ReviewFailure), f"F06 {lookalike=} must fail closed" assert len(raw.calls) == 1 and backup.calls == [], ( f"F06 {lookalike=} zero fallback after wrapper" ) diff --git a/tests/test_council_agent_parsing.py b/tests/test_council_agent_parsing.py index ea0030a2..ea66de25 100644 --- a/tests/test_council_agent_parsing.py +++ b/tests/test_council_agent_parsing.py @@ -13,6 +13,7 @@ ChairmanAgent, CodeReviewAgent, CouncilMemberAgent, + ReviewFailure, _parse_chairman_decision, _parse_evaluation, ) @@ -66,16 +67,14 @@ def test_timeout_is_named_as_a_timeout(self): from nomos.llm.base import LLMTimeoutError from nomos.llm.council_agent import _describe_failure - assert _describe_failure(LLMTimeoutError("Request timed out.")) == ( - "provider timeout: Request timed out." - ) + assert _describe_failure(LLMTimeoutError("Request timed out.")) == ("provider timeout") def test_rate_limit_is_distinguished_from_a_timeout(self): from nomos.llm.base import LLMRateLimitError from nomos.llm.council_agent import _describe_failure described = _describe_failure(LLMRateLimitError("Too Many Requests")) - assert described == "provider rate limit: Too Many Requests" + assert described == "provider rate limit" assert "timeout" not in described def test_http_status_is_surfaced_when_the_provider_supplies_one(self): @@ -86,7 +85,7 @@ class _ProviderError(Exception): described = _describe_failure(_ProviderError("DEGRADED function cannot be invoked")) assert "HTTP 400" in described - assert "DEGRADED function cannot be invoked" in described + assert "DEGRADED function cannot be invoked" not in described def test_status_is_read_from_a_nested_response_object(self): """openai-style SDK errors carry the status on `.response`, not the exception.""" @@ -103,7 +102,7 @@ class _SdkError(Exception): def test_an_error_with_no_message_still_names_its_type(self): from nomos.llm.council_agent import _describe_failure - assert _describe_failure(ValueError()) == "ValueError: ValueError" + assert _describe_failure(ValueError()) == "ValueError" class TestCallerFailurePaths: @@ -178,39 +177,34 @@ def _assert_diagnostic(self, text: str) -> None: assert "nim-inkling" in text, f"provider/backend missing from: {text!r}" @pytest.mark.asyncio - async def test_evaluate_intent_denies_and_names_the_backend(self): + async def test_evaluate_intent_fails_and_names_the_backend(self): agent = CouncilMemberAgent( CouncilMemberConfig(id="environment-isolation", backend="nim-inkling"), self._DeadBackend(self._rate_limited()), max_retries=0, ) result = await agent.evaluate_intent(self._intent()) - assert result.decision == "deny", "a member that cannot evaluate must fail closed" + assert isinstance(result, ReviewFailure) self._assert_diagnostic(result.reasoning) @pytest.mark.asyncio - async def test_debate_evaluate_denies_and_names_the_backend(self): + async def test_debate_evaluate_fails_and_names_the_backend(self): agent = CouncilMemberAgent( CouncilMemberConfig(id="environment-isolation", backend="nim-inkling"), self._DeadBackend(self._rate_limited()), max_retries=0, ) result = await agent.debate_evaluate(self._intent(), []) - assert result.decision == "deny" + assert isinstance(result, ReviewFailure) self._assert_diagnostic(result.reasoning) @pytest.mark.asyncio - async def test_review_intent_files_denies_and_names_the_backend(self): + async def test_review_intent_files_fails_and_names_the_backend(self): intent = self._packaged_intent() agent = CodeReviewAgent(self._DeadBackend(self._rate_limited()), max_retries=0) result = await agent.review_intent_files(intent) - assert result.decision == "deny" + assert isinstance(result, ReviewFailure) self._assert_diagnostic(result.reasoning) - # Schema-complete: voting members require one assessment per packaged - # file, so a failure must still describe every file rather than none. - assert len(result.files) == len(intent.packaged_files) - assert {f.path for f in result.files} == {f.path for f in intent.packaged_files} - assert all(f.review_status == "inconclusive" for f in result.files) @pytest.mark.asyncio async def test_decide_threshold_falls_back_to_unanimous_and_names_the_backend(self): diff --git a/tests/test_decision_deadlines.py b/tests/test_decision_deadlines.py index 9e87c8c1..e0016d26 100644 --- a/tests/test_decision_deadlines.py +++ b/tests/test_decision_deadlines.py @@ -510,8 +510,9 @@ async def test_propose_records_a_review_that_expires_during_debate(parallel): result = await service.propose_intent(_proposal("expires in debate"), enable_debate=True) - assert result.state == "expired" and not result.requires_approval - assert result.debate_rounds == 1 + assert (result.success, result.state, result.error_code) == (False, "failed", "review_failed") + assert not result.requires_approval + assert result.debate_rounds == 0 workflow = service.council._workflows[result.intent_id] assert workflow.state == WorkflowState.EXPIRED assert service.council.mint_token(result.intent_id) is None @@ -538,8 +539,9 @@ async def test_authorize_records_a_review_that_expires_during_debate(tmp_path, p result = await service.authorize(_debated_authorization(), enable_debate=True) - assert result.status == "denied" and not result.writ - assert result.debate_rounds == 1 + assert (result.status, result.error_code) == ("error", "review_failed") + assert not result.writ + assert result.debate_rounds == 0 workflow = service.council._workflows[result.decision_id] assert workflow.state == WorkflowState.EXPIRED assert "writ_id" not in workflow.metadata diff --git a/tests/test_llm.py b/tests/test_llm.py index 0c4197bf..5eb79dc2 100644 --- a/tests/test_llm.py +++ b/tests/test_llm.py @@ -19,6 +19,7 @@ ChairmanAgent, CodeReviewAgent, CouncilMemberAgent, + ReviewFailure, _format_intent_for_review, _parse_code_review_evaluation, _parse_evaluation, @@ -119,19 +120,16 @@ def test_parse_valid_deny(self): assert result.decision == "deny" assert result.risk_concerns == ["Privilege escalation"] - def test_parse_invalid_decision_defaults_deny(self): - content = json.dumps({"decision": "maybe", "reasoning": "Unsure"}) - result = _parse_evaluation(content) - assert result.decision == "deny" - - def test_parse_invalid_json_defaults_deny(self): - result = _parse_evaluation("not json at all") - assert result.decision == "deny" - assert "Unparseable" in result.risk_concerns[0] + @pytest.mark.parametrize("decision", ["maybe", 1, None]) + def test_parse_invalid_decision_is_not_a_vote(self, decision): + content = json.dumps({"decision": decision, "reasoning": "Unsure"}) + with pytest.raises(ValueError, match="decision must be approve or deny"): + _parse_evaluation(content) - def test_parse_empty_content(self): - result = _parse_evaluation("") - assert result.decision == "deny" + @pytest.mark.parametrize("content", ["not json at all", ""]) + def test_parse_invalid_json_is_not_a_vote(self, content): + with pytest.raises(ValueError, match="was not a JSON object"): + _parse_evaluation(content) def test_parse_markdown_fenced_json(self): content = '```json\n{"decision": "approve", "reasoning": "Looks safe"}\n```' @@ -187,7 +185,7 @@ def test_parse_code_review_requires_clear_json_schema(self, observed_operations) ) if not observed_operations: - with pytest.raises(ValueError, match="observed_operations"): + with pytest.raises(ValueError, match="did not match its schema"): _parse_code_review_evaluation(content, intent) return @@ -454,7 +452,7 @@ async def test_system_prompt_sent(self, approve_agent, test_intent): assert "Allow safe operations" in system_msg.content @pytest.mark.asyncio - async def test_error_handling_defaults_deny(self, test_intent): + async def test_error_handling_returns_review_failure(self, test_intent): class ErrorBackend(LLMBackend): async def complete(self, messages, **kwargs): raise RuntimeError("API error") @@ -469,8 +467,8 @@ def provider_name(self): ) agent = CouncilMemberAgent(member_config=config, backend=ErrorBackend()) result = await agent.evaluate_intent(test_intent) - assert result.decision == "deny" - assert "failed" in result.reasoning.lower() or "error" in result.reasoning.lower() + assert isinstance(result, ReviewFailure) + assert "RuntimeError" in result.reasoning @pytest.mark.asyncio async def test_malformed_json_response_is_retried(self, test_intent, monkeypatch): diff --git a/tests/test_llm_fallback.py b/tests/test_llm_fallback.py index 154e4600..036ffdf7 100644 --- a/tests/test_llm_fallback.py +++ b/tests/test_llm_fallback.py @@ -26,6 +26,7 @@ from nomos.llm.council_agent import ( ChairmanAgent, CouncilMemberAgent, + ReviewFailure, _complete_with_retry, _parse_evaluation, _RetryExhaustedError, @@ -73,7 +74,7 @@ def run_route(primary, backup, *, candidate_timeout=0.05, **kwargs): [], temperature=0.3, max_tokens=237, - parse=lambda text: _parse_evaluation(text, raise_on_parse_error=True), + parse=_parse_evaluation, log_ctx="engineer", call_candidates=candidates(primary, backup, candidate_timeout), **kwargs, @@ -424,7 +425,7 @@ async def test_code_review_fallback_ignores_forged_execution_and_keeps_coverage( content["files"] = [] backup.value = json.dumps(content) failed = await agent.review_intent_files(intent) - assert failed.decision == "deny" + assert isinstance(failed, ReviewFailure) assert failed.execution.selected_backend is None assert failed.execution.attempts[-1].outcome == "invalid_response" diff --git a/tests/test_llm_limits.py b/tests/test_llm_limits.py index 21fe2d1a..53f1a15a 100644 --- a/tests/test_llm_limits.py +++ b/tests/test_llm_limits.py @@ -20,7 +20,7 @@ LLMRole, LLMTimeoutError, ) -from nomos.llm.council_agent import CouncilMemberAgent, create_backend +from nomos.llm.council_agent import CouncilMemberAgent, ReviewFailure, create_backend from nomos.llm.limiter import EndpointLimiter, LimitedBackend, LimiterPool APPROVE_JSON = json.dumps({"decision": "approve", "reasoning": "Safe operation."}) @@ -289,7 +289,7 @@ async def fail_sleep(delay): # pragma: no cover - must not be reached result = await agent.evaluate_intent(test_intent) - assert result.decision == "deny" + assert isinstance(result, ReviewFailure) assert backend.calls == 1 assert "failed after 1 attempts" in result.reasoning @@ -353,7 +353,7 @@ async def complete(self, **kwargs): result = await agent.evaluate_intent(test_intent) elapsed = _time.monotonic() - began - assert result.decision == "deny", "an evaluation that ran out of budget fails closed" + assert isinstance(result, ReviewFailure) assert elapsed < 2.0, ( f"the helper ran {elapsed:.2f}s against a 0.3s budget, so the budget is " "not being enforced as a deadline" @@ -367,5 +367,5 @@ async def test_timeout_retries_are_bounded_by_max_retries(self, test_intent): result = await agent.evaluate_intent(test_intent) - assert result.decision == "deny" + assert isinstance(result, ReviewFailure) assert backend.calls <= 3, f"unbounded timeout retries: {backend.calls} calls" diff --git a/tests/test_monitor_token_usage.py b/tests/test_monitor_token_usage.py index 40530455..a948f900 100644 --- a/tests/test_monitor_token_usage.py +++ b/tests/test_monitor_token_usage.py @@ -17,6 +17,7 @@ from nomos.llm.base import LLMResponse, LLMTimeoutError from nomos.llm.council_agent import ( CouncilMemberAgent, + ReviewFailure, _call_timing, _complete_with_retry, _RetryExhaustedError, @@ -103,7 +104,7 @@ async def test_exhausted_retries_carry_the_tokens_they_spent(self, monkeypatch): @pytest.mark.asyncio async def test_failed_member_evaluation_reports_its_spend(self, monkeypatch): - # Every attempt is billed and unparseable: the member denies, and the actor + # Every attempt is billed and unparseable: the review fails, and the actor # entry the council records still says what the failed evaluation cost. monkeypatch.setattr("nomos.llm.council_agent.RETRY_DELAY_SECONDS", 0.0) agent = CouncilMemberAgent( @@ -113,13 +114,13 @@ async def test_failed_member_evaluation_reports_its_spend(self, monkeypatch): ) evaluation = await agent.evaluate_intent(_intent()) - assert evaluation.decision == "deny" + assert isinstance(evaluation, ReviewFailure) entry = CouncilService._actor_latency( role="council_member", member_id="blast", provider="nim", duration_ms=12.0, - decision=evaluation.decision, + status="error", timing=evaluation.timing, ) assert (entry["input_tokens"], entry["output_tokens"]) == (1850.0, 85.0) @@ -144,14 +145,14 @@ def provider_name(self): ) evaluation = await agent.evaluate_intent(_intent()) - assert evaluation.decision == "deny" + assert isinstance(evaluation, ReviewFailure) assert evaluation.timing == {} entry = CouncilService._actor_latency( role="council_member", member_id="blast", provider="nim", duration_ms=12.0, - decision=evaluation.decision, + status="error", timing=evaluation.timing, ) assert "input_tokens" not in entry and "output_tokens" not in entry diff --git a/tests/test_nat_functions.py b/tests/test_nat_functions.py index 55cd5b93..82e60e6a 100644 --- a/tests/test_nat_functions.py +++ b/tests/test_nat_functions.py @@ -30,6 +30,7 @@ CodeReviewAgent, CouncilMemberAgent, IntentEvaluation, + ReviewFailure, _format_intent_for_review, format_debate_context, ) @@ -1624,7 +1625,7 @@ async def test_member_exhausts_retries(self): justification="Testing", ) result = await agent.evaluate_intent(intent) - assert result.decision == "deny" + assert isinstance(result, ReviewFailure) assert "failed after 3 attempts" in result.reasoning.lower() assert backend.call_count == 3 # initial + 2 retries @@ -2541,7 +2542,7 @@ async def test_code_review_never_overlaps_the_parallel_phase(self): { "decision": "approve", "reviewed_all_content": True, - "claim_match": "match", + "claim_match": "yes", "overall_risk": "low", "reasoning": "fine", "files": [ @@ -2553,7 +2554,7 @@ async def test_code_review_never_overlaps_the_parallel_phase(self): # which is not what this test means to exercise. "sha256": hashlib.sha256(b"echo hello\n").hexdigest(), "mode": "0600", - "review_status": "reviewed", + "review_status": "complete", "matches_claimed_behavior": "yes", "observed_operations": ["echo"], "risk_findings": [], diff --git a/tests/test_one_to_one_ledger.py b/tests/test_one_to_one_ledger.py index 341e0088..1fbf0fac 100644 --- a/tests/test_one_to_one_ledger.py +++ b/tests/test_one_to_one_ledger.py @@ -354,8 +354,9 @@ async def test_authorize_orchestration_carries_debate_into_record(tmp_path, monk ), ] - async def fake_collect(intent, **kwargs): - return debate[-1].votes, debate, 1, WorkflowState.DENIED + async def fake_collect(intent, *, workflow, **kwargs): + workflow.state = WorkflowState.DENIED + return debate[-1].votes, debate, 1, workflow, True monkeypatch.setattr(service, "_collect_review_outcome", fake_collect) await service.authorize(request) diff --git a/tests/test_opa_nat_integration.py b/tests/test_opa_nat_integration.py index 5e719d7d..e03a6670 100644 --- a/tests/test_opa_nat_integration.py +++ b/tests/test_opa_nat_integration.py @@ -245,6 +245,8 @@ async def test_opa_fail_closed_denies_when_opa_is_unavailable(tmp_path): assert result.status == "denied" assert "OPA evaluation failed" in result.error + assert "connection refused" not in result.error + assert "error_code" not in result.model_dump() assert result.writ is None @@ -286,7 +288,7 @@ def log_message(self, format, *args): @pytest.mark.asyncio -async def test_opa_fail_open_allows_existing_flow_to_continue(tmp_path): +async def test_opa_fail_open_allows_existing_flow_to_continue(tmp_path, caplog): service = _make_service(tmp_path, fail_closed=False) service._opa_client = RecordingOPAClient( error=OPAEvaluationError("connection refused"), @@ -306,3 +308,4 @@ async def test_opa_fail_open_allows_existing_flow_to_continue(tmp_path): assert result.success is True assert result.intent_id.startswith("intent-") assert service.council.get_workflow(result.intent_id) is not None + assert "connection refused" not in caplog.text diff --git a/tests/test_parallel_council_review.py b/tests/test_parallel_council_review.py index 2ad01dc8..dcd616a3 100644 --- a/tests/test_parallel_council_review.py +++ b/tests/test_parallel_council_review.py @@ -14,12 +14,16 @@ from nomos.auth.authenticator import AgentIdentity from nomos.auth.permissions import PermissionScope from nomos.auth.writ_factory import WritFactory -from nomos.config.settings import ChairmanConfig, CouncilSettings, OPAConfig -from nomos.level_0.types import CouncilMember, Intent +from nomos.config.settings import ChairmanConfig, CouncilMemberConfig, CouncilSettings, OPAConfig +from nomos.level_0.clock import MockClock +from nomos.level_0.types import CouncilMember, Intent, PackagedFile from nomos.level_1.policy import DecisionType, PolicyRule +from nomos.llm.base import LLMBackend, LLMResponse, LLMTimeoutError from nomos.llm.council_agent import ( ChairmanDecision, ChairmanPreAuthDecision, + CodeReviewAgent, + CouncilMemberAgent, IntentEvaluation, ) from nomos.nat.functions import AuthorizeInput, CouncilService, ProposeIntentInput @@ -118,6 +122,678 @@ def _approval(decision: str = "approve") -> IntentEvaluation: return IntentEvaluation(decision=decision, reasoning=f"member says {decision}") +@pytest.mark.asyncio +@pytest.mark.parametrize("parallel", [False, True]) +@pytest.mark.parametrize("failure", ["timeout", "malformed", "rejected_ballot"]) +@pytest.mark.parametrize("consolidated", [False, True]) +@pytest.mark.parametrize("tool", ["authorize", "propose"]) +@pytest.mark.parametrize( + "threshold,policy_floor,peer_decisions,expected", + [ + ("quorum", 0, ("approve", "approve"), "approved"), + ("quorum", 0, ("deny", "deny"), "denied"), + ("quorum", 0, ("approve", "deny"), "failed"), + ("unanimous", 0, ("approve", "approve"), "failed"), + ("quorum", 3, ("approve", "approve"), "failed"), + ], +) +async def test_incomplete_member_review_counts_only_available_votes( + parallel, + failure, + consolidated, + tool, + threshold, + policy_floor, + peer_decisions, + expected, + tmp_path, + caplog, + monkeypatch, +): + service = _service(parallel=parallel, council_key_path=str(tmp_path)) + service.council.config.consolidated_review_audit = consolidated + service.council._quorum_manager._record_audit_entries = not consolidated + if policy_floor: + service.council._policy_engine.add_rule( + PolicyRule( + rule_id="policy-floor", + name="Require a minimum approval weight", + priority=0, + action_types={"system.exec"}, + decision=DecisionType.REQUIRE_QUORUM, + required_quorum_weight=policy_floor, + ) + ) + latency = [] + monkeypatch.setattr(service, "_publish_latency", lambda **kwargs: latency.append(kwargs)) + marker = "private fixture response" + + class FailingBackend(LLMBackend): + def provider_name(self): + return "fixture" + + async def complete(self, messages, **kwargs): + if failure == "timeout": + raise LLMTimeoutError(marker) + return LLMResponse(content='{"reasoning": "private fixture response"}', model="fixture") + + async def chairman(_intent: Intent) -> ChairmanDecision: + return ChairmanDecision(threshold=threshold) + + reviewer = CouncilMemberAgent( + CouncilMemberConfig(id="m2", backend="fixture"), + FailingBackend(), + max_retries=0, + ) + _add_member( + service, "m1", lambda _intent: asyncio.sleep(0, result=_approval(peer_decisions[0])) + ) + if failure == "rejected_ballot": + cast = service.council.cast_member_vote + + def reject_member_ballot(intent_id, voter_id, *args, **kwargs): + if voter_id == "m2": + service.council._quorum_manager.unregister_member(voter_id) + return cast(intent_id, voter_id, *args, **kwargs) + + monkeypatch.setattr(service.council, "cast_member_vote", reject_member_ballot) + _add_member(service, "m2", lambda _intent: asyncio.sleep(0, result=_approval())) + else: + _add_member(service, "m2", reviewer.evaluate_intent) + _add_member( + service, "m3", lambda _intent: asyncio.sleep(0, result=_approval(peer_decisions[1])) + ) + service._chairman = FakeChairman(chairman) # type: ignore[assignment] + + proposal = _proposal("incomplete") + failed = expected == "failed" + if tool == "authorize": + result = await service.authorize( + AuthorizeInput(**proposal.model_dump(exclude_defaults=True)) + ) + assert result.status == ("error" if failed else expected) + assert bool(result.writ) == (expected == "approved") + intent_id = result.decision_id + else: + result = await service.propose_intent(proposal) + assert (result.success, result.state) == (not failed, expected) + intent_id = result.intent_id + assert result.model_dump().get("error_code") == ("review_failed" if failed else None) + assert {vote.member_id for vote in result.council_members} == {"m1", "m3"} + workflow = service.council.get_workflow(intent_id) + assert workflow.state.value == expected + assert workflow.vote_record.required_weight == ( + 3 if policy_floor or threshold == "unanimous" else 2 + ) + if failed: + assert service.council.get_active_workflows() == [] + assert service.council._submission_preflights == {} + assert service.council._quorum_manager.get_pending_votes() == [] + assert latency[-1]["outcome"] == ("error" if failed else expected) + actor = next(actor for actor in latency[-1]["actors"] if actor["member_id"] == "m2") + if failure == "rejected_ballot": + assert actor["decision"] == "approve" + else: + assert (actor["status"], actor["decision"]) == ("error", "") + assert marker not in result.model_dump_json() + assert marker not in caplog.text + + entries = [ + entry + for i in range(service.council.ledger.length()) + if (entry := service.council.ledger.get(i)) is not None + ] + outcome = {"approved": "approve", "denied": "deny", "failed": "aborted"}[expected] + if consolidated: + [review] = [ + entry.payload for entry in entries if entry.entry_type.value == "intent_review_recorded" + ] + assert (review["final"]["state"], review["final"]["decision"]) == (expected, outcome) + assert {v["member_id"] for v in review["quorum"]["member_votes"]} == {"m1", "m3"} + assert marker not in str(review) + else: + [decision] = [ + entry.payload for entry in entries if entry.entry_type.value == "decision_made" + ] + assert decision["outcome"] == outcome + assert decision["deny_weight"] == peer_decisions.count("deny") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("parallel", [False, True]) +@pytest.mark.parametrize("failure", ["inference", "rejected_ballot"]) +@pytest.mark.parametrize( + "threshold,second_vote,expected", + [ + ("unanimous", "approve", "error"), + ("quorum", "approve", "approved"), + ("quorum", "deny", "error"), + ], +) +async def test_partial_debate_counts_current_round_votes_only( + parallel, failure, threshold, second_vote, expected, tmp_path +): + service = _service(parallel=parallel, council_key_path=str(tmp_path)) + calls = {member_id: 0 for member_id in ("m1", "m2", "m3")} + + async def member(_intent: Intent, member_id: str) -> IntentEvaluation: + calls[member_id] += 1 + if calls[member_id] == 1: + return _approval("deny" if member_id == "m2" else "approve") + if member_id == "m3": + if failure == "inference": + raise RuntimeError("failed re-evaluation") + service.council._quorum_manager.unregister_member(member_id) + return _approval(second_vote if member_id == "m2" else "approve") + + async def chairman(_intent: Intent) -> ChairmanDecision: + return ChairmanDecision(threshold=threshold) + + for member_id in calls: + _add_member( + service, member_id, lambda intent, member_id=member_id: member(intent, member_id) + ) + service._chairman = FakeChairman(chairman) # type: ignore[assignment] + result = await service.authorize( + AuthorizeInput(**_proposal("incomplete debate").model_dump(exclude_defaults=True)), + enable_debate=True, + ) + + assert result.status == expected + assert result.error_code == ("review_failed" if expected == "error" else None) + assert bool(result.writ) == (expected == "approved") + [audit] = [ + entry.payload + for i in range(service.council.ledger.length()) + if (entry := service.council.ledger.get(i)) is not None + and entry.entry_type.value == "intent_review_recorded" + ] + first, partial = audit["debate_rounds"] + assert (first["round_number"], partial["round_number"], result.debate_rounds) == (0, 1, 0) + assert {vote["member_id"]: vote["decision"] for vote in first["votes"]} == { + "m1": "approve", + "m2": "deny", + "m3": "approve", + } + assert {vote["member_id"] for vote in partial["votes"]} == {"m1", "m2"} + assert set(audit["quorum"]["votes"]) == {"m1", "m2"} + if expected == "error": + assert service.council.get_active_workflows() == [] + assert service.council._quorum_manager.get_pending_votes() == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("parallel", [False, True]) +@pytest.mark.parametrize("tool", ["authorize", "propose"]) +@pytest.mark.parametrize("native_deny", [False, True]) +async def test_incomplete_packaged_file_review_preserves_native_denial( + monkeypatch, parallel, tool, native_deny +): + service = _service(parallel=parallel) + if native_deny: + service.council._policy_engine.add_rule( + PolicyRule( + rule_id="deny-fixture", + name="Deny test commands", + priority=0, + action_types={"system.exec"}, + decision=DecisionType.DENY, + ) + ) + + class IncompleteReviewer(LLMBackend): + def provider_name(self): + return "fixture" + + async def complete(self, messages, **kwargs): + return LLMResponse(content="{}", model="fixture") + + async def unexpected_vote(*_args, **_kwargs): + pytest.fail("The Council must not vote without the configured file review") + + service._code_reviewer = CodeReviewAgent(IncompleteReviewer(), max_retries=0) + monkeypatch.setattr(service, "_evaluate_agents", unexpected_vote) + service._chairman = FakeChairman(unexpected_vote) # type: ignore[assignment] + values = _proposal("incomplete files").model_dump(exclude_defaults=True) + values["packaged_files"] = [PackagedFile(path="note.txt", content_base64="bm90ZQ==")] + if tool == "authorize": + result = await service.authorize(AuthorizeInput(**values)) + assert result.status == ("denied" if native_deny else "error") + assert result.error_code == (None if native_deny else "review_failed") + assert result.writ is None + intent_id = result.decision_id + else: + result = await service.propose_intent(ProposeIntentInput(**values)) + assert result.state == ("denied" if native_deny else "failed") + assert not result.success + intent_id = result.intent_id + + if native_deny: + assert "error_code" not in result.model_dump() + else: + assert result.model_dump()["error_code"] == "review_failed" + + workflow = service.council.get_workflow(intent_id) + if native_deny: + assert workflow is not None and workflow.state.value == "denied" + assert workflow.denial_reason in result.error + else: + assert workflow is None + assert result.code_review is None + assert service.council.get_active_workflows() == [] + assert service.council._submission_preflights == {} + entries = [ + entry + for i in range(service.council.ledger.length()) + if (entry := service.council.ledger.get(i)) is not None + and entry.entry_type.value == "intent_review_recorded" + ] + [audit] = entries + assert audit.payload["final"]["decision"] == ("deny" if native_deny else "aborted") + + +def _packaged_request_with_failed_reviewer(service): + class IncompleteReviewer(LLMBackend): + def provider_name(self): + return "fixture" + + async def complete(self, messages, **kwargs): + return LLMResponse(content="{}", model="fixture") + + service._code_reviewer = CodeReviewAgent(IncompleteReviewer(), max_retries=0) + values = _proposal("incomplete files").model_dump(exclude_defaults=True) + values["packaged_files"] = [PackagedFile(path="note.txt", content_base64="bm90ZQ==")] + return values + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tool", ["authorize", "propose"]) +@pytest.mark.parametrize("rejection", ["justification", "capacity"]) +async def test_failed_packaged_review_preserves_admission_error(tool, rejection): + service = _service() + values = _packaged_request_with_failed_reviewer(service) + if rejection == "justification": + values["justification"] = "" + expected = "Justification required for all intents" + else: + service.council.config.max_pending_intents = 1 + reserved = service.council.preflight_intent( + Intent.create( + agent_id="agent-1", + description="Inspect a separate request", + target_resource="/tmp", + justification="Hold the only admission slot", + ) + ).preflight + assert reserved is not None + expected = "Maximum pending intents exceeded" + + ledger_length = service.council.ledger.length() + try: + if tool == "authorize": + result = await service.authorize(AuthorizeInput(**values)) + assert result.status == "error" + assert result.error_code is None + assert result.writ is None + else: + result = await service.propose_intent(ProposeIntentInput(**values)) + assert not result.success + assert result.state == "" + assert result.error == expected + assert service.council.ledger.length() == ledger_length + finally: + if rejection == "capacity": + service.council.release_preflight(reserved) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tool", ["authorize", "propose"]) +async def test_failed_packaged_review_commits_native_denial_on_owning_loop(tool, monkeypatch): + service = _service() + clock = MockClock() + service.council._clock = clock + service.council.config.preflight_ttl_seconds = 1 + service.council._policy_engine.add_rule( + PolicyRule( + rule_id="deny-fixture", + name="Deny test commands", + priority=0, + action_types={"system.exec"}, + decision=DecisionType.DENY, + ) + ) + + preflight = service.council.preflight_intent + + def schedule_expiry_after_preflight(intent): + result = preflight(intent) + asyncio.get_running_loop().call_soon(lambda: clock.advance(seconds=2)) + return result + + monkeypatch.setattr(service.council, "preflight_intent", schedule_expiry_after_preflight) + values = _packaged_request_with_failed_reviewer(service) + if tool == "authorize": + result = await service.authorize(AuthorizeInput(**values)) + assert result.status == "denied" + assert result.error_code is None + assert result.writ is None + else: + result = await service.propose_intent(ProposeIntentInput(**values)) + assert result.state == "denied" + assert not result.success + assert service.council._submission_preflights == {} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tool", ["authorize", "propose"]) +@pytest.mark.parametrize( + "parallel,phase", [(False, "initial"), (False, "debate"), (True, "debate")] +) +async def test_incomplete_review_keeps_outcome_when_other_workflows_finish(tool, parallel, phase): + service = _service(parallel=parallel) + service.council.config.max_pending_intents = 2 + waiting = asyncio.Event() + release = asyncio.Event() + attempts = 0 + + async def peer(intent): + return _approval("approve" if "delayed review" in intent.description else "deny") + + async def reviewer(intent): + nonlocal attempts + if "delayed review" not in intent.description: + return _approval("deny") + attempts += 1 + if phase == "debate" and attempts == 1: + return _approval("deny") + waiting.set() + await release.wait() + raise RuntimeError("review unavailable") + + async def chairman(_intent): + return ChairmanDecision(threshold="unanimous") + + service._chairman = FakeChairman(chairman) # type: ignore[assignment] + _add_member(service, "m1", peer) + _add_member(service, "m2", reviewer) + + async def run(tag): + proposal = _proposal(tag) + if tool == "authorize": + return await service.authorize( + AuthorizeInput(**proposal.model_dump(exclude_defaults=True)), enable_debate=True + ) + return await service.propose_intent(proposal, enable_debate=True) + + task = asyncio.create_task(run("delayed review")) + try: + await asyncio.wait_for(waiting.wait(), timeout=5) + for tag in ("other review B", "other review C"): + other = await run(tag) + assert (other.status if tool == "authorize" else other.state) == "denied" + finally: + release.set() + result = await asyncio.wait_for(task, timeout=5) + + if tool == "authorize": + assert (result.status, result.error_code, result.writ) == ("error", "review_failed", None) + intent_id = result.decision_id + else: + assert (result.success, result.state, result.error) == ( + False, + "failed", + "Council review could not complete", + ) + intent_id = result.intent_id + assert result.model_dump()["error_code"] == "review_failed" + assert result.debate_rounds == 0 + assert [x.round_number for x in result.debate_history] == ([0, 1] if phase == "debate" else [0]) + assert service.council.get_workflow(intent_id).state.value == "failed" + entries = [ + entry.payload + for i in range(service.council.ledger.length()) + if (entry := service.council.ledger.get(i)) is not None + and entry.entry_type.value == "intent_review_recorded" + and entry.payload["intent_id"] == intent_id + ] + [audit] = entries + assert (audit["final"]["state"], audit["final"]["decision"]) == ("failed", "aborted") + assert audit["policy_evaluation"] + assert {vote["member_id"] for vote in audit["quorum"]["member_votes"]} == {"m1"} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tool", ["authorize", "propose"]) +@pytest.mark.parametrize("handoff", ["before_debate", "after_continuation"]) +async def test_pending_review_expires_at_parallel_handoff(tool, handoff, monkeypatch): + service = _service() + clock = MockClock() + service.council._clock = clock + service.council.config.default_token_ttl_seconds = 1 + + async def chairman(_intent): + return ChairmanDecision(threshold="unanimous") + + service._chairman = FakeChairman(chairman) # type: ignore[assignment] + _add_member(service, "m1", lambda _intent: asyncio.sleep(0, result=_approval())) + _add_member(service, "m2", lambda _intent: asyncio.sleep(0, result=_approval("deny"))) + + if handoff == "before_debate": + commit = service._commit_parallel_initial_review + + async def commit_then_expire(*args, **kwargs): + result = await commit(*args, **kwargs) + assert result[2].state.value == "awaiting_approval" + clock.advance(seconds=2) + return result + + monkeypatch.setattr(service, "_commit_parallel_initial_review", commit_then_expire) + else: + continue_review = service._continue_review_outcome + + async def continue_then_expire(*args, **kwargs): + result = await continue_review(*args, **kwargs) + assert result[3].state.value == "awaiting_approval" + clock.advance(seconds=2) + service.council.maintain_local_workflows() + return result + + monkeypatch.setattr(service, "_continue_review_outcome", continue_then_expire) + + max_rounds = 1 if handoff == "before_debate" else 0 + proposal = _proposal("expired after pending finalization") + if tool == "authorize": + result = await service.authorize( + AuthorizeInput(**proposal.model_dump(exclude_defaults=True)), + enable_debate=True, + max_debate_rounds=max_rounds, + ) + assert (result.status, result.writ) == ("error", None) + else: + result = await service.propose_intent( + proposal, enable_debate=True, max_debate_rounds=max_rounds + ) + assert (result.success, result.state) == (False, "failed") + + assert result.error_code == "review_failed" + assert result.debate_rounds == 0 + assert [round_.round_number for round_ in result.debate_history] == [0] + [audit] = [ + entry.payload + for entry in service.council.ledger._storage.iterate() + if entry.entry_type.value == "intent_review_recorded" + ] + assert (audit["final"]["state"], audit["final"]["decision"]) == ("expired", "aborted") + assert {vote["member_id"] for vote in audit["quorum"]["member_votes"]} == {"m1", "m2"} + await service.aclose_workflows() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tool", ["authorize", "propose"]) +async def test_aborted_review_audit_is_retried_with_original_payload(tool, monkeypatch): + service = _service() + clock = MockClock() + service.council._clock = clock + service.council.config.workflow_retention_seconds = 1 + reviewer_calls = 0 + + async def chairman(_intent): + return ChairmanDecision(threshold="unanimous") + + async def reviewer(_intent): + nonlocal reviewer_calls + reviewer_calls += 1 + if reviewer_calls == 1: + return _approval("deny") + raise RuntimeError("review unavailable") + + service._chairman = FakeChairman(chairman) # type: ignore[assignment] + _add_member(service, "m1", lambda _intent: asyncio.sleep(0, result=_approval())) + _add_member(service, "m2", reviewer) + original_append = service._append_review_entry + attempts = [] + ledger_unavailable = True + + def append(payload, intent_id): + attempts.append(payload) + if ledger_unavailable: + raise RuntimeError("ledger unavailable") + return original_append(payload, intent_id) + + monkeypatch.setattr(service, "_append_review_entry", append) + proposal = _proposal("failed audit") + with pytest.raises(RuntimeError, match="ledger unavailable"): + if tool == "authorize": + await service.authorize( + AuthorizeInput(**proposal.model_dump(exclude_defaults=True)), enable_debate=True + ) + else: + await service.propose_intent(proposal, enable_debate=True) + + service._workflow_janitor.cancel() + [payload] = attempts + intent_id = payload["intent_id"] + assert (payload["final"]["state"], payload["final"]["decision"]) == ("failed", "aborted") + assert [v["member_id"] for v in payload["quorum"]["member_votes"]] == ["m1"] + assert [[v["member_id"] for v in rnd["votes"]] for rnd in payload["debate_rounds"]] == [ + ["m1", "m2"], + ["m1"], + ] + assert service.council._quorum_manager.get_pending_votes() == [] + + clock.advance(seconds=3600) + service.council.maintain_local_workflows() + workflow = service.council._workflows[intent_id] + assert workflow.state.value == "failed" + await service._record_expired_reviews() + ledger_unavailable = False + await service._record_expired_reviews() + await service._record_expired_reviews() + assert attempts == [payload, payload, payload] + assert reviewer_calls == 2 + audit = service.council.ledger.get_review_by_intent(intent_id) + assert audit.payload == payload + assert workflow.metadata["audit_committed"] is True + await service._workflow_runtime.flush(intent_id, workflow.logical_version) + service.council.maintain_local_workflows() + assert intent_id not in service.council._workflows + await service.aclose_workflows() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tool", ["authorize", "propose"]) +@pytest.mark.parametrize( + "parallel,phase,expiry", + [ + (parallel, phase, expiry) + for parallel, phase in [(False, "initial"), (False, "debate"), (True, "debate")] + for expiry in ("failed_inference", "valid_inference", "finalization") + ] + + [(True, "initial", "finalization")], +) +@pytest.mark.parametrize("consolidated", [False, True]) +async def test_review_keeps_failure_outcome_when_workflow_expires( + tool, parallel, phase, expiry, consolidated, monkeypatch +): + service = _service(parallel=parallel) + service.council.config.consolidated_review_audit = consolidated + service.council._quorum_manager._record_audit_entries = not consolidated + clock = MockClock() + service.council._clock = clock + service.council.config.default_token_ttl_seconds = 1 + service.council.config.workflow_retention_seconds = 60 + attempts = 0 + + async def peer(_intent): + return _approval() + + async def reviewer(_intent): + nonlocal attempts + attempts += 1 + if phase == "debate" and attempts == 1: + return _approval("deny") + if expiry != "finalization": + clock.advance(seconds=2) + if expiry == "failed_inference": + raise RuntimeError("review unavailable") + return _approval() + + async def chairman(_intent): + return ChairmanDecision(threshold="unanimous") + + service._chairman = FakeChairman(chairman) # type: ignore[assignment] + _add_member(service, "m1", peer) + _add_member(service, "m2", reviewer) + + if expiry == "finalization": + finalize = service.council.finalize_intent_review + + def expire_before_finalize(intent_id, **kwargs): + if phase == "initial" or attempts == 2: + clock.advance(seconds=2) + return finalize(intent_id, **kwargs) + + monkeypatch.setattr(service.council, "finalize_intent_review", expire_before_finalize) + + proposal = _proposal("expired workflow") + if tool == "authorize": + result = await service.authorize( + AuthorizeInput(**proposal.model_dump(exclude_defaults=True)), enable_debate=True + ) + assert (result.status, result.writ) == ("error", None) + intent_id = result.decision_id + else: + result = await service.propose_intent(proposal, enable_debate=True) + assert (result.success, result.state) == (False, "failed") + intent_id = result.intent_id + + assert result.model_dump()["error_code"] == "review_failed" + assert result.debate_rounds == 0 + assert [round_.round_number for round_ in result.debate_history] == ( + [0, 1] if phase == "debate" else [0] + ) + assert {vote.member_id for vote in result.council_members} == ( + {"m1", "m2"} if expiry == "finalization" else set() + ) + assert service.council.get_workflow(intent_id).state.value == "expired" + assert service.council._quorum_manager.get_pending_votes() == [] + audit_type = "intent_review_recorded" if consolidated else "decision_made" + [audit] = [ + entry.payload + for i in range(service.council.ledger.length()) + if (entry := service.council.ledger.get(i)) is not None + and entry.entry_type.value == audit_type + and entry.payload["intent_id"] == intent_id + ] + if consolidated: + assert (audit["final"]["state"], audit["final"]["decision"]) == ("expired", "aborted") + assert {v["member_id"] for v in audit["quorum"].get("member_votes", [])} == { + v.member_id for v in result.council_members + } + else: + assert audit["outcome"] == "aborted" + + @pytest.mark.asyncio async def test_parallel_happy_path_enters_chairman_and_all_members_before_release(): service = _service() @@ -432,11 +1108,11 @@ async def chairman_call() -> ChairmanPreAuthDecision: @pytest.mark.asyncio -async def test_member_exception_becomes_one_deny_vote_and_siblings_are_tallied(): +async def test_member_exception_aborts_review_and_keeps_sibling_votes(): service = _service() async def chairman(_intent: Intent) -> ChairmanDecision: - return ChairmanDecision(threshold="quorum") + return ChairmanDecision(threshold="unanimous") async def raises(_intent: Intent) -> IntentEvaluation: raise RuntimeError("member unavailable") @@ -449,9 +1125,9 @@ async def raises(_intent: Intent) -> IntentEvaluation: result = await service.propose_intent(_proposal("member exception")) by_member = {vote.member_id: vote for vote in result.council_members} - assert result.state == "approved" - assert by_member["m2"].decision == "deny" - assert "Evaluation error: member unavailable" in by_member["m2"].reasoning + assert not result.success + assert result.state == "failed" + assert "m2" not in by_member assert by_member["m1"].decision == by_member["m3"].decision == "approve" @@ -460,7 +1136,7 @@ async def test_invalid_member_result_fails_closed_without_orphaning_siblings(): service = _service() async def chairman(_intent: Intent) -> ChairmanDecision: - return ChairmanDecision(threshold="quorum") + return ChairmanDecision(threshold="unanimous") async def invalid(_intent: Intent) -> Any: return None @@ -474,9 +1150,9 @@ async def invalid(_intent: Intent) -> Any: result = await service.propose_intent(_proposal("invalid member result")) by_member = {vote.member_id: vote for vote in result.council_members} - assert result.state == "approved" - assert by_member["m1"].decision == "deny" - assert "Evaluation error" in by_member["m1"].reasoning + assert not result.success + assert result.state == "failed" + assert "m1" not in by_member assert by_member["m2"].decision == by_member["m3"].decision == "approve" # Compare task sets rather than matching a private qualname: renaming the # member helper would silently make a name-based filter match nothing and diff --git a/tests/test_public_nim_smoke.py b/tests/test_public_nim_smoke.py index 5f36733d..1af80531 100644 --- a/tests/test_public_nim_smoke.py +++ b/tests/test_public_nim_smoke.py @@ -285,7 +285,7 @@ async def behavior(index, kwargs): expected_labels = { "malformed": {"ParseFailureOrFallback": 3}, "empty": {"InvalidResponse": 1, "ParseFailureOrFallback": 2}, - "invalid": {"InvalidResponse": 2, "ParseFailureOrFallback": 1}, + "invalid": {"InvalidResponse": 1, "ParseFailureOrFallback": 2}, "timeout": {"DeadlineExceeded": 3}, "http": {"AuthenticationError": 3}, }[failure]