From 60ac746164cd3eeeb6faaeb4f55f2bcfe619484a Mon Sep 17 00:00:00 2001 From: Hsin Chen Date: Wed, 18 Nov 2026 13:59:14 -0800 Subject: [PATCH 1/6] Distinguish incomplete council reviews from denials --- docs/agent-denial-recovery.md | 14 +- nomos/llm/council_agent.py | 197 +++------ nomos/nat/functions.py | 387 ++++++++++++------ tests/test_approved_fallback_contract.py | 19 +- ..._approved_fallback_contract_sdk_service.py | 24 +- tests/test_council_agent_parsing.py | 28 +- tests/test_llm.py | 30 +- tests/test_llm_fallback.py | 5 +- tests/test_llm_limits.py | 8 +- tests/test_monitor_token_usage.py | 11 +- tests/test_nat_functions.py | 7 +- tests/test_opa_nat_integration.py | 5 +- tests/test_parallel_council_review.py | 200 ++++++++- 13 files changed, 595 insertions(+), 340 deletions(-) diff --git a/docs/agent-denial-recovery.md b/docs/agent-denial-recovery.md index 895b6ebc..28b96494 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,13 @@ 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. + +If a required review cannot complete, `council_authorize` returns +`status: error` with `error_code: review_failed` and no Writ. Any member votes +in that 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. 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/llm/council_agent.py b/nomos/llm/council_agent.py index 227ec208..1afde42f 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 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.""" @@ -527,16 +537,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): @@ -546,7 +547,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): @@ -561,7 +562,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 @@ -578,6 +579,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. @@ -904,14 +915,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", log_ctx, attempt + 1, e) + 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", log_ctx, attempt + 1, e) + logger.warning("%s timed out on attempt %d, retrying", log_ctx, attempt + 1) attempt += 1 continue except Exception as e: @@ -927,7 +938,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, @@ -940,7 +951,7 @@ async def _complete_with_retry( log_ctx, attempt + 1, 1 + max_retries, - e, + _describe_failure(e), ) await asyncio.sleep(delay) attempt += 1 @@ -994,7 +1005,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. @@ -1024,7 +1035,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, @@ -1032,17 +1043,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 " @@ -1063,7 +1064,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. @@ -1103,7 +1104,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, @@ -1111,17 +1112,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 " @@ -1243,7 +1234,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( @@ -1271,15 +1262,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 " @@ -1306,13 +1289,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} @@ -1339,37 +1317,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, @@ -1497,53 +1444,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, @@ -1682,13 +1605,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 763ef329..a9c6d404 100644 --- a/nomos/nat/functions.py +++ b/nomos/nat/functions.py @@ -20,7 +20,7 @@ from contextlib import asynccontextmanager from dataclasses import dataclass from pathlib import Path -from typing import Any, ClassVar, TypeVar +from typing import Any, ClassVar, Literal, TypeVar from pydantic import ( BaseModel, @@ -63,7 +63,7 @@ PreflightResult, SecurityCouncil, ) -from nomos.level_4.council.workflow import WorkflowState +from nomos.level_4.council.workflow import IntentWorkflow, WorkflowState from nomos.llm.base import LLMBackend, LLMCallCandidate, LLMExecution from nomos.llm.council_agent import ( ChairmanAgent, @@ -71,6 +71,7 @@ CodeReviewAgent, CouncilMemberAgent, IntentEvaluation, + ReviewFailure, create_backend, format_code_review_analysis, format_code_review_result_json, @@ -107,6 +108,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" _TaskResultT = TypeVar("_TaskResultT") @@ -116,8 +118,7 @@ class PendingMemberEvaluation: """A member inference result that has not mutated council state.""" agent: CouncilMemberAgent - evaluation: IntentEvaluation - duration_ms: float + evaluation: IntentEvaluation | None def _elapsed_ms(start: float) -> float: @@ -622,6 +623,9 @@ class AuthorizeOutput(_LoadSheddingOutput): decision_id: str = Field(default="", description="Intent/decision ID") guidance: list[str] = Field(default_factory=list, description="Guidance from council on denial") error: str = Field(default="", description="Error message if status is 'error'") + error_code: Literal["review_failed"] | None = Field( + default=None, description="Set when a required Council review could not complete" + ) council_members: list[MemberVote] = Field(default_factory=list, description="Member votes") chairman: ChairmanInfo | None = Field(default=None, description="Chairman decision") code_review: MemberVote | None = Field( @@ -636,6 +640,13 @@ class AuthorizeOutput(_LoadSheddingOutput): description="Per-round vote snapshots: index 0 = initial votes, 1+ = debate rounds", ) + @model_serializer(mode="wrap") + def serialize_retry_hint(self, handler: SerializerFunctionWrapHandler): + data = super().serialize_retry_hint(handler) + if self.error_code is None: + data.pop("error_code", None) + return data + @model_validator(mode="after") def clarify_denial_retry_semantics(self) -> "AuthorizeOutput": # Existing agents render guidance, not necessarily the output schema. @@ -1260,21 +1271,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}, ) @@ -1559,11 +1570,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 ) @@ -1581,6 +1599,38 @@ async def _preflight_intent(self, intent: Intent) -> PreflightResult: raise asyncio.CancelledError return result + async def _commit_native_denial_after_review_failure( + self, + intent: Intent, + *, + request_type: str, + ) -> tuple[IntentWorkflow | None, bool]: + """Preserve native policy denials without admitting an incomplete review.""" + preflight_result = await self._preflight_intent(intent) + preflight = preflight_result.preflight + if preflight is None: + return None, False + if preflight.policy_evaluation.decision.decision != DecisionType.DENY: + await self._release_preflight_safely(preflight) + return None, False + + try: + _, _, workflow, _, _, cancelled = await self._commit_parallel_initial_review( + intent, + preflight, + [], + review_threshold=None, + enable_debate=False, + request_type=request_type, + ) + except BaseException: + await self._release_preflight_safely(preflight) + raise + if workflow is None: + # The preflight can expire while waiting for the submit lock. + await self._release_preflight_safely(preflight) + return workflow, cancelled + @staticmethod async def _shield_and_drain( task: asyncio.Task[_TaskResultT], @@ -1992,7 +2042,8 @@ async def _continue_review_outcome( allow_pending=round_num < bounded_rounds and not self._all_agree(votes), ).workflow debate_history.append(DebateRound(round_number=round_num, votes=list(votes))) - debate_rounds_completed += 1 + if workflow is None or workflow.state != WorkflowState.FAILED: + 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)", @@ -2526,11 +2577,53 @@ 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, cancelled = await self._commit_native_denial_after_review_failure( + intent, request_type="propose" + ) + final_state = ( + WorkflowState.DENIED if denied_workflow is not None else WorkflowState.FAILED + ) + 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, + error=( + f"Intent denied: {denied_workflow.denial_reason}" + if denied_workflow is not None + else _REVIEW_FAILED_MESSAGE + ), + ) parallel_enabled = bool( self._chairman and self._settings.chairman.parallel_member_evaluation @@ -2838,12 +2931,17 @@ async def propose_intent( _stage(stages, tool, "review_collect", stage_start, intent_id=intent.intent_id) state_value = state.value if state else "unknown" - if state in (WorkflowState.APPROVED, WorkflowState.DENIED): + if state in (WorkflowState.APPROVED, WorkflowState.DENIED, WorkflowState.FAILED): self._record_consolidated_review( intent, request_type="propose", final_state=state_value, - decision="approve" if state == WorkflowState.APPROVED else "deny", + decision={ + WorkflowState.APPROVED: "approve", + WorkflowState.DENIED: "deny", + WorkflowState.FAILED: "aborted", + }[state], + denial_reason=_REVIEW_FAILED_MESSAGE if state == WorkflowState.FAILED else "", workflow=self._council.get_workflow(intent.intent_id), opa_decision=opa_decision, votes=votes, @@ -2856,7 +2954,7 @@ async def propose_intent( self._publish_latency( tool=tool, intent_id=intent.intent_id, - outcome=state_value, + outcome="error" if state == WorkflowState.FAILED else state_value, stages=stages, actors=actors, stage_intervals=stage_intervals or None, @@ -2867,7 +2965,8 @@ async def propose_intent( return ProposeIntentOutput( api_version=input_data.api_version, council_id=effective_council_id, - success=True, + success=state != WorkflowState.FAILED, + error=_REVIEW_FAILED_MESSAGE if state == WorkflowState.FAILED else "", intent_id=intent.intent_id, state=state_value, requires_approval=state == WorkflowState.AWAITING_APPROVAL, @@ -2894,81 +2993,57 @@ async def _evaluate_agents( 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) @@ -2983,10 +3058,13 @@ def _record_agent_votes( ) -> list[MemberVote]: """Cast buffered member evaluations in configured member order.""" votes: list[MemberVote] = [] + complete = all(item.evaluation is not None for item in evaluations) for pending in evaluations: agent = pending.agent eval_result = pending.evaluation + if eval_result is None: + continue votes.append( MemberVote( member_id=agent.member_id, @@ -3007,7 +3085,7 @@ def _record_agent_votes( agent.member_id, VoteType.APPROVE if eval_result.decision == "approve" else VoteType.DENY, reason=eval_result.reasoning, - finalize=finalize, + finalize=finalize and complete, ) if not vote_result.success: logger.warning( @@ -3017,6 +3095,8 @@ def _record_agent_votes( vote_result.error, ) + if not complete: + self._council.abort_intent_review(intent.intent_id, _REVIEW_FAILED_MESSAGE) return votes @staticmethod @@ -3065,85 +3145,49 @@ 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}", - ) + complete = all(item.evaluation is not None for item in evaluations) + 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] + and previous_decisions[agent.member_id] != eval_result.decision ) 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] + 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, # type: ignore[union-attr] + guidance=eval_result.guidance, changed_vote=changed, ) ) - 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=finalize and complete, ) if not vote_result.success: logger.warning( @@ -3153,6 +3197,8 @@ async def _debate_one( vote_result.error, ) + if not complete: + self._council.abort_intent_review(intent.intent_id, _REVIEW_FAILED_MESSAGE) return new_votes def check_intent_status(self, input_data: IntentStatusInput) -> IntentStatusOutput: @@ -3407,11 +3453,53 @@ 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, cancelled = await self._commit_native_denial_after_review_failure( + intent, request_type="authorize" + ) + final_state = ( + WorkflowState.DENIED if denied_workflow is not None else WorkflowState.FAILED + ) + 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=None if denied_workflow is not None else "review_failed", + decision_id=intent.intent_id, + error=( + denied_workflow.denial_reason + if denied_workflow is not None + else _REVIEW_FAILED_MESSAGE + ), + ) parallel_enabled = bool( self._chairman and self._settings.chairman.parallel_member_evaluation @@ -3849,6 +3937,47 @@ def chairman_authorizes(decision: Any) -> bool: actor_timings=actors, ) _stage(stages, tool, "review_collect", stage_start, intent_id=intent.intent_id) + if state == WorkflowState.FAILED: + self._record_consolidated_review( + intent, + request_type="authorize", + final_state=state.value, + decision="aborted", + workflow=self._council.get_workflow(intent.intent_id), + opa_decision=opa_decision, + votes=votes, + chairman=chairman_info, + code_review=code_review_vote, + debate_history=debate_history, + denial_reason=_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: 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_llm.py b/tests/test_llm.py index 8a3ac3ee..e2e763b1 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 c5ddc9c0..3c8c7201 100644 --- a/tests/test_nat_functions.py +++ b/tests/test_nat_functions.py @@ -28,6 +28,7 @@ CodeReviewAgent, CouncilMemberAgent, IntentEvaluation, + ReviewFailure, _format_intent_for_review, format_debate_context, ) @@ -1509,7 +1510,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 @@ -2426,7 +2427,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": [ @@ -2438,7 +2439,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_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 1dcfddff..77c4a2a5 100644 --- a/tests/test_parallel_council_review.py +++ b/tests/test_parallel_council_review.py @@ -14,12 +14,15 @@ 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.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 +121,185 @@ 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"]) +@pytest.mark.parametrize("consolidated", [False, True]) +async def test_authorize_incomplete_member_review_is_not_a_vote( + parallel, failure, consolidated, 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 + 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="quorum") + + reviewer = CouncilMemberAgent( + CouncilMemberConfig(id="m2", backend="fixture"), + FailingBackend(), + max_retries=0, + ) + _add_member(service, "m1", lambda _intent: asyncio.sleep(0, result=_approval())) + _add_member(service, "m2", reviewer.evaluate_intent) + _add_member(service, "m3", lambda _intent: asyncio.sleep(0, result=_approval())) + service._chairman = FakeChairman(chairman) # type: ignore[assignment] + + result = await service.authorize(AuthorizeInput(**_proposal("incomplete").model_dump())) + + assert result.status == "error" + assert result.model_dump()["error_code"] == "review_failed" + assert result.writ is None + assert {vote.member_id for vote in result.council_members} == {"m1", "m3"} + assert service.council.get_workflow(result.decision_id).state.value == "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" + failed_actor = next(actor for actor in latency[-1]["actors"] if actor["member_id"] == "m2") + assert (failed_actor["status"], failed_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 + ] + if consolidated: + [review] = [ + entry.payload for entry in entries if entry.entry_type.value == "intent_review_recorded" + ] + assert (review["final"]["state"], review["final"]["decision"]) == ("failed", "aborted") + 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"] == "aborted" + assert decision["deny_weight"] == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("parallel", [False, True]) +async def test_authorize_failed_debate_preserves_completed_round_and_partial_votes(parallel): + service = _service(parallel=parallel) + 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 == "m3" else "approve") + if member_id == "m3": + raise RuntimeError("failed re-evaluation") + return _approval() + + async def chairman(_intent: Intent) -> ChairmanDecision: + return ChairmanDecision(threshold="unanimous") + + 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()), + enable_debate=True, + ) + + assert result.status == "error" + assert result.error_code == "review_failed" + assert result.writ is None + first, partial = result.debate_history + 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": "approve", + "m3": "deny", + } + assert {vote.member_id for vote in partial.votes} == {"m1", "m2"} + 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() + 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 + + 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") + + @pytest.mark.asyncio async def test_parallel_happy_path_enters_chairman_and_all_members_before_release(): service = _service() @@ -432,7 +614,7 @@ 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: @@ -449,9 +631,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" @@ -474,9 +656,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 From 6b8c2d97dec62e414a86cfe8699c8804e88f8064 Mon Sep 17 00:00:00 2001 From: Hsin Chen Date: Wed, 18 Nov 2026 18:12:17 -0800 Subject: [PATCH 2/6] Preserve review outcomes through admission and workflow eviction --- docs/agent-denial-recovery.md | 6 + nomos/nat/functions.py | 206 ++++++++++++++------------ tests/test_one_to_one_ledger.py | 5 +- tests/test_parallel_council_review.py | 172 +++++++++++++++++++++ 4 files changed, 291 insertions(+), 98 deletions(-) diff --git a/docs/agent-denial-recovery.md b/docs/agent-denial-recovery.md index 28b96494..4184bc82 100644 --- a/docs/agent-denial-recovery.md +++ b/docs/agent-denial-recovery.md @@ -32,6 +32,12 @@ in that 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. +A deterministic native policy denial still returns `status: denied` if a +packaged-file review fails. Follow the denial guidance in that case. If the +request cannot pass admission, such as a missing required justification or a +full pending queue, the response reports the admission error without +`review_failed`. None of these outcomes issues a Writ. + 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; the original denial grants no permission. The agent must not invent evidence, diff --git a/nomos/nat/functions.py b/nomos/nat/functions.py index a9c6d404..54647891 100644 --- a/nomos/nat/functions.py +++ b/nomos/nat/functions.py @@ -1599,37 +1599,33 @@ async def _preflight_intent(self, intent: Intent) -> PreflightResult: raise asyncio.CancelledError return result - async def _commit_native_denial_after_review_failure( - self, - intent: Intent, - *, - request_type: str, - ) -> tuple[IntentWorkflow | None, bool]: - """Preserve native policy denials without admitting an incomplete review.""" - preflight_result = await self._preflight_intent(intent) - preflight = preflight_result.preflight - if preflight is None: - return None, False - if preflight.policy_evaluation.decision.decision != DecisionType.DENY: - await self._release_preflight_safely(preflight) - return None, False + 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 in one submission lock.""" + + 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._council.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) - try: - _, _, workflow, _, _, cancelled = await self._commit_parallel_initial_review( - intent, - preflight, - [], - review_threshold=None, - enable_debate=False, - request_type=request_type, + async with self._submit_lock: + return await self._shield_and_drain( + asyncio.create_task(asyncio.to_thread(check_and_commit)) ) - except BaseException: - await self._release_preflight_safely(preflight) - raise - if workflow is None: - # The preflight can expire while waiting for the submit lock. - await self._release_preflight_safely(preflight) - return workflow, cancelled @staticmethod async def _shield_and_drain( @@ -1899,10 +1895,14 @@ async def _commit() -> tuple[Any, list[MemberVote], Any | None, float, float]: 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 + if workflow is None or workflow.state != WorkflowState.FAILED: + workflow = ( + self._council.finalize_intent_review( + intent.intent_id, + allow_pending=enable_debate and not self._all_agree(votes), + ).workflow + or workflow + ) except BaseException as exc: # BaseException, not Exception: once submit_intent has # consumed the preflight, created the workflow and opened @@ -1977,17 +1977,22 @@ 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]: """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 + if workflow is None or workflow.state != WorkflowState.FAILED: + workflow = ( + self._council.finalize_intent_review( + intent.intent_id, + allow_pending=enable_debate and not self._all_agree(votes), + ).workflow + or workflow + ) return await self._continue_review_outcome( intent, @@ -2002,12 +2007,12 @@ async def _continue_review_outcome( self, intent: Intent, votes: list[MemberVote], - workflow: Any | None, + 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]: """Continue from an already-recorded initial round into dependent debate rounds.""" debate_history: list[DebateRound] = [DebateRound(round_number=0, votes=list(votes))] @@ -2037,29 +2042,28 @@ async def _continue_review_outcome( 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 debate_history.append(DebateRound(round_number=round_num, votes=list(votes))) - if workflow is None or workflow.state != WorkflowState.FAILED: - debate_rounds_completed += 1 - if workflow is None or workflow.state != WorkflowState.AWAITING_APPROVAL: + if workflow.state == WorkflowState.FAILED: + break + workflow = ( + self._council.finalize_intent_review( + intent.intent_id, + allow_pending=round_num < bounded_rounds and not self._all_agree(votes), + ).workflow + or workflow + ) + debate_rounds_completed += 1 + if 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, ) 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 def _record_consolidated_review( self, @@ -2586,22 +2590,24 @@ async def propose_intent( ) ) if isinstance(code_review_vote, ReviewFailure): - denied_workflow, cancelled = await self._commit_native_denial_after_review_failure( - intent, request_type="propose" - ) + ( + (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 ) - 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), - ) + if submission_error is None: + 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, @@ -2617,11 +2623,11 @@ async def propose_intent( council_id=effective_council_id, success=False, intent_id=intent.intent_id, - state=final_state.value, + state=final_state.value if submission_error is None else "", error=( f"Intent denied: {denied_workflow.denial_reason}" if denied_workflow is not None - else _REVIEW_FAILED_MESSAGE + else submission_error or _REVIEW_FAILED_MESSAGE ), ) @@ -2896,7 +2902,7 @@ async def propose_intent( votes = initial_votes 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( @@ -2910,7 +2916,7 @@ async def propose_intent( ) ) ) - votes, debate_history, debate_rounds_completed, state = continuation + votes, debate_history, debate_rounds_completed, reviewed_workflow = continuation deferred_cancellation = deferred_cancellation or continuation_cancelled stages["review_collect"] = stages.get("member_evaluation", 0.0) + _elapsed_ms( review_continuation_started @@ -2921,14 +2927,16 @@ async def propose_intent( votes, debate_history, debate_rounds_completed, - state, + reviewed_workflow, ) = 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) + state = reviewed_workflow.state if reviewed_workflow is not None else None state_value = state.value if state else "unknown" if state in (WorkflowState.APPROVED, WorkflowState.DENIED, WorkflowState.FAILED): @@ -2942,7 +2950,7 @@ async def propose_intent( WorkflowState.FAILED: "aborted", }[state], denial_reason=_REVIEW_FAILED_MESSAGE if state == WorkflowState.FAILED else "", - workflow=self._council.get_workflow(intent.intent_id), + workflow=reviewed_workflow, opa_decision=opa_decision, votes=votes, chairman=chairman_info, @@ -3462,22 +3470,24 @@ async def authorize( ) ) if isinstance(code_review_vote, ReviewFailure): - denied_workflow, cancelled = await self._commit_native_denial_after_review_failure( - intent, request_type="authorize" - ) + ( + (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 ) - 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), - ) + if submission_error is None: + 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, @@ -3492,12 +3502,14 @@ async def authorize( api_version=input_data.api_version, council_id=effective_council_id, status="denied" if denied_workflow is not None else "error", - error_code=None if denied_workflow is not None else "review_failed", + 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 _REVIEW_FAILED_MESSAGE + else submission_error or _REVIEW_FAILED_MESSAGE ), ) @@ -3904,7 +3916,7 @@ def chairman_authorizes(decision: Any) -> bool: votes = initial_votes 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( @@ -3918,7 +3930,7 @@ def chairman_authorizes(decision: Any) -> bool: ) ) ) - votes, debate_history, debate_rounds_completed, state = continuation + votes, debate_history, debate_rounds_completed, reviewed_workflow = continuation deferred_cancellation = deferred_cancellation or continuation_cancelled stages["review_collect"] = stages.get("member_evaluation", 0.0) + _elapsed_ms( review_continuation_started @@ -3929,21 +3941,23 @@ def chairman_authorizes(decision: Any) -> bool: votes, debate_history, debate_rounds_completed, - state, + reviewed_workflow, ) = 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) + state = reviewed_workflow.state if reviewed_workflow is not None else None if state == WorkflowState.FAILED: self._record_consolidated_review( intent, request_type="authorize", final_state=state.value, decision="aborted", - workflow=self._council.get_workflow(intent.intent_id), + workflow=reviewed_workflow, opa_decision=opa_decision, votes=votes, chairman=chairman_info, @@ -3989,7 +4003,7 @@ def chairman_authorizes(decision: Any) -> bool: request_type="authorize", final_state=state.value, decision="deny", - workflow=self._council.get_workflow(intent.intent_id), + workflow=reviewed_workflow, opa_decision=opa_decision, votes=votes, chairman=chairman_info, @@ -4026,7 +4040,7 @@ def chairman_authorizes(decision: Any) -> bool: request_type="authorize", final_state=state.value, decision="deny", - workflow=self._council.get_workflow(intent.intent_id), + workflow=reviewed_workflow, opa_decision=opa_decision, votes=votes, chairman=chairman_info, @@ -4063,7 +4077,7 @@ def chairman_authorizes(decision: Any) -> bool: 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/test_one_to_one_ledger.py b/tests/test_one_to_one_ledger.py index 6c3efa19..c51ffd08 100644 --- a/tests/test_one_to_one_ledger.py +++ b/tests/test_one_to_one_ledger.py @@ -321,8 +321,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 monkeypatch.setattr(service, "_collect_review_outcome", fake_collect) await service.authorize(request) diff --git a/tests/test_parallel_council_review.py b/tests/test_parallel_council_review.py index 77c4a2a5..856d1878 100644 --- a/tests/test_parallel_council_review.py +++ b/tests/test_parallel_council_review.py @@ -15,6 +15,7 @@ from nomos.auth.permissions import PermissionScope from nomos.auth.writ_factory import WritFactory 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 @@ -300,6 +301,177 @@ async def unexpected_vote(*_args, **_kwargs): 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() + 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_before_unlocking(tool): + 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, + ) + ) + + class AdvanceClockOnRelease(asyncio.Lock): + def release(self): + # Model other work holding the submission lock between preflight and commit. + if service.council._submission_preflights: + clock.advance(seconds=2) + super().release() + + service._submit_lock = AdvanceClockOnRelease() + 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_terminal_workflow_is_evicted( + 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()), 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.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) is None + 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 async def test_parallel_happy_path_enters_chairman_and_all_members_before_release(): service = _service() From bc3dffffda39e2f846f6bed39c99bf761b565058 Mon Sep 17 00:00:00 2001 From: Hsin Chen Date: Wed, 18 Nov 2026 18:31:03 -0800 Subject: [PATCH 3/6] Align smoke test and secret baseline with review failure changes --- .secrets.baseline | 2 +- tests/test_public_nim_smoke.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.secrets.baseline b/.secrets.baseline index 526da46f..7edb46ed 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -1504,7 +1504,7 @@ "filename": "tests/test_llm.py", "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", "is_verified": false, - "line_number": 577 + "line_number": 575 } ] }, 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] From 534cf79fb0e78ead01c158ae3fcb287a89a68993 Mon Sep 17 00:00:00 2001 From: Hsin Chen Date: Wed, 18 Nov 2026 18:36:36 -0800 Subject: [PATCH 4/6] Keep incomplete review outcomes independent of workflow expiry --- docs/agent-denial-recovery.md | 23 +++-- nomos/level_4/council/council.py | 7 +- nomos/nat/functions.py | 137 +++++++++++++++++--------- tests/test_one_to_one_ledger.py | 2 +- tests/test_parallel_council_review.py | 66 +++++++++++++ 5 files changed, 174 insertions(+), 61 deletions(-) diff --git a/docs/agent-denial-recovery.md b/docs/agent-denial-recovery.md index 4184bc82..b67ae2e5 100644 --- a/docs/agent-denial-recovery.md +++ b/docs/agent-denial-recovery.md @@ -26,17 +26,20 @@ 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. -If a required review cannot complete, `council_authorize` returns -`status: error` with `error_code: review_failed` and no Writ. Any member votes -in that 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. +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`. -A deterministic native policy denial still returns `status: denied` if a -packaged-file review fails. Follow the denial guidance in that case. If the -request cannot pass admission, such as a missing required justification or a -full pending queue, the response reports the admission error without -`review_failed`. None of these outcomes issues a Writ. +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. 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_4/council/council.py b/nomos/level_4/council/council.py index 3a40a97a..1b8b93bb 100644 --- a/nomos/level_4/council/council.py +++ b/nomos/level_4/council/council.py @@ -735,10 +735,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/nat/functions.py b/nomos/nat/functions.py index 54647891..f3048eef 100644 --- a/nomos/nat/functions.py +++ b/nomos/nat/functions.py @@ -121,6 +121,12 @@ class PendingMemberEvaluation: evaluation: IntentEvaluation | None +@dataclass(frozen=True) +class MemberReviewRound: + votes: list["MemberVote"] + complete: bool = True + + def _elapsed_ms(start: float) -> float: return (time.perf_counter() - start) * 1000 @@ -374,7 +380,20 @@ def serialize_retry_hint(self, handler: SerializerFunctionWrapHandler): return data -class ProposeIntentOutput(_LoadSheddingOutput): +class _ReviewOutput(_LoadSheddingOutput): + error_code: Literal["review_failed"] | None = Field( + default=None, description="Set when a required Council review could not complete" + ) + + @model_serializer(mode="wrap") + def serialize_retry_hint(self, handler: SerializerFunctionWrapHandler): + data = super().serialize_retry_hint(handler) + if self.error_code is None: + data.pop("error_code", None) + return data + + +class ProposeIntentOutput(_ReviewOutput): """Output schema for propose_intent.""" api_version: str = API_VERSION_V1 @@ -610,7 +629,7 @@ def validate_operation_shape(self) -> "AuthorizeInput": ) -class AuthorizeOutput(_LoadSheddingOutput): +class AuthorizeOutput(_ReviewOutput): """Output for council_authorize.""" api_version: str = API_VERSION_V1 @@ -623,9 +642,6 @@ class AuthorizeOutput(_LoadSheddingOutput): decision_id: str = Field(default="", description="Intent/decision ID") guidance: list[str] = Field(default_factory=list, description="Guidance from council on denial") error: str = Field(default="", description="Error message if status is 'error'") - error_code: Literal["review_failed"] | None = Field( - default=None, description="Set when a required Council review could not complete" - ) council_members: list[MemberVote] = Field(default_factory=list, description="Member votes") chairman: ChairmanInfo | None = Field(default=None, description="Chairman decision") code_review: MemberVote | None = Field( @@ -640,13 +656,6 @@ class AuthorizeOutput(_LoadSheddingOutput): description="Per-round vote snapshots: index 0 = initial votes, 1+ = debate rounds", ) - @model_serializer(mode="wrap") - def serialize_retry_hint(self, handler: SerializerFunctionWrapHandler): - data = super().serialize_retry_hint(handler) - if self.error_code is None: - data.pop("error_code", None) - return data - @model_validator(mode="after") def clarify_denial_retry_semantics(self) -> "AuthorizeOutput": # Existing agents render guidance, not necessarily the output schema. @@ -1874,10 +1883,10 @@ 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, 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, float, float]: async with self._submit_lock: submit_started = time.perf_counter() result = await asyncio.to_thread( @@ -1888,18 +1897,21 @@ async def _commit() -> tuple[Any, list[MemberVote], Any | None, float, float]: ) submit_ms = _elapsed_ms(submit_started) - votes: list[MemberVote] = [] + initial_round = MemberReviewRound([]) 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) - if workflow is None or workflow.state != WorkflowState.FAILED: + initial_round = self._record_agent_votes( + intent, evaluations, finalize=False + ) + if initial_round.complete: workflow = ( self._council.finalize_intent_review( intent.intent_id, - allow_pending=enable_debate and not self._all_agree(votes), + allow_pending=enable_debate + and not self._all_agree(initial_round.votes), ).workflow or workflow ) @@ -1949,7 +1961,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: @@ -1968,7 +1980,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, submit_ms, tally_ms committed, cancelled = await self._shield_and_drain(asyncio.create_task(_commit())) return (*committed, cancelled) @@ -1981,22 +1993,22 @@ async def _collect_review_outcome( enable_debate: bool, max_debate_rounds: int, actor_timings: list[dict[str, Any]] | None = None, - ) -> tuple[list[MemberVote], list[DebateRound], int, IntentWorkflow | 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) - if workflow is None or workflow.state != WorkflowState.FAILED: + initial_round = self._record_agent_votes(intent, evaluations, finalize=False) + if initial_round.complete: workflow = ( self._council.finalize_intent_review( intent.intent_id, - allow_pending=enable_debate and not self._all_agree(votes), + allow_pending=enable_debate and not self._all_agree(initial_round.votes), ).workflow or workflow ) return await self._continue_review_outcome( intent, - votes, + initial_round, workflow, enable_debate=enable_debate, max_debate_rounds=max_debate_rounds, @@ -2006,16 +2018,18 @@ async def _collect_review_outcome( async def _continue_review_outcome( self, intent: Intent, - votes: list[MemberVote], + initial_round: MemberReviewRound, workflow: IntentWorkflow | None, *, enable_debate: bool, max_debate_rounds: int, actor_timings: list[dict[str, Any]] | None = None, - ) -> tuple[list[MemberVote], list[DebateRound], int, IntentWorkflow | 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 + review_complete = initial_round.complete + debate_history = [DebateRound(round_number=0, votes=list(votes))] debate_rounds_completed = 0 # Clamp the (potentially request-supplied) round count to a safe ceiling @@ -2024,6 +2038,7 @@ async def _continue_review_outcome( if ( enable_debate + and review_complete and votes and workflow is not None and workflow.state == WorkflowState.AWAITING_APPROVAL @@ -2035,15 +2050,17 @@ 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, ) + votes = debate_round.votes + review_complete = debate_round.complete debate_history.append(DebateRound(round_number=round_num, votes=list(votes))) - if workflow.state == WorkflowState.FAILED: + if not review_complete: break workflow = ( self._council.finalize_intent_review( @@ -2063,7 +2080,7 @@ async def _continue_review_outcome( break # Keep the result of this request even if terminal cache entries are evicted. - return votes, debate_history, debate_rounds_completed, workflow + return votes, debate_history, debate_rounds_completed, workflow, review_complete def _record_consolidated_review( self, @@ -2624,6 +2641,9 @@ async def propose_intent( 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 @@ -2634,7 +2654,7 @@ async def propose_intent( parallel_enabled = bool( self._chairman and self._settings.chairman.parallel_member_evaluation ) - initial_votes: list[MemberVote] = [] + initial_round = MemberReviewRound([]) initial_workflow: Any | None = None deferred_cancellation = False @@ -2775,7 +2795,7 @@ async def propose_intent( try: ( result, - initial_votes, + initial_round, initial_workflow, submit_ms, tally_ms, @@ -2895,11 +2915,12 @@ async def propose_intent( if parallel_enabled: review_continuation_started = time.perf_counter() - if ( + if not initial_round.complete or ( initial_workflow is not None and initial_workflow.state != WorkflowState.AWAITING_APPROVAL ): - votes = initial_votes + votes = initial_round.votes + review_complete = initial_round.complete debate_history = [DebateRound(round_number=0, votes=list(votes))] debate_rounds_completed = 0 reviewed_workflow = initial_workflow @@ -2908,7 +2929,7 @@ async def propose_intent( asyncio.create_task( self._continue_review_outcome( intent, - initial_votes, + initial_round, initial_workflow, enable_debate=enable_debate, max_debate_rounds=max_debate_rounds, @@ -2916,7 +2937,13 @@ async def propose_intent( ) ) ) - votes, debate_history, debate_rounds_completed, reviewed_workflow = continuation + ( + votes, + debate_history, + debate_rounds_completed, + reviewed_workflow, + review_complete, + ) = continuation deferred_cancellation = deferred_cancellation or continuation_cancelled stages["review_collect"] = stages.get("member_evaluation", 0.0) + _elapsed_ms( review_continuation_started @@ -2928,6 +2955,7 @@ async def propose_intent( debate_history, debate_rounds_completed, reviewed_workflow, + review_complete, ) = await self._collect_review_outcome( intent, workflow=result.workflow, @@ -2937,6 +2965,8 @@ async def propose_intent( ) _stage(stages, tool, "review_collect", stage_start, intent_id=intent.intent_id) state = reviewed_workflow.state if reviewed_workflow is not None else None + if not review_complete: + state = WorkflowState.FAILED state_value = state.value if state else "unknown" if state in (WorkflowState.APPROVED, WorkflowState.DENIED, WorkflowState.FAILED): @@ -2974,6 +3004,7 @@ async def propose_intent( api_version=input_data.api_version, council_id=effective_council_id, success=state != WorkflowState.FAILED, + error_code="review_failed" if state == WorkflowState.FAILED else None, error=_REVIEW_FAILED_MESSAGE if state == WorkflowState.FAILED else "", intent_id=intent.intent_id, state=state_value, @@ -2994,7 +3025,7 @@ 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) + return self._record_agent_votes(intent, evaluations, finalize=finalize).votes async def _evaluate_agents( self, @@ -3063,7 +3094,7 @@ def _record_agent_votes( evaluations: list[PendingMemberEvaluation], *, finalize: bool = False, - ) -> list[MemberVote]: + ) -> MemberReviewRound: """Cast buffered member evaluations in configured member order.""" votes: list[MemberVote] = [] complete = all(item.evaluation is not None for item in evaluations) @@ -3105,7 +3136,7 @@ def _record_agent_votes( if not complete: self._council.abort_intent_review(intent.intent_id, _REVIEW_FAILED_MESSAGE) - return votes + return MemberReviewRound(votes, complete) @staticmethod def _all_agree(votes: list[MemberVote]) -> bool: @@ -3143,7 +3174,7 @@ async def _run_debate_round( *, 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 @@ -3207,7 +3238,7 @@ async def _run_debate_round( if not complete: self._council.abort_intent_review(intent.intent_id, _REVIEW_FAILED_MESSAGE) - return new_votes + return MemberReviewRound(new_votes, complete) def check_intent_status(self, input_data: IntentStatusInput) -> IntentStatusOutput: """Check the current status of an intent.""" @@ -3516,7 +3547,7 @@ async def authorize( parallel_enabled = bool( self._chairman and self._settings.chairman.parallel_member_evaluation ) - initial_votes: list[MemberVote] = [] + initial_round = MemberReviewRound([]) initial_workflow: Any | None = None deferred_cancellation = False @@ -3708,7 +3739,7 @@ def chairman_authorizes(decision: Any) -> bool: try: ( result, - initial_votes, + initial_round, initial_workflow, submit_ms, tally_ms, @@ -3909,11 +3940,12 @@ def chairman_authorizes(decision: Any) -> bool: if parallel_enabled: review_continuation_started = time.perf_counter() - if ( + if not initial_round.complete or ( initial_workflow is not None and initial_workflow.state != WorkflowState.AWAITING_APPROVAL ): - votes = initial_votes + votes = initial_round.votes + review_complete = initial_round.complete debate_history = [DebateRound(round_number=0, votes=list(votes))] debate_rounds_completed = 0 reviewed_workflow = initial_workflow @@ -3922,7 +3954,7 @@ def chairman_authorizes(decision: Any) -> bool: asyncio.create_task( self._continue_review_outcome( intent, - initial_votes, + initial_round, initial_workflow, enable_debate=enable_debate, max_debate_rounds=max_debate_rounds, @@ -3930,7 +3962,13 @@ def chairman_authorizes(decision: Any) -> bool: ) ) ) - votes, debate_history, debate_rounds_completed, reviewed_workflow = continuation + ( + votes, + debate_history, + debate_rounds_completed, + reviewed_workflow, + review_complete, + ) = continuation deferred_cancellation = deferred_cancellation or continuation_cancelled stages["review_collect"] = stages.get("member_evaluation", 0.0) + _elapsed_ms( review_continuation_started @@ -3942,6 +3980,7 @@ def chairman_authorizes(decision: Any) -> bool: debate_history, debate_rounds_completed, reviewed_workflow, + review_complete, ) = await self._collect_review_outcome( intent, workflow=result.workflow, @@ -3951,6 +3990,8 @@ def chairman_authorizes(decision: Any) -> bool: ) _stage(stages, tool, "review_collect", stage_start, intent_id=intent.intent_id) state = reviewed_workflow.state if reviewed_workflow is not None else None + if not review_complete: + state = WorkflowState.FAILED if state == WorkflowState.FAILED: self._record_consolidated_review( intent, diff --git a/tests/test_one_to_one_ledger.py b/tests/test_one_to_one_ledger.py index c51ffd08..715afcdf 100644 --- a/tests/test_one_to_one_ledger.py +++ b/tests/test_one_to_one_ledger.py @@ -323,7 +323,7 @@ async def test_authorize_orchestration_carries_debate_into_record(tmp_path, monk async def fake_collect(intent, *, workflow, **kwargs): workflow.state = WorkflowState.DENIED - return debate[-1].votes, debate, 1, workflow + 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_parallel_council_review.py b/tests/test_parallel_council_review.py index 856d1878..0d190b36 100644 --- a/tests/test_parallel_council_review.py +++ b/tests/test_parallel_council_review.py @@ -282,6 +282,11 @@ async def unexpected_vote(*_args, **_kwargs): 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" @@ -456,6 +461,7 @@ async def run(tag): "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) is None @@ -472,6 +478,66 @@ async def run(tag): assert {vote["member_id"] for vote in audit["quorum"]["member_votes"]} == {"m1"} +@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_workflow_expires(tool, parallel, phase): + service = _service(parallel=parallel) + clock = MockClock() + service.council._clock = clock + service.council.config.default_token_ttl_seconds = 1 + 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") + clock.advance(seconds=2) + 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) + + proposal = _proposal("expired workflow") + if tool == "authorize": + result = await service.authorize( + AuthorizeInput(**proposal.model_dump()), 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"} + assert service.council.get_workflow(intent_id).state.value == "expired" + assert service.council._quorum_manager.get_pending_votes() == [] + [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" + and entry.payload["intent_id"] == intent_id + ] + assert (audit["final"]["state"], audit["final"]["decision"]) == ("failed", "aborted") + + @pytest.mark.asyncio async def test_parallel_happy_path_enters_chairman_and_all_members_before_release(): service = _service() From bb602d9c371761f021012464cccac2489b478f03 Mon Sep 17 00:00:00 2001 From: Hsin Chen Date: Fri, 20 Nov 2026 13:35:33 -0800 Subject: [PATCH 5/6] fix(council): preserve quorum and report expired reviews --- nomos/level_2/quorum/manager.py | 30 +++- nomos/level_4/council/council.py | 16 +- nomos/nat/functions.py | 211 +++++++++++++++----------- tests/test_parallel_council_review.py | 180 +++++++++++++++++----- 4 files changed, 298 insertions(+), 139 deletions(-) diff --git a/nomos/level_2/quorum/manager.py b/nomos/level_2/quorum/manager.py index a12f8942..19542286 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 abort_vote(self, intent_id: str) -> bool: diff --git a/nomos/level_4/council/council.py b/nomos/level_4/council/council.py index 1b8b93bb..c53959f1 100644 --- a/nomos/level_4/council/council.py +++ b/nomos/level_4/council/council.py @@ -659,6 +659,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) @@ -703,12 +706,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() @@ -719,7 +729,9 @@ 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) + 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) diff --git a/nomos/nat/functions.py b/nomos/nat/functions.py index f3048eef..c9ace781 100644 --- a/nomos/nat/functions.py +++ b/nomos/nat/functions.py @@ -125,6 +125,7 @@ class PendingMemberEvaluation: class MemberReviewRound: votes: list["MemberVote"] complete: bool = True + recording_failed: bool = False def _elapsed_ms(start: float) -> float: @@ -1883,10 +1884,12 @@ async def _commit_parallel_initial_review( review_threshold: str | None, enable_debate: bool, request_type: str, - ) -> tuple[Any, MemberReviewRound, IntentWorkflow | 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, MemberReviewRound, IntentWorkflow | None, float, float]: + async def _commit() -> tuple[ + Any, MemberReviewRound, IntentWorkflow | None, bool, float, float + ]: async with self._submit_lock: submit_started = time.perf_counter() result = await asyncio.to_thread( @@ -1899,22 +1902,15 @@ async def _commit() -> tuple[Any, MemberReviewRound, IntentWorkflow | None, floa initial_round = MemberReviewRound([]) workflow = result.workflow + review_succeeded = True tally_ms = 0.0 if result.success: tally_started = time.perf_counter() try: - initial_round = self._record_agent_votes( - intent, evaluations, finalize=False + initial_round = self._record_agent_votes(intent, evaluations) + workflow, review_succeeded = self._finalize_review_round( + intent, initial_round, workflow, allow_debate=enable_debate ) - if initial_round.complete: - workflow = ( - self._council.finalize_intent_review( - intent.intent_id, - allow_pending=enable_debate - and not self._all_agree(initial_round.votes), - ).workflow - or workflow - ) except BaseException as exc: # BaseException, not Exception: once submit_intent has # consumed the preflight, created the workflow and opened @@ -1980,7 +1976,7 @@ async def _commit() -> tuple[Any, MemberReviewRound, IntentWorkflow | None, floa raise tally_ms = _elapsed_ms(tally_started) - return result, initial_round, 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) @@ -1996,31 +1992,59 @@ async def _collect_review_outcome( ) -> 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) - initial_round = self._record_agent_votes(intent, evaluations, finalize=False) - if initial_round.complete: - workflow = ( - self._council.finalize_intent_review( - intent.intent_id, - allow_pending=enable_debate and not self._all_agree(initial_round.votes), - ).workflow - or 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, 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.""" + if not review_round.recording_failed: + 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 = result.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 + async def _continue_review_outcome( self, intent: Intent, initial_round: MemberReviewRound, workflow: IntentWorkflow | None, *, + review_succeeded: bool, enable_debate: bool, max_debate_rounds: int, actor_timings: list[dict[str, Any]] | None = None, @@ -2028,7 +2052,6 @@ async def _continue_review_outcome( """Continue from an already-recorded initial round into dependent debate rounds.""" votes = initial_round.votes - review_complete = initial_round.complete debate_history = [DebateRound(round_number=0, votes=list(votes))] debate_rounds_completed = 0 @@ -2038,7 +2061,8 @@ async def _continue_review_outcome( if ( enable_debate - and review_complete + and review_succeeded + and initial_round.complete and votes and workflow is not None and workflow.state == WorkflowState.AWAITING_APPROVAL @@ -2054,33 +2078,27 @@ async def _continue_review_outcome( intent, votes, round_num, - finalize=False, actor_timings=actor_timings, ) votes = debate_round.votes - review_complete = debate_round.complete debate_history.append(DebateRound(round_number=round_num, votes=list(votes))) - if not review_complete: - break - workflow = ( - self._council.finalize_intent_review( - intent.intent_id, - allow_pending=round_num < bounded_rounds and not self._all_agree(votes), - ).workflow - or workflow + 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.state != WorkflowState.AWAITING_APPROVAL: + 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, + workflow.state.value if workflow is not None else "unknown", ) break # Keep the result of this request even if terminal cache entries are evicted. - return votes, debate_history, debate_rounds_completed, workflow, review_complete + return votes, debate_history, debate_rounds_completed, workflow, review_succeeded def _record_consolidated_review( self, @@ -2655,7 +2673,8 @@ async def propose_intent( self._chairman and self._settings.chairman.parallel_member_evaluation ) initial_round = MemberReviewRound([]) - initial_workflow: Any | None = None + initial_workflow: IntentWorkflow | None = None + initial_review_succeeded = True deferred_cancellation = False # Chairman decides threshold (if configured) @@ -2704,6 +2723,7 @@ async def propose_intent( result, _, _, + _, submit_ms, tally_ms, deferred_cancellation, @@ -2797,6 +2817,7 @@ async def propose_intent( result, initial_round, initial_workflow, + initial_review_succeeded, submit_ms, tally_ms, deferred_cancellation, @@ -2915,12 +2936,12 @@ async def propose_intent( if parallel_enabled: review_continuation_started = time.perf_counter() - if not initial_round.complete or ( + if not initial_review_succeeded or ( initial_workflow is not None and initial_workflow.state != WorkflowState.AWAITING_APPROVAL ): votes = initial_round.votes - review_complete = initial_round.complete + review_succeeded = initial_review_succeeded debate_history = [DebateRound(round_number=0, votes=list(votes))] debate_rounds_completed = 0 reviewed_workflow = initial_workflow @@ -2931,6 +2952,7 @@ async def propose_intent( intent, initial_round, initial_workflow, + review_succeeded=initial_review_succeeded, enable_debate=enable_debate, max_debate_rounds=max_debate_rounds, actor_timings=actors, @@ -2942,7 +2964,7 @@ async def propose_intent( debate_history, debate_rounds_completed, reviewed_workflow, - review_complete, + review_succeeded, ) = continuation deferred_cancellation = deferred_cancellation or continuation_cancelled stages["review_collect"] = stages.get("member_evaluation", 0.0) + _elapsed_ms( @@ -2955,7 +2977,7 @@ async def propose_intent( debate_history, debate_rounds_completed, reviewed_workflow, - review_complete, + review_succeeded, ) = await self._collect_review_outcome( intent, workflow=result.workflow, @@ -2965,7 +2987,7 @@ async def propose_intent( ) _stage(stages, tool, "review_collect", stage_start, intent_id=intent.intent_id) state = reviewed_workflow.state if reviewed_workflow is not None else None - if not review_complete: + if not review_succeeded: state = WorkflowState.FAILED state_value = state.value if state else "unknown" @@ -3025,7 +3047,10 @@ 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).votes + 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, @@ -3092,51 +3117,49 @@ def _record_agent_votes( self, intent: Intent, evaluations: list[PendingMemberEvaluation], - *, - finalize: bool = False, ) -> MemberReviewRound: """Cast buffered member evaluations in configured member order.""" votes: list[MemberVote] = [] - complete = all(item.evaluation is not None for item in evaluations) + recording_failed = False for pending in evaluations: agent = pending.agent eval_result = pending.evaluation if eval_result is None: 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, - ) - ) - # 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 and complete, + finalize=False, ) if not vote_result.success: + recording_failed = True logger.warning( "Vote cast failed for %s on %s: %s", agent.member_id, 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, + ) + ) - if not complete: - self._council.abort_intent_review(intent.intent_id, _REVIEW_FAILED_MESSAGE) - return MemberReviewRound(votes, complete) + return MemberReviewRound(votes, len(votes) == len(evaluations), recording_failed) @staticmethod def _all_agree(votes: list[MemberVote]) -> bool: @@ -3172,7 +3195,6 @@ async def _run_debate_round( previous_votes: list[MemberVote], round_number: int, *, - finalize: bool = True, actor_timings: list[dict[str, Any]] | None = None, ) -> MemberReviewRound: """Run a debate round where each member re-evaluates using its own backend. @@ -3194,7 +3216,7 @@ async def _run_debate_round( ) new_votes: list[MemberVote] = [] - complete = all(item.evaluation is not None for item in evaluations) + recording_failed = False for pending in evaluations: agent, eval_result = pending.agent, pending.evaluation if eval_result is None: @@ -3205,20 +3227,6 @@ async def _run_debate_round( and previous_decisions[agent.member_id] != eval_result.decision ) - 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, - ) - ) # Record the revised vote in the council and ledger vote_result = self._council.revise_vote( intent.intent_id, @@ -3226,19 +3234,34 @@ async def _run_debate_round( vote_type_str=eval_result.decision, reason=eval_result.reasoning, debate_round=round_number, - finalize=finalize and complete, + finalize=False, ) if not vote_result.success: + recording_failed = True logger.warning( "Debate vote failed for %s on %s: %s", agent.member_id, intent.intent_id, vote_result.error, ) + continue + + 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, + ) + ) - if not complete: - self._council.abort_intent_review(intent.intent_id, _REVIEW_FAILED_MESSAGE) - return MemberReviewRound(new_votes, complete) + return MemberReviewRound(new_votes, len(new_votes) == len(evaluations), recording_failed) def check_intent_status(self, input_data: IntentStatusInput) -> IntentStatusOutput: """Check the current status of an intent.""" @@ -3548,7 +3571,8 @@ async def authorize( self._chairman and self._settings.chairman.parallel_member_evaluation ) initial_round = MemberReviewRound([]) - initial_workflow: Any | None = None + initial_workflow: IntentWorkflow | None = None + initial_review_succeeded = True deferred_cancellation = False # 4. Chairman pre-auth (if configured and agent is authenticated) @@ -3597,6 +3621,7 @@ async def authorize( result, _, _, + _, submit_ms, tally_ms, deferred_cancellation, @@ -3741,6 +3766,7 @@ def chairman_authorizes(decision: Any) -> bool: result, initial_round, initial_workflow, + initial_review_succeeded, submit_ms, tally_ms, deferred_cancellation, @@ -3940,12 +3966,12 @@ def chairman_authorizes(decision: Any) -> bool: if parallel_enabled: review_continuation_started = time.perf_counter() - if not initial_round.complete or ( + if not initial_review_succeeded or ( initial_workflow is not None and initial_workflow.state != WorkflowState.AWAITING_APPROVAL ): votes = initial_round.votes - review_complete = initial_round.complete + review_succeeded = initial_review_succeeded debate_history = [DebateRound(round_number=0, votes=list(votes))] debate_rounds_completed = 0 reviewed_workflow = initial_workflow @@ -3956,6 +3982,7 @@ def chairman_authorizes(decision: Any) -> bool: intent, initial_round, initial_workflow, + review_succeeded=initial_review_succeeded, enable_debate=enable_debate, max_debate_rounds=max_debate_rounds, actor_timings=actors, @@ -3967,7 +3994,7 @@ def chairman_authorizes(decision: Any) -> bool: debate_history, debate_rounds_completed, reviewed_workflow, - review_complete, + review_succeeded, ) = continuation deferred_cancellation = deferred_cancellation or continuation_cancelled stages["review_collect"] = stages.get("member_evaluation", 0.0) + _elapsed_ms( @@ -3980,7 +4007,7 @@ def chairman_authorizes(decision: Any) -> bool: debate_history, debate_rounds_completed, reviewed_workflow, - review_complete, + review_succeeded, ) = await self._collect_review_outcome( intent, workflow=result.workflow, @@ -3990,7 +4017,7 @@ def chairman_authorizes(decision: Any) -> bool: ) _stage(stages, tool, "review_collect", stage_start, intent_id=intent.intent_id) state = reviewed_workflow.state if reviewed_workflow is not None else None - if not review_complete: + if not review_succeeded: state = WorkflowState.FAILED if state == WorkflowState.FAILED: self._record_consolidated_review( diff --git a/tests/test_parallel_council_review.py b/tests/test_parallel_council_review.py index 0d190b36..cd9bf885 100644 --- a/tests/test_parallel_council_review.py +++ b/tests/test_parallel_council_review.py @@ -126,12 +126,44 @@ def _approval(decision: str = "approve") -> IntentEvaluation: @pytest.mark.parametrize("parallel", [False, True]) @pytest.mark.parametrize("failure", ["timeout", "malformed"]) @pytest.mark.parametrize("consolidated", [False, True]) -async def test_authorize_incomplete_member_review_is_not_a_vote( - parallel, failure, consolidated, tmp_path, caplog, monkeypatch +@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" @@ -146,29 +178,45 @@ async def complete(self, messages, **kwargs): return LLMResponse(content='{"reasoning": "private fixture response"}', model="fixture") async def chairman(_intent: Intent) -> ChairmanDecision: - return ChairmanDecision(threshold="quorum") + 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())) + _add_member( + service, "m1", lambda _intent: asyncio.sleep(0, result=_approval(peer_decisions[0])) + ) _add_member(service, "m2", reviewer.evaluate_intent) - _add_member(service, "m3", lambda _intent: asyncio.sleep(0, result=_approval())) + _add_member( + service, "m3", lambda _intent: asyncio.sleep(0, result=_approval(peer_decisions[1])) + ) service._chairman = FakeChairman(chairman) # type: ignore[assignment] - result = await service.authorize(AuthorizeInput(**_proposal("incomplete").model_dump())) - - assert result.status == "error" - assert result.model_dump()["error_code"] == "review_failed" - assert result.writ is None + proposal = _proposal("incomplete") + failed = expected == "failed" + if tool == "authorize": + result = await service.authorize(AuthorizeInput(**proposal.model_dump())) + 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"} - assert service.council.get_workflow(result.decision_id).state.value == "failed" - assert service.council.get_active_workflows() == [] + 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" + assert latency[-1]["outcome"] == ("error" if failed else expected) failed_actor = next(actor for actor in latency[-1]["actors"] if actor["member_id"] == "m2") assert (failed_actor["status"], failed_actor["decision"]) == ("error", "") assert marker not in result.model_dump_json() @@ -179,37 +227,48 @@ async def chairman(_intent: Intent) -> ChairmanDecision: 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"]) == ("failed", "aborted") + 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"] == "aborted" - assert decision["deny_weight"] == 0 + assert decision["outcome"] == outcome + assert decision["deny_weight"] == peer_decisions.count("deny") @pytest.mark.asyncio @pytest.mark.parametrize("parallel", [False, True]) -async def test_authorize_failed_debate_preserves_completed_round_and_partial_votes(parallel): - service = _service(parallel=parallel) +@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, 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 == "m3" else "approve") + return _approval("deny" if member_id == "m2" else "approve") if member_id == "m3": raise RuntimeError("failed re-evaluation") - return _approval() + return _approval(second_vote if member_id == "m2" else "approve") async def chairman(_intent: Intent) -> ChairmanDecision: - return ChairmanDecision(threshold="unanimous") + return ChairmanDecision(threshold=threshold) for member_id in calls: _add_member( @@ -221,18 +280,26 @@ async def chairman(_intent: Intent) -> ChairmanDecision: enable_debate=True, ) - assert result.status == "error" - assert result.error_code == "review_failed" - assert result.writ is None - first, partial = result.debate_history - assert (first.round_number, partial.round_number, result.debate_rounds) == (0, 1, 0) - assert {vote.member_id: vote.decision for vote in first.votes} == { + 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": "approve", - "m3": "deny", + "m2": "deny", + "m3": "approve", } - assert {vote.member_id for vote in partial.votes} == {"m1", "m2"} - assert service.council.get_active_workflows() == [] + 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() == [] @@ -481,10 +548,21 @@ async def run(tag): @pytest.mark.asyncio @pytest.mark.parametrize("tool", ["authorize", "propose"]) @pytest.mark.parametrize( - "parallel,phase", [(False, "initial"), (False, "debate"), (True, "debate")] + "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")], ) -async def test_incomplete_review_keeps_outcome_when_workflow_expires(tool, parallel, phase): +@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 @@ -498,8 +576,11 @@ async def reviewer(_intent): attempts += 1 if phase == "debate" and attempts == 1: return _approval("deny") - clock.advance(seconds=2) - raise RuntimeError("review unavailable") + 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") @@ -508,6 +589,16 @@ async def chairman(_intent): _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( @@ -525,17 +616,26 @@ async def chairman(_intent): 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"} + 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 == "intent_review_recorded" + and entry.entry_type.value == audit_type and entry.payload["intent_id"] == intent_id ] - assert (audit["final"]["state"], audit["final"]["decision"]) == ("failed", "aborted") + if consolidated: + assert (audit["final"]["state"], audit["final"]["decision"]) == ("failed", "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 @@ -856,7 +956,7 @@ 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") @@ -880,7 +980,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 From a5fecf88de1534f2c66e051e673676266e88e7f6 Mon Sep 17 00:00:00 2001 From: Hsin Chen Date: Fri, 20 Nov 2026 14:13:45 -0800 Subject: [PATCH 6/6] fix(council): preserve quorum and retry aborted review audits Keep full-round adapter calls compatible, detect undecided expiry at review handoffs, and retry the original aborted audit payload through workflow maintenance. --- nomos/level_4/council/council.py | 9 +- nomos/nat/functions.py | 164 +++++++++++++++---------- tests/level_4/test_council.py | 24 ++++ tests/test_parallel_council_review.py | 165 +++++++++++++++++++++++++- 4 files changed, 292 insertions(+), 70 deletions(-) diff --git a/nomos/level_4/council/council.py b/nomos/level_4/council/council.py index b5187be6..6a766c3e 100644 --- a/nomos/level_4/council/council.py +++ b/nomos/level_4/council/council.py @@ -883,9 +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, partial_voters=partial_voters - ) + 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) diff --git a/nomos/nat/functions.py b/nomos/nat/functions.py index 41135c6e..f933f993 100644 --- a/nomos/nat/functions.py +++ b/nomos/nat/functions.py @@ -167,7 +167,13 @@ class PendingMemberEvaluation: class MemberReviewRound: votes: list["MemberVote"] complete: bool = True - recording_failed: bool = False + + +@dataclass(frozen=True) +class PendingReviewAudit: + workflow: IntentWorkflow + request_type: str + payload: dict[str, Any] | None = None _workflow_request: ContextVar[dict[str, Intent] | None] = ContextVar( @@ -1043,9 +1049,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() @@ -2179,8 +2184,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) @@ -2215,7 +2224,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 @@ -2227,14 +2236,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: @@ -2263,19 +2278,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) @@ -2746,28 +2763,34 @@ def _finalize_review_round( allow_debate: bool, ) -> tuple[IntentWorkflow | None, bool]: """Commit a complete round or a decision supported by a partial quorum.""" - if not review_round.recording_failed: - 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 = result.workflow.state - if result.success and ( - state in (WorkflowState.APPROVED, WorkflowState.DENIED) - or (review_round.complete and state == WorkflowState.AWAITING_APPROVAL) - ): - return workflow, True + 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, @@ -2784,6 +2807,7 @@ async def _continue_review_outcome( 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). @@ -2837,7 +2861,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, @@ -2849,7 +2873,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 — @@ -2861,28 +2885,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 ) @@ -3858,6 +3899,9 @@ async def _propose_intent( 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 @@ -3995,8 +4039,6 @@ def _record_agent_votes( ) -> MemberReviewRound: """Cast buffered member evaluations in configured member order.""" votes: list[MemberVote] = [] - recording_failed = False - for pending in evaluations: agent = pending.agent eval_result = pending.evaluation @@ -4011,7 +4053,6 @@ def _record_agent_votes( finalize=False, ) if not vote_result.success: - recording_failed = True logger.warning( "Vote cast failed for %s on %s: %s", agent.member_id, @@ -4034,7 +4075,7 @@ def _record_agent_votes( ) ) - return MemberReviewRound(votes, len(votes) == len(evaluations), recording_failed) + return MemberReviewRound(votes, len(votes) == len(evaluations)) @staticmethod def _all_agree(votes: list[MemberVote]) -> bool: @@ -4091,7 +4132,6 @@ async def _run_debate_round( ) new_votes: list[MemberVote] = [] - recording_failed = False for pending in evaluations: agent, eval_result = pending.agent, pending.evaluation if eval_result is None: @@ -4112,7 +4152,6 @@ async def _run_debate_round( finalize=False, ) if not vote_result.success: - recording_failed = True logger.warning( "Debate vote failed for %s on %s: %s", agent.member_id, @@ -4136,7 +4175,7 @@ async def _run_debate_round( ) ) - return MemberReviewRound(new_votes, len(new_votes) == len(evaluations), recording_failed) + return MemberReviewRound(new_votes, len(new_votes) == len(evaluations)) async def check_intent_status_async(self, input_data: IntentStatusInput) -> IntentStatusOutput: read_error = "" @@ -5027,6 +5066,9 @@ def chairman_authorizes(decision: Any) -> bool: 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 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_parallel_council_review.py b/tests/test_parallel_council_review.py index 7d250f39..9289a36a 100644 --- a/tests/test_parallel_council_review.py +++ b/tests/test_parallel_council_review.py @@ -124,7 +124,7 @@ def _approval(decision: str = "approve") -> IntentEvaluation: @pytest.mark.asyncio @pytest.mark.parametrize("parallel", [False, True]) -@pytest.mark.parametrize("failure", ["timeout", "malformed"]) +@pytest.mark.parametrize("failure", ["timeout", "malformed", "rejected_ballot"]) @pytest.mark.parametrize("consolidated", [False, True]) @pytest.mark.parametrize("tool", ["authorize", "propose"]) @pytest.mark.parametrize( @@ -188,7 +188,18 @@ async def chairman(_intent: Intent) -> ChairmanDecision: _add_member( service, "m1", lambda _intent: asyncio.sleep(0, result=_approval(peer_decisions[0])) ) - _add_member(service, "m2", reviewer.evaluate_intent) + 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])) ) @@ -217,8 +228,11 @@ async def chairman(_intent: Intent) -> ChairmanDecision: assert service.council._submission_preflights == {} assert service.council._quorum_manager.get_pending_votes() == [] assert latency[-1]["outcome"] == ("error" if failed else expected) - failed_actor = next(actor for actor in latency[-1]["actors"] if actor["member_id"] == "m2") - assert (failed_actor["status"], failed_actor["decision"]) == ("error", "") + 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 @@ -245,6 +259,7 @@ async def chairman(_intent: Intent) -> ChairmanDecision: @pytest.mark.asyncio @pytest.mark.parametrize("parallel", [False, True]) +@pytest.mark.parametrize("failure", ["inference", "rejected_ballot"]) @pytest.mark.parametrize( "threshold,second_vote,expected", [ @@ -254,7 +269,7 @@ async def chairman(_intent: Intent) -> ChairmanDecision: ], ) async def test_partial_debate_counts_current_round_votes_only( - parallel, threshold, second_vote, expected, tmp_path + 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")} @@ -264,7 +279,9 @@ async def member(_intent: Intent, member_id: str) -> IntentEvaluation: if calls[member_id] == 1: return _approval("deny" if member_id == "m2" else "approve") if member_id == "m3": - raise RuntimeError("failed re-evaluation") + 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: @@ -543,6 +560,142 @@ async def run(tag): 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()), + 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()), 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(