diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.yml index de61a811..daddf77d 100644 --- a/.github/workflows/python-tests.yml +++ b/.github/workflows/python-tests.yml @@ -109,6 +109,7 @@ jobs: uv run --no-project --with ./extras/chronicle-client --with pytest + --with pytest-asyncio pytest extras/chronicle-client/tests -q backend-unit: diff --git a/backend/src/backend/config_loader.py b/backend/src/backend/config_loader.py index 50bf3a38..33b78fc4 100644 --- a/backend/src/backend/config_loader.py +++ b/backend/src/backend/config_loader.py @@ -11,10 +11,27 @@ from pathlib import Path from typing import Optional -from omegaconf import DictConfig, OmegaConf +from omegaconf import DictConfig, ListConfig, OmegaConf logger = logging.getLogger(__name__) + +class ConfigSaveError(RuntimeError): + """A runtime settings change could not be written to config.yml.""" + + +def _save_failure(what: str, config_path: Path, error: Exception) -> ConfigSaveError: + if isinstance(error, OSError) and error.errno == 30: # EROFS + reason = ( + f"{config_path} is read-only. In Kubernetes it is usually mounted from a " + "ConfigMap; edit that ConfigMap (or give the config directory writable " + "storage) instead of using the Settings page." + ) + else: + reason = f"{type(error).__name__}: {error}" + return ConfigSaveError(f"Could not save {what}: {reason}") + + # Global config cache _config_cache: Optional[DictConfig] = None _config_warnings: tuple[str, ...] = () @@ -250,8 +267,9 @@ def save_config_section(section_path: str, values: dict) -> bool: return True except Exception as e: - logger.error(f"Error saving config section '{section_path}': {e}") - return False + error = _save_failure(f"config section '{section_path}'", config_path, e) + logger.error(str(error)) + raise error from e def _load_raw_config() -> DictConfig: @@ -277,7 +295,15 @@ def get_raw_models() -> list: note it excludes default-only models that live solely in defaults.yml. """ raw = _load_raw_config() - models = raw.get("models", []) or [] + models = raw.get("models") + # A config.yml without a ``models`` key yields None, not a ListConfig, and + # OmegaConf.to_container() rejects plain Python values. + if models is None: + return [] + if not isinstance(models, ListConfig): + raise ValueError( + f"config.yml 'models' must be a list, got {type(models).__name__}" + ) return OmegaConf.to_container(models, resolve=False) @@ -306,5 +332,6 @@ def save_models_list(models: list) -> bool: return True except Exception as e: - logger.error(f"Error saving models list: {e}") - return False + error = _save_failure("the models list", config_path, e) + logger.error(str(error)) + raise error from e diff --git a/backend/src/backend/controllers/queue_controller.py b/backend/src/backend/controllers/queue_controller.py index 9707b2fe..f0000521 100644 --- a/backend/src/backend/controllers/queue_controller.py +++ b/backend/src/backend/controllers/queue_controller.py @@ -18,6 +18,7 @@ from fastapi.responses import JSONResponse from rq import Queue, Retry, Worker +from rq.command import send_stop_job_command from rq.exceptions import NoSuchJobError from rq.job import Dependency, Job, JobStatus from rq.registry import DeferredJobRegistry, ScheduledJobRegistry @@ -927,6 +928,27 @@ def enqueue_explicit_timeline_reconciliation(request_id: str) -> Optional[str]: return job.id +def stop_explicit_timeline_reconciliation(job_id: str) -> str: + """Stop one explicit reconciliation job wherever it is in its lifecycle. + + A running job's work-horse is killed; a queued, scheduled, or retry-deferred job + is cancelled so RQ never starts it. Returns what was done, for the caller's log. + """ + + try: + job = Job.fetch(job_id, connection=redis_conn) + except NoSuchJobError: + return "missing" + status = get_job_status_from_rq(job) + if status == "started": + send_stop_job_command(redis_conn, job_id) + return "stopped" + if status in {"queued", "deferred", "scheduled"}: + job.cancel() + return "cancelled" + return status + + def start_streaming_jobs( session_id: str, user_id: str, diff --git a/backend/src/backend/controllers/system_controller.py b/backend/src/backend/controllers/system_controller.py index 8c62da77..4325890f 100644 --- a/backend/src/backend/controllers/system_controller.py +++ b/backend/src/backend/controllers/system_controller.py @@ -15,7 +15,7 @@ from datetime import UTC, datetime from io import StringIO from pathlib import Path -from typing import Optional +from typing import Any, Optional from urllib.parse import urlparse import httpx @@ -48,6 +48,7 @@ _find_config_path, get_models_registry, load_models_config, + output_token_limit_findings, ) from backend.model_routes import effective_model_routes, effective_operation_routes from backend.models.user import User @@ -176,6 +177,42 @@ def _is_self_hosted_model(model) -> bool: return host.endswith(".ts.net") or "." not in host +def _output_limit_issues(registry: Any) -> list[dict[str, Any]]: + """Report each max_tokens setting its model cannot honour. + + These are errors: the operation refuses to run (see ``OutputLimitExceeded``) + until a larger-output model is chosen or the setting is lowered. + """ + + timeline_pi = (load_config().get("timeline", {}) or {}).get("pi", {}) or {} + extra = [ + ( + "timeline.pi.max_tokens", + str(timeline_pi.get("operation") or "timeline_segmentation"), + timeline_pi.get("max_tokens"), + ) + ] + return [ + { + "component": "Model Limits", + "severity": "error", + "message": ( + f"'{finding['operation']}' needs a model with at least " + f"{finding['requested']} output tokens, but it uses " + f"{finding['model']} ({finding['model_name']}), which accepts at most " + f"{finding['limit']}. It will not run until this is fixed." + ), + "resolution": ( + f"Settings > AI Model Settings: route '{finding['operation']}' to a " + f"model that supports at least {finding['requested']} output " + f"tokens. Or lower {finding['setting']} to {finding['limit']} or " + f"less, if shorter results are acceptable." + ), + } + for finding in output_token_limit_findings(registry, extra) + ] + + async def get_config_diagnostics(): """ Get comprehensive configuration diagnostics. @@ -360,6 +397,13 @@ async def get_config_diagnostics(): } ) + # Listed under issues so the health poller records a System Event. + limit_issues = _output_limit_issues(registry) + if limit_issues: + diagnostics["issues"].extend(limit_issues) + if diagnostics["overall_status"] == "healthy": + diagnostics["overall_status"] = "partial" + else: diagnostics["overall_status"] = "unhealthy" diagnostics["issues"].append( @@ -2679,7 +2723,9 @@ async def create_plugin( if events else '"conversation.complete"' ) - boilerplate = inspect.cleandoc(f''' + boilerplate = ( + inspect.cleandoc( + f''' """ {class_name} implementation. @@ -2716,7 +2762,10 @@ async def cleanup(self): async def on_conversation_complete(self, context: PluginContext) -> Optional[PluginResult]: logger.info(f"Processing conversation for user: {{context.user_id}}") return PluginResult(success=True, message="OK") - ''') + "\n" + ''' + ) + + "\n" + ) (plugin_dir / "plugin.py").write_text(boilerplate, encoding="utf-8") created_files.append("plugin.py") diff --git a/backend/src/backend/middleware/app_middleware.py b/backend/src/backend/middleware/app_middleware.py index 58a4382c..f063c96c 100644 --- a/backend/src/backend/middleware/app_middleware.py +++ b/backend/src/backend/middleware/app_middleware.py @@ -17,6 +17,8 @@ from starlette.responses import Response from backend.app_config import get_app_config +from backend.config_loader import ConfigSaveError +from backend.model_registry import MissingModelCredentialsError logger = logging.getLogger(__name__) request_logger = logging.getLogger("api.requests") @@ -225,6 +227,32 @@ async def connection_exception_handler(request: Request, exc: ConnectionError): }, ) + @app.exception_handler(ConfigSaveError) + async def config_save_exception_handler(request: Request, exc: ConfigSaveError): + """A settings write failed; tell the caller why instead of a bare 500.""" + return JSONResponse( + status_code=500, + content={ + "detail": str(exc), + "error_type": "config_save_failure", + "error_category": "configuration", + }, + ) + + @app.exception_handler(MissingModelCredentialsError) + async def missing_credentials_exception_handler( + request: Request, exc: MissingModelCredentialsError + ): + """An LLM call was attempted against a hosted model with no API key.""" + return JSONResponse( + status_code=503, + content={ + "detail": str(exc), + "error_type": "missing_model_credentials", + "error_category": "configuration", + }, + ) + @app.exception_handler(HTTPException) async def http_exception_handler(request: Request, exc: HTTPException): """Handle HTTP exceptions with structured error response.""" diff --git a/backend/src/backend/model_registry.py b/backend/src/backend/model_registry.py index 9b8ff584..90d7ea60 100644 --- a/backend/src/backend/model_registry.py +++ b/backend/src/backend/model_registry.py @@ -34,6 +34,37 @@ logger = logging.getLogger(__name__) + +class MissingModelCredentialsError(RuntimeError): + """A hosted model was selected but its API key is not configured.""" + + +def require_api_key( + api_key: Optional[str], + url: str, + model_name: str, + *, + operation: Optional[str] = None, +) -> str: + """Return ``api_key``, or raise when a hosted HTTPS endpoint has none. + + Local servers (llama.cpp, Ollama, Tailnet ASR) declare a placeholder such as + ``no-key``. A key that resolved to empty for an HTTPS URL means a hosted + provider whose environment variable is unset; calling it would only fail + later as an opaque 401 inside a background job. + """ + if api_key: + return api_key + if url.startswith("https://"): + used_by = f" (used by LLM operation '{operation}')" if operation else "" + raise MissingModelCredentialsError( + f"Model '{model_name}'{used_by} calls {url} but its api_key is empty. " + "Set the environment variable its api_key references in config, " + "or select a different model in Settings > AI Model Settings." + ) + return "" + + # Operations whose normal routing role is not the primary LLM. Keeping this policy # beside the resolver makes the effective route inspectable without teaching every # caller or diagnostic which default it should use. @@ -150,6 +181,17 @@ def reasoning_allowed(self) -> bool: embedding_dimensions: Optional[int] = Field( default=None, ge=1, description="Embedding vector dimensions" ) + max_output_tokens: Optional[int] = Field( + default=None, + ge=1, + description=( + "Largest completion the provider accepts for this model. A request for " + "more is rejected outright (OpenAI returns HTTP 400), so every requested " + "max_tokens is fitted to this value. Unset means unknown: requests pass " + "through unchanged, which is the right default for local servers whose " + "only limit is their context window." + ), + ) operations: Dict[str, Any] = Field( default_factory=dict, description="API operation definitions" ) @@ -254,6 +296,12 @@ def resolved_url(self) -> str: return _with_scheme(discovered) return _with_scheme(self.discovery_default or "") + def require_api_key(self, operation: Optional[str] = None) -> str: + """Return the API key, or raise when a hosted endpoint has none.""" + return require_api_key( + self.api_key, self.resolved_url(), self.name, operation=operation + ) + @model_validator(mode="after") def validate_model(self) -> ModelDef: """Cross-field validation.""" @@ -287,6 +335,94 @@ def validate_model(self) -> ModelDef: return self +class OutputLimitExceeded(ValueError): + """A configured max_tokens is larger than the routed model can produce. + + Raised before any request is sent. Silently shrinking the allowance would run the + operation with less room than it was tuned for (a long timeline day is cut off + before its last episodes), so the operator is told to choose a bigger model. + """ + + def __init__(self, *, setting: str, model: str, requested: int, limit: int): + self.setting = setting + self.model = model + self.requested = requested + self.limit = limit + super().__init__( + f"{setting} needs {requested} output tokens, but model '{model}' accepts " + f"at most {limit}. Choose a model that supports at least {requested} " + f"output tokens for this operation (Settings > AI Model Settings), or " + f"lower {setting}." + ) + + +def check_output_tokens(model_def: Any, requested: int, *, setting: str) -> int: + """Return ``requested`` if the model can produce it; raise otherwise.""" + + # Test fakes and extra-field model entries share this path with ModelDef, the + # same way callers already read ``context_window``. + return check_output_limit( + getattr(model_def, "max_output_tokens", None), + requested, + setting=setting, + model=str(model_def.name), + ) + + +def check_output_limit( + limit: Optional[int], requested: int, *, setting: str, model: str +) -> int: + """Core of :func:`check_output_tokens` for callers holding only the limit. + + An undeclared limit means unknown, so the request passes through unchanged. + """ + + if limit is not None and requested > limit: + raise OutputLimitExceeded( + setting=setting, model=model, requested=int(requested), limit=int(limit) + ) + return requested + + +def output_token_limit_findings( + registry: "AppModels", + extra_settings: Optional[List[tuple[str, str, Any]]] = None, +) -> List[Dict[str, Any]]: + """List every configured ``max_tokens`` larger than its model accepts. + + Checks each ``llm_operations`` entry against the model it routes to, plus + ``extra_settings``: ``(setting_path, operation_name, requested)`` triples for + feature settings that override an operation's limit (``timeline.pi.max_tokens``). + """ + + candidates: List[tuple[str, str, Any]] = [] + for name, op_config in registry.llm_operations.items(): + if op_config.max_tokens is not None: + candidates.append( + (f"llm_operations.{name}.max_tokens", name, op_config.max_tokens) + ) + candidates.extend(extra_settings or []) + + findings: List[Dict[str, Any]] = [] + for setting, operation, requested in candidates: + if requested in (None, "") or isinstance(requested, bool): + continue + model_def = registry.resolve_operation_model(operation) + limit = model_def.max_output_tokens + if limit is not None and int(requested) > limit: + findings.append( + { + "setting": setting, + "operation": operation, + "model": model_def.name, + "model_name": model_def.model_name, + "requested": int(requested), + "limit": limit, + } + ) + return findings + + class LLMOperationConfig(BaseModel): """Per-operation LLM config as written in YAML. @@ -319,6 +455,7 @@ class ResolvedLLMOperation(BaseModel): max_tokens: Optional[int] = None response_format: Optional[Dict[str, Any]] = None # {"type": "json_object"} or None reasoning_effort: Optional[str] = None # OpenAI reasoning models OR thinking models + operation: Optional[str] = None # llm_operations name, for actionable errors @property def reasoning_allowed(self) -> bool: @@ -433,7 +570,7 @@ def get_client(self, is_async: bool = False): Uses create_openai_client which handles Langfuse tracing. """ return create_openai_client( - api_key=self.model_def.api_key or "", + api_key=self.model_def.require_api_key(self.operation), base_url=self.model_def.resolved_url(), is_async=is_async, ) @@ -526,28 +663,13 @@ def list_model_types(self) -> List[str]: """ return sorted(set(m.model_type for m in self.models.values())) - def get_llm_operation( - self, - name: str, - *, - model_override: Optional[str] = None, - ) -> ResolvedLLMOperation: - """Resolve a named LLM operation to a self-contained config. - - Resolution: - 1. Look up llm_operations[name] (empty LLMOperationConfig if missing) - 2. Resolve model_def: model_override → get_by_name, else op.model → - get_by_name, else the operation's centrally defined default role - 3. Merge parameters: operation > model_def.model_params > safe fallback - 4. Return ResolvedLLMOperation ready for use + def resolve_operation_model( + self, name: str, *, model_override: Optional[str] = None + ) -> ModelDef: + """Return the model an operation routes to, without validating its settings. - Args: - name: Operation name (e.g. "memory_extraction", "chat") - model_override: pin a specific model by name, overriding both the - operation's model and the defaults (used for fallback retries). - - Returns: - ResolvedLLMOperation with model_def, temperature, max_tokens, response_format + Diagnostics and route explanations use this so a misconfigured operation can + still be reported; :meth:`get_llm_operation` adds the settings checks. Raises: RuntimeError: If no model can be resolved for the operation @@ -555,7 +677,6 @@ def get_llm_operation( op_config = self.llm_operations.get(name, LLMOperationConfig()) default_role = self.llm_operation_role(name) - # Resolve model definition if model_override: model_def = self.get_by_name(model_override) if not model_def: @@ -578,6 +699,37 @@ def get_llm_operation( raise RuntimeError( f"No model specified for operation '{name}' and no default LLM defined" ) + return model_def + + def get_llm_operation( + self, + name: str, + *, + model_override: Optional[str] = None, + ) -> ResolvedLLMOperation: + """Resolve a named LLM operation to a self-contained config. + + Resolution: + 1. Look up llm_operations[name] (empty LLMOperationConfig if missing) + 2. Resolve model_def: model_override → get_by_name, else op.model → + get_by_name, else the operation's centrally defined default role + 3. Merge parameters: operation > model_def.model_params > safe fallback + 4. Return ResolvedLLMOperation ready for use + + Args: + name: Operation name (e.g. "memory_extraction", "chat") + model_override: pin a specific model by name, overriding both the + operation's model and the defaults (used for fallback retries). + + Returns: + ResolvedLLMOperation with model_def, temperature, max_tokens, response_format + + Raises: + RuntimeError: If no model can be resolved for the operation + OutputLimitExceeded: If max_tokens is larger than the model can produce + """ + op_config = self.llm_operations.get(name, LLMOperationConfig()) + model_def = self.resolve_operation_model(name, model_override=model_override) # Merge parameters: operation config > model_params > safe fallback model_params = model_def.model_params or {} @@ -603,12 +755,21 @@ def get_llm_operation( if op_config.response_format == "json": response_format = {"type": "json_object"} + if max_tokens is not None: + source = ( + f"llm_operations.{name}.max_tokens" + if op_config.max_tokens is not None + else f"models.{model_def.name}.model_params.max_tokens" + ) + max_tokens = check_output_tokens(model_def, int(max_tokens), setting=source) + return ResolvedLLMOperation( model_def=model_def, temperature=float(temperature), max_tokens=int(max_tokens) if max_tokens is not None else None, response_format=response_format, reasoning_effort=reasoning_effort, + operation=name, ) def explain_llm_operation(self, name: str) -> Dict[str, Optional[str]]: @@ -620,11 +781,11 @@ def explain_llm_operation(self, name: str) -> Dict[str, Optional[str]]: else: role = self.llm_operation_role(name) source = f"defaults.{role}" - resolved = self.get_llm_operation(name) + model_def = self.resolve_operation_model(name) return { - "model": resolved.model_def.name, - "model_name": resolved.model_name, - "provider": resolved.model_def.model_provider, + "model": model_def.name, + "model_name": model_def.model_name, + "provider": model_def.model_provider, "role": role, "source": source, } diff --git a/backend/src/backend/models/timeline.py b/backend/src/backend/models/timeline.py index f94b6a12..37b86bfd 100644 --- a/backend/src/backend/models/timeline.py +++ b/backend/src/backend/models/timeline.py @@ -534,10 +534,19 @@ class DirtyEvidenceRangeResolution(BaseModel): """Append-only human resolution of one terminal reconciliation range.""" resolution_id: str = Field(default_factory=lambda: str(uuid.uuid4())) - action: Literal["dismissed"] = "dismissed" + action: Literal["dismissed", "cancelled"] = "dismissed" actor_user_id: str = Field(min_length=1) reason: str = Field(min_length=1, max_length=500) - prior_state: Literal["failed"] = "failed" + # A cancel can stop a range at any non-terminal stage, not only after failure. + prior_state: Literal[ + "failed", + "pending", + "authorized_pending", + "leased", + "waiting", + "awaiting_context", + "context_pending", + ] = "failed" created_at: datetime = Field(default_factory=utcnow) @@ -768,7 +777,7 @@ class TimelineReconciliationRequest(Document): user_id: str local_date: date timezone: str - state: Literal["blocked", "queued", "running", "completed", "failed"] + state: Literal["blocked", "queued", "running", "completed", "failed", "cancelled"] reason: Literal[ "assets_on_day", "later_asset_watermark", diff --git a/backend/src/backend/routers/modules/timeline_routes.py b/backend/src/backend/routers/modules/timeline_routes.py index 6f8dcf16..a9228dc3 100644 --- a/backend/src/backend/routers/modules/timeline_routes.py +++ b/backend/src/backend/routers/modules/timeline_routes.py @@ -19,6 +19,7 @@ import backend.services.privacy as privacy import backend.services.timeline.memory_sources as memory_sources from backend.auth import current_active_user +from backend.model_registry import OutputLimitExceeded from backend.models.audio_chunk import AudioChunkDocument from backend.models.conversation import Conversation from backend.models.notification import NotificationIntent @@ -61,6 +62,7 @@ ) from backend.services.timeline.dirty_ranges import ( DirtyRangeDismissalError, + DirtyRangeLeaseLost, dismiss_failed_range, ) from backend.services.timeline.dispatch import enqueue_episode_detailed_summary @@ -73,7 +75,12 @@ EvidenceRelationPreview, infer_evidence_relations, ) +from backend.services.timeline.executor import ( + check_output_limits as check_timeline_output_limits, +) from backend.services.timeline.explicit_reconciliation import ( + ReconciliationNotCancellable, + cancel_explicit_reconciliation, reconciliation_request_payload, request_explicit_reconciliation, ) @@ -551,6 +558,10 @@ async def reconcile_timeline_day( user: User = Depends(current_active_user), ): timezone = _validate_timezone(body.timezone) + try: + check_timeline_output_limits() + except OutputLimitExceeded as error: + raise HTTPException(status_code=409, detail=str(error)) from error try: request, created = await request_explicit_reconciliation( user=user, @@ -563,6 +574,20 @@ async def reconcile_timeline_day( return {**reconciliation_request_payload(request), "created": created} +@router.post("/reconciliation/{request_id}/cancel") +async def cancel_reconciliation_request( + request_id: str, + user: User = Depends(current_active_user), +): + try: + request = await cancel_explicit_reconciliation(user=user, request_id=request_id) + except LookupError as error: + raise HTTPException(status_code=404, detail=str(error)) from error + except (ReconciliationNotCancellable, DirtyRangeLeaseLost) as error: + raise HTTPException(status_code=409, detail=str(error)) from error + return reconciliation_request_payload(request) + + @router.get("/reconciliation/{request_id}") async def get_reconciliation_request( request_id: str, diff --git a/backend/src/backend/services/immich_discovery.py b/backend/src/backend/services/immich_discovery.py index 2003a934..95cbcf5e 100644 --- a/backend/src/backend/services/immich_discovery.py +++ b/backend/src/backend/services/immich_discovery.py @@ -49,6 +49,10 @@ def _settings() -> tuple[str, str] | None: return (url, key) if url and key else None +def immich_configured() -> bool: + return _settings() is not None + + async def resolve_immich_user_id() -> str | None: """Chronicle user that owns imported Immich references. @@ -146,7 +150,8 @@ async def check_immich_day_readiness( checked_at = utcnow() settings = _settings() if settings is None: - return ImmichDayReadiness(False, "immich_unconfigured", 0, None, checked_at, []) + # Immich is optional. A deployment without it has no backup to wait for. + return ImmichDayReadiness(True, "immich_unconfigured", 0, None, checked_at, []) try: zone = ZoneInfo(timezone_name) except Exception as error: diff --git a/backend/src/backend/services/memory/agent/operating_memory_optimizer.py b/backend/src/backend/services/memory/agent/operating_memory_optimizer.py index 673f74b4..739eb3a4 100644 --- a/backend/src/backend/services/memory/agent/operating_memory_optimizer.py +++ b/backend/src/backend/services/memory/agent/operating_memory_optimizer.py @@ -10,6 +10,7 @@ from typing import Any from backend.config_loader import load_config +from backend.model_registry import check_output_limit from backend.services.inference_artifacts import ( canonical_hash, load_inference_runs, @@ -108,8 +109,11 @@ def _optimizer_runtime_config(config: Any) -> Any: """Give the meta-optimizer room to reason and still emit its tool call.""" values = dict(vars(config)) - values["max_tokens"] = max( - _OPTIMIZER_MIN_MAX_TOKENS, int(values.get("max_tokens") or 0) + values["max_tokens"] = check_output_limit( + values.get("max_output_tokens"), + max(_OPTIMIZER_MIN_MAX_TOKENS, int(values.get("max_tokens") or 0)), + setting="operating_memory optimizer minimum max_tokens", + model=str(values.get("model_entry") or values.get("model") or ""), ) return type(config)(**values) diff --git a/backend/src/backend/services/memory/agent/pi_agent.py b/backend/src/backend/services/memory/agent/pi_agent.py index dc7f82a0..c4f79949 100644 --- a/backend/src/backend/services/memory/agent/pi_agent.py +++ b/backend/src/backend/services/memory/agent/pi_agent.py @@ -26,7 +26,13 @@ from urllib.parse import unquote, urlsplit import backend.services.privacy as privacy -from backend.model_registry import AppModels, ResolvedLLMOperation, get_models_registry +from backend.model_registry import ( + AppModels, + ResolvedLLMOperation, + check_output_tokens, + get_models_registry, + require_api_key, +) from backend.services.inference_artifacts import canonical_hash, persist_inference_run from ..session_write import WriteSourcePermissions @@ -202,6 +208,10 @@ class _PiRuntimeConfig: system_prompt_prefix: str = "" compat: Dict[str, Any] = field(default_factory=dict) reasoning_allowed: bool = False + # The model's declared completion cap, kept so a later per-feature override of + # max_tokens (timeline.pi.max_tokens) is checked against the same model. + max_output_tokens: Optional[int] = None + model_entry: str = "" def __post_init__(self) -> None: if not self.reasoning_allowed: @@ -437,6 +447,11 @@ def _resolve_pi_config( name="max_tokens", default=DEFAULT_MAX_TOKENS, ) + # resolved.max_tokens is already checked by the registry; the settings fallback + # and the built-in default are not. + max_tokens = check_output_tokens( + model_def, max_tokens, setting="memory.backends.pi.max_tokens" + ) if max_tokens > context_window - MIN_PROMPT_HEADROOM_TOKENS: raise PiExecutorError( "memory.backends.pi.max_tokens must leave at least " @@ -452,7 +467,10 @@ def _resolve_pi_config( provider=_provider_slug(str(model_def.model_provider)), model=resolved.model_name, base_url=base_url, - api_key=resolved.api_key or "no-key", + api_key=require_api_key( + resolved.api_key, base_url, model_def.name, operation=operation + ) + or "no-key", thinking=_thinking_level(settings.get("thinking"), resolved), max_tokens=max_tokens, context_window=context_window, @@ -463,6 +481,8 @@ def _resolve_pi_config( ), reasoning=bool(model_def.thinking), reasoning_allowed=resolved.reasoning_allowed, + max_output_tokens=getattr(model_def, "max_output_tokens", None), + model_entry=str(model_def.name), temperature=resolved.temperature, sampling={ key: model_params[key] diff --git a/backend/src/backend/services/timeline/dirty_ranges.py b/backend/src/backend/services/timeline/dirty_ranges.py index f03eedfb..e7def028 100644 --- a/backend/src/backend/services/timeline/dirty_ranges.py +++ b/backend/src/backend/services/timeline/dirty_ranges.py @@ -1253,6 +1253,65 @@ async def dismiss_failed_range( ) +CANCELLABLE_RANGE_STATES = ( + "pending", + "authorized_pending", + "leased", + "waiting", + "awaiting_context", + "context_pending", +) + + +async def cancel_range( + dirty_range_id: str, *, user_id: str, reason: str +) -> Optional[DirtyEvidenceRange]: + """Take one owner-scoped, unfinished range out of scheduling. + + Clearing the lease fences a still-running attempt: its next lease-checked write + raises ``DirtyRangeLeaseLost`` instead of publishing. ``dismissed`` keeps the + recovery cron from re-dispatching it. Returns None when the range had already + reached a terminal state, so there was nothing to cancel. + """ + + existing = await DirtyEvidenceRange.find_one( + DirtyEvidenceRange.dirty_range_id == dirty_range_id, + DirtyEvidenceRange.user_id == user_id, + ) + if existing is None: + raise LookupError("reconciliation range not found") + if existing.state not in CANCELLABLE_RANGE_STATES: + return None + resolution = DirtyEvidenceRangeResolution( + action="cancelled", + actor_user_id=user_id, + reason=reason, + prior_state=existing.state, + ) + document = await DirtyEvidenceRange.get_pymongo_collection().find_one_and_update( + { + "dirty_range_id": dirty_range_id, + "user_id": user_id, + "state": existing.state, + }, + { + "$set": { + "state": "dismissed", + "lease_owner": None, + "lease_expires_at": None, + "updated_at": resolution.created_at, + }, + "$push": {"resolution_history": resolution.model_dump(mode="python")}, + }, + return_document=ReturnDocument.AFTER, + ) + if document is None: + raise DirtyRangeLeaseLost( + f"dirty range {dirty_range_id} changed state while being cancelled; retry" + ) + return DirtyEvidenceRange.model_validate(document) + + async def release_range_for_retry( dirty_range: DirtyEvidenceRange, error: str ) -> DirtyEvidenceRange: diff --git a/backend/src/backend/services/timeline/executor.py b/backend/src/backend/services/timeline/executor.py index 4191b32d..26f98a8e 100644 --- a/backend/src/backend/services/timeline/executor.py +++ b/backend/src/backend/services/timeline/executor.py @@ -10,6 +10,11 @@ from omegaconf import OmegaConf from backend.config_loader import load_config +from backend.model_registry import ( + OutputLimitExceeded, + get_models_registry, + output_token_limit_findings, +) from backend.services.job_progress import report_job_progress from .codex_executor import CodexTimelineExecutor @@ -485,6 +490,39 @@ def settings_dict() -> dict[str, Any]: return converted if isinstance(converted, dict) else {} +def check_output_limits() -> None: + """Refuse a timeline run that the configured model cannot complete. + + Called before a day is queued so the person asking sees the model-choice + message at once, rather than a background failure after the run starts. The + executor repeats the check at run time; this is only the early warning. + """ + + settings = settings_dict() + if str(settings.get("executor") or "pi") != "pi": + return # Codex runs on its own subscription model and limits. + registry = get_models_registry() + if registry is None: + return # The run itself raises the precise registry error. + pi = settings.get("pi") or {} + operation = str(pi.get("operation") or "timeline_segmentation") + findings = [ + finding + for finding in output_token_limit_findings( + registry, [("timeline.pi.max_tokens", operation, pi.get("max_tokens"))] + ) + if finding["operation"] == operation + ] + if findings: + finding = findings[0] + raise OutputLimitExceeded( + setting=finding["setting"], + model=finding["model"], + requested=finding["requested"], + limit=finding["limit"], + ) + + def build_executor(): settings = settings_dict() executor = str(settings.get("executor") or "pi") diff --git a/backend/src/backend/services/timeline/explicit_reconciliation.py b/backend/src/backend/services/timeline/explicit_reconciliation.py index 099f5880..1f44c1b8 100644 --- a/backend/src/backend/services/timeline/explicit_reconciliation.py +++ b/backend/src/backend/services/timeline/explicit_reconciliation.py @@ -14,12 +14,16 @@ ) from backend.services.immich_discovery import ( check_immich_day_readiness, + immich_configured, import_immich_day_candidates, resolve_immich_user_id, ) from backend.services.notifications import NotificationCommand, enqueue_notification from backend.services.redis_lock import distributed_lock -from backend.services.timeline.dirty_ranges import authorize_explicit_range +from backend.services.timeline.dirty_ranges import ( + authorize_explicit_range, + cancel_range, +) from backend.users import User # The readiness check can page through several Immich search windows before importing @@ -61,7 +65,7 @@ async def request_explicit_reconciliation( start, _ = day_bounds(local_date, timezone_name) if start >= utcnow(): raise ValueError("Cannot reconcile a future evidence interval") - if not skip_immich: + if not skip_immich and immich_configured(): immich_owner_id = await resolve_immich_user_id() if immich_owner_id != user_id: raise PermissionError( @@ -178,7 +182,8 @@ async def _request_explicit_reconciliation_locked( await request.save() return request, True - if not skip_immich: + # Importing also registers an Immich capture source, so skip it without Immich. + if not skip_immich and readiness.reason != "immich_unconfigured": await import_immich_day_candidates(user_id, readiness.target_assets) started_at, _ = day_bounds(local_date, timezone_name) ended_at = evidence_cutoff(request) @@ -205,6 +210,59 @@ async def _request_explicit_reconciliation_locked( return request, True +class ReconciliationNotCancellable(ValueError): + """The request already finished, so there is nothing to stop.""" + + +CANCELLABLE_REQUEST_STATES = ("queued", "running") + + +async def cancel_explicit_reconciliation( + *, user: User, request_id: str +) -> TimelineReconciliationRequest: + """Stop one queued or running day request so the day can be requested again. + + Order matters: the range is fenced first, so a worker that outlives the stop + command loses its lease rather than publishing; then the RQ job is stopped; the + request is marked last, because a still-active request is what blocks a retry. + """ + + user_id = str(user.id) + request = await TimelineReconciliationRequest.find_one( + TimelineReconciliationRequest.request_id == request_id, + TimelineReconciliationRequest.user_id == user_id, + ) + if request is None: + raise LookupError("Reconciliation request not found") + if request.state not in CANCELLABLE_REQUEST_STATES: + raise ReconciliationNotCancellable( + f"Only a queued or running reconciliation can be cancelled " + f"(state={request.state})" + ) + if request.dirty_range_id: + await cancel_range( + request.dirty_range_id, + user_id=user_id, + reason=f"Cancelled by user (request {request_id})", + ) + if request.job_id: + await asyncio.to_thread(_stop_job, request.job_id) + request.state = "cancelled" + request.last_error = "Cancelled by user" + request.updated_at = utcnow() + await request.save() + return request + + +def _stop_job(job_id: str) -> str: + # Lazy for the same worker-bootstrap reason as _queue_request. + from backend.controllers.queue_controller import ( + stop_explicit_timeline_reconciliation, + ) + + return stop_explicit_timeline_reconciliation(job_id) + + def _queue_request(request_id: str) -> str | None: # Lazy to avoid coupling the Timeline service import graph to worker bootstrap. from backend.controllers.queue_controller import ( diff --git a/backend/src/backend/services/timeline/pi_executor.py b/backend/src/backend/services/timeline/pi_executor.py index b56d9986..126b6516 100644 --- a/backend/src/backend/services/timeline/pi_executor.py +++ b/backend/src/backend/services/timeline/pi_executor.py @@ -19,6 +19,7 @@ import backend.services.timeline.pi_tasks as pi_tasks import backend.services.timeline.prompt as prompt +from backend.model_registry import check_output_limit from backend.services.inference_artifacts import ( invalidate_reusable_result, load_reusable_result, @@ -753,6 +754,16 @@ def _final_stage_config(self, reasoning_effort: str | None) -> Any: raise ValueError( "timeline.pi.max_tokens must be a positive integer" ) from exc + if max_tokens > 0: + # The shipped 32K allowance needs a large-output model. Stop with a + # model-choice message rather than send a request the provider + # rejects, or quietly shrink the room a dense day needs. + max_tokens = check_output_limit( + config.max_output_tokens, + max_tokens, + setting="timeline.pi.max_tokens", + model=config.model_entry, + ) if max_tokens <= 0 or max_tokens > config.context_window - 1024: raise ValueError( "timeline.pi.max_tokens must be positive and leave at least " diff --git a/backend/src/backend/services/transcription/__init__.py b/backend/src/backend/services/transcription/__init__.py index cd9585df..3d4ddce5 100644 --- a/backend/src/backend/services/transcription/__init__.py +++ b/backend/src/backend/services/transcription/__init__.py @@ -944,16 +944,29 @@ async def process_audio_chunk( return None async def end_stream(self, stream_id: str) -> dict: - if stream_id not in self._streams: + # Unregister first so no exit path below can leak the stream entry. + stream = self._streams.pop(stream_id, None) + if stream is None: return {"text": "", "words": [], "segments": []} - ws = self._streams[stream_id]["ws"] + ws = stream["ws"] ops = self.model.operations or {} - pending = self._streams[stream_id].get("pending_audio") - if pending: - await ws.send(bytes(pending)) - pending.clear() + pending = stream.get("pending_audio") end_msg = (ops.get("end", {}) or {}).get("message", {"type": "stop"}) - await ws.send(json.dumps(end_msg)) + try: + if pending: + await ws.send(bytes(pending)) + pending.clear() + await ws.send(json.dumps(end_msg)) + except websockets.exceptions.ConnectionClosed as e: + # The provider already closed the socket, e.g. Deepgram's idle + # timeout (NET-0001) after ~10 s without audio. Finals that arrived + # before the close were already published; nothing is left to flush. + logger.warning( + f"Provider closed stream {stream_id} before it ended " + f"(code={e.rcvd.code if e.rcvd else None}, " + f"reason={e.rcvd.reason if e.rcvd else ''})" + ) + return {"text": "", "words": [], "segments": []} expect = ops.get("expect", {}) or {} final_type = expect.get("final_type") @@ -978,8 +991,6 @@ async def end_stream(self, stream_id: str) -> dict: except Exception: pass - self._streams.pop(stream_id, None) - if not isinstance(final, dict): return {"text": "", "words": [], "segments": []} segments = ( diff --git a/backend/src/backend/workers/timeline_jobs.py b/backend/src/backend/workers/timeline_jobs.py index b343ae8e..f23d8243 100644 --- a/backend/src/backend/workers/timeline_jobs.py +++ b/backend/src/backend/workers/timeline_jobs.py @@ -87,7 +87,7 @@ async def explicit_reconciliation_job(request_id: str, *, redis_client=None) -> request = await TimelineReconciliationRequest.find_one({"request_id": request_id}) if request is None: return {"request_id": request_id, "state": "missing"} - if request.state in {"completed", "failed", "blocked"}: + if request.state in {"completed", "failed", "blocked", "cancelled"}: return {"request_id": request_id, "state": request.state} return await _run_explicit_reconciliation(request) diff --git a/backend/tests/test_explicit_reconciliation.py b/backend/tests/test_explicit_reconciliation.py index eadd14d6..41bf672a 100644 --- a/backend/tests/test_explicit_reconciliation.py +++ b/backend/tests/test_explicit_reconciliation.py @@ -93,7 +93,7 @@ async def test_blocked_request_never_imports_or_queues_work(requests_db, monkeyp explicit_reconciliation, "check_immich_day_readiness", lambda *_args: _async_value( - readiness(ready=False, reason="immich_unconfigured") + readiness(ready=False, reason="immich_unreachable") ), ) imported = queued = 0 @@ -119,11 +119,55 @@ def queue_request(*_args): assert created is True assert request.state == "blocked" - assert request.reason == "immich_unconfigured" + assert request.reason == "immich_unreachable" assert imported == 0 assert queued == 0 +@pytest.mark.asyncio +async def test_unconfigured_immich_queues_any_user_without_import( + requests_db, monkeypatch +): + monkeypatch.setattr(explicit_reconciliation, "immich_configured", lambda: False) + monkeypatch.setattr( + explicit_reconciliation, + "check_immich_day_readiness", + lambda *_args: _async_value( + readiness(ready=True, reason="immich_unconfigured") + ), + ) + imported = 0 + + async def import_candidates(*_args): + nonlocal imported + imported += 1 + + async def not_called(): + raise AssertionError("Immich ownership does not apply without Immich") + + async def authorize(**_kwargs): + return SimpleNamespace(dirty_range_id="range-one") + + monkeypatch.setattr( + explicit_reconciliation, "import_immich_day_candidates", import_candidates + ) + monkeypatch.setattr(explicit_reconciliation, "resolve_immich_user_id", not_called) + monkeypatch.setattr(explicit_reconciliation, "authorize_explicit_range", authorize) + monkeypatch.setattr(explicit_reconciliation, "_queue_request", lambda *_args: "job") + + request, created = await explicit_reconciliation.request_explicit_reconciliation( + user=SimpleNamespace(id="not-the-admin"), + local_date=date(2026, 8, 15), + timezone_name="Asia/Kolkata", + ) + + assert created is True + assert request.state == "queued" + assert request.reason == "immich_unconfigured" + assert request.job_id == "job" + assert imported == 0 + + @pytest.mark.asyncio async def test_user_can_explicitly_reconcile_without_immich(requests_db, monkeypatch): checked = imported = 0 @@ -312,7 +356,7 @@ async def local_lock(*_args, **_kwargs): async def check(*_args): nonlocal checks checks += 1 - return readiness(ready=False, reason="immich_unconfigured") + return readiness(ready=False, reason="immich_unreachable") monkeypatch.setattr(explicit_reconciliation, "distributed_lock", local_lock) monkeypatch.setattr(explicit_reconciliation, "check_immich_day_readiness", check) @@ -335,6 +379,7 @@ async def check(*_args): @pytest.mark.asyncio async def test_non_owner_cannot_query_or_import_immich(requests_db, monkeypatch): + monkeypatch.setattr(explicit_reconciliation, "immich_configured", lambda: True) monkeypatch.setattr( explicit_reconciliation, "resolve_immich_user_id", @@ -696,3 +741,86 @@ def test_enqueue_keeps_running_retry_with_previous_ended_at(monkeypatch, status) queue_controller.enqueue_explicit_timeline_reconciliation("request") == "live-retry" ) + + +@pytest.mark.asyncio +async def test_cancel_stops_job_dismisses_range_and_allows_a_new_request( + requests_db, monkeypatch +): + stopped = [] + monkeypatch.setattr(explicit_reconciliation, "_queue_request", lambda _id: "job") + monkeypatch.setattr(explicit_reconciliation, "_stop_job", stopped.append) + user = SimpleNamespace(id="user") + day = date(2026, 8, 15) + + first, _ = await explicit_reconciliation.request_explicit_reconciliation( + user=user, local_date=day, timezone_name="Asia/Kolkata", skip_immich=True + ) + cancelled = await explicit_reconciliation.cancel_explicit_reconciliation( + user=user, request_id=first.request_id + ) + + assert cancelled.state == "cancelled" + assert stopped == ["job"] + dirty_range = await DirtyEvidenceRange.find_one( + DirtyEvidenceRange.dirty_range_id == first.dirty_range_id + ) + assert dirty_range.state == "dismissed" + assert dirty_range.lease_owner is None + assert dirty_range.resolution_history[-1].action == "cancelled" + assert dirty_range.resolution_history[-1].prior_state == "authorized_pending" + + # The cancelled request no longer pins the day: asking again starts fresh. + second, created = await explicit_reconciliation.request_explicit_reconciliation( + user=user, local_date=day, timezone_name="Asia/Kolkata", skip_immich=True + ) + assert created is True + assert second.request_id != first.request_id + + # The worker entrypoint refuses to run a cancelled request. + result = await timeline_jobs.explicit_reconciliation_job.__wrapped__( + first.request_id + ) + assert result == {"request_id": first.request_id, "state": "cancelled"} + + +@pytest.mark.asyncio +async def test_finished_request_cannot_be_cancelled(requests_db): + request = TimelineReconciliationRequest( + user_id="user", + local_date=date(2026, 8, 15), + timezone="Asia/Kolkata", + state="completed", + reason="user_bypassed_immich", + ) + await request.insert() + + with pytest.raises(explicit_reconciliation.ReconciliationNotCancellable): + await explicit_reconciliation.cancel_explicit_reconciliation( + user=SimpleNamespace(id="user"), request_id=request.request_id + ) + with pytest.raises(LookupError): + await explicit_reconciliation.cancel_explicit_reconciliation( + user=SimpleNamespace(id="someone-else"), request_id=request.request_id + ) + + +@pytest.mark.parametrize( + ("status", "expected"), + [("started", "stopped"), ("queued", "cancelled"), ("scheduled", "cancelled")], +) +def test_stop_job_kills_running_and_cancels_pending(monkeypatch, status, expected): + calls = [] + job = SimpleNamespace( + id="timeline-explicit_x", cancel=lambda: calls.append("cancel") + ) + monkeypatch.setattr(queue_controller.Job, "fetch", lambda *_a, **_k: job) + monkeypatch.setattr(queue_controller, "get_job_status_from_rq", lambda _j: status) + monkeypatch.setattr( + queue_controller, + "send_stop_job_command", + lambda _conn, job_id: calls.append(("stop", job_id)), + ) + + assert queue_controller.stop_explicit_timeline_reconciliation(job.id) == expected + assert calls == ([("stop", job.id)] if status == "started" else ["cancel"]) diff --git a/backend/tests/test_immich_discovery.py b/backend/tests/test_immich_discovery.py index 11f440b8..c2940a34 100644 --- a/backend/tests/test_immich_discovery.py +++ b/backend/tests/test_immich_discovery.py @@ -241,15 +241,16 @@ async def test_external_library_assets_do_not_satisfy_gate(monkeypatch): @pytest.mark.asyncio -async def test_unconfigured_immich_blocks_without_network(monkeypatch): +async def test_unconfigured_immich_is_ready_without_network(monkeypatch): monkeypatch.setattr(immich_discovery, "_settings", lambda: None) result = await immich_discovery.check_immich_day_readiness( date(2026, 8, 15), "Asia/Kolkata" ) - assert result.ready is False + assert result.ready is True assert result.reason == "immich_unconfigured" + assert result.target_assets == [] @pytest.mark.asyncio diff --git a/backend/tests/test_llm_config_errors.py b/backend/tests/test_llm_config_errors.py new file mode 100644 index 00000000..2ac8507e --- /dev/null +++ b/backend/tests/test_llm_config_errors.py @@ -0,0 +1,79 @@ +"""Misconfigured LLMs and unwritable settings must fail loudly, not silently.""" + +import os +from pathlib import Path + +import pytest + +from backend import config_loader +from backend.config_loader import ConfigSaveError, get_raw_models, save_config_section +from backend.model_registry import ( + AppModels, + LLMOperationConfig, + MissingModelCredentialsError, + ModelDef, +) + + +def _model(name: str, url: str, api_key) -> ModelDef: + return ModelDef( + name=name, + model_type="llm", + model_provider="openrouter", + api_family="openai", + model_name=name, + model_url=url, + api_key=api_key, + ) + + +def test_hosted_model_without_key_raises_when_client_is_built(): + hosted = _model("openrouter-qwen", "https://openrouter.ai/api/v1", "") + registry = AppModels( + defaults={"llm": hosted.name}, + models={hosted.name: hosted}, + llm_operations={"memory_write": LLMOperationConfig(model=hosted.name)}, + ) + + op = registry.get_llm_operation("memory_write") + + with pytest.raises(MissingModelCredentialsError) as error: + op.get_client(is_async=True) + assert "openrouter-qwen" in str(error.value) + assert "memory_write" in str(error.value) + + +def test_local_model_without_key_is_allowed(): + local = _model("local-llm", "http://llama-cpp-llm:8080/v1", "") + assert local.require_api_key() == "" + + +def test_hosted_model_with_key_returns_key(): + hosted = _model("openai", "https://api.openai.com/v1", "sk-test") + assert hosted.require_api_key() == "sk-test" + + +@pytest.fixture +def config_dir(tmp_path: Path, monkeypatch): + monkeypatch.setenv("CONFIG_DIR", str(tmp_path)) + yield tmp_path + config_loader._runtime_overrides.clear() + + +def test_raw_models_is_empty_when_config_has_no_models_key(config_dir: Path): + (config_dir / "config.yml").write_text("llm_operations: {}\n") + assert get_raw_models() == [] + + +def test_save_to_read_only_config_raises_actionable_error(config_dir: Path): + config_file = config_dir / "config.yml" + config_file.write_text("llm_operations: {}\n") + os.chmod(config_dir, 0o500) + os.chmod(config_file, 0o400) + try: + with pytest.raises(ConfigSaveError) as error: + save_config_section("llm_operations", {"memory_write": {"model": "x"}}) + finally: + os.chmod(config_dir, 0o700) + os.chmod(config_file, 0o600) + assert "llm_operations" in str(error.value) diff --git a/backend/tests/test_model_output_limits.py b/backend/tests/test_model_output_limits.py new file mode 100644 index 00000000..ee9c1add --- /dev/null +++ b/backend/tests/test_model_output_limits.py @@ -0,0 +1,195 @@ +"""An operation whose max_tokens its model cannot produce refuses to run. + +Regression: timeline days failed with OpenAI HTTP 400 ("max_tokens is too large: +32000. This model supports at most 16384") because the shipped 32K timeline +allowance was sent unchanged to gpt-4o-mini. The fix stops before the request and +asks for a larger-output model; it does not shrink the allowance silently. +""" + +from pathlib import Path + +import pytest +import yaml + +import backend.services.timeline.executor as timeline_executor +import backend.services.timeline.pi_executor as pi_executor +from backend.model_registry import ( + AppModels, + LLMOperationConfig, + ModelDef, + OutputLimitExceeded, + output_token_limit_findings, +) +from backend.services.memory.agent.pi_agent import _PiRuntimeConfig + +DEFAULTS_YML = Path(__file__).resolve().parents[2] / "config" / "defaults.yml" + + +def _model(name: str, max_output_tokens=None) -> ModelDef: + return ModelDef( + name=name, + model_type="llm", + model_provider="openai", + model_name="gpt-4o-mini", + model_url="https://api.openai.com/v1", + max_output_tokens=max_output_tokens, + model_params={"max_tokens": 2000}, + ) + + +def _registry(model: ModelDef, **operations) -> AppModels: + return AppModels( + defaults={"llm": model.name}, + models={model.name: model}, + llm_operations={ + name: LLMOperationConfig(max_tokens=value) + for name, value in operations.items() + }, + ) + + +def test_oversized_operation_refuses_and_names_the_model(): + registry = _registry(_model("small", 16384), timeline_segmentation=32000) + + with pytest.raises(OutputLimitExceeded) as raised: + registry.get_llm_operation("timeline_segmentation") + + message = str(raised.value) + assert "llm_operations.timeline_segmentation.max_tokens needs 32000" in message + assert "model 'small' accepts at most 16384" in message + assert "Choose a model that supports at least 32000" in message + + +def test_operation_within_limit_is_unchanged(): + registry = _registry(_model("small", 16384), chat=8000) + + assert registry.get_llm_operation("chat").max_tokens == 8000 + + +def test_model_without_declared_limit_passes_requests_through(): + registry = _registry(_model("local"), timeline_segmentation=32000) + + assert registry.get_llm_operation("timeline_segmentation").max_tokens == 32000 + + +def test_route_explanation_still_works_for_a_misconfigured_operation(): + registry = _registry(_model("small", 16384), timeline_segmentation=32000) + + assert registry.explain_llm_operation("timeline_segmentation")["model"] == "small" + + +def test_findings_name_each_oversized_setting(): + registry = _registry(_model("small", 16384), timeline_segmentation=32000, chat=8000) + + findings = output_token_limit_findings( + registry, + [("timeline.pi.max_tokens", "timeline_segmentation", 32000)], + ) + + assert [f["setting"] for f in findings] == [ + "llm_operations.timeline_segmentation.max_tokens", + "timeline.pi.max_tokens", + ] + assert findings[0]["model"] == "small" + assert findings[0]["requested"] == 32000 + assert findings[0]["limit"] == 16384 + + +def _pi_config(max_output_tokens) -> _PiRuntimeConfig: + return _PiRuntimeConfig( + binary="pi", + provider="openai", + model="gpt-4o-mini", + base_url="https://api.openai.com/v1", + api_key="k", + thinking="off", + max_tokens=4096, + context_window=98304, + timeout_seconds=30, + reasoning=False, + temperature=0.0, + max_output_tokens=max_output_tokens, + model_entry="openai-llm", + ) + + +def test_timeline_pi_override_refuses_a_small_model(monkeypatch): + monkeypatch.setattr( + pi_executor, "_resolve_pi_config", lambda operation: _pi_config(16384) + ) + executor = pi_executor.PiTimelineExecutor({"max_tokens": 32000}) + + with pytest.raises(OutputLimitExceeded, match="timeline.pi.max_tokens needs 32000"): + executor._final_stage_config(None) + + +def test_timeline_pi_override_kept_for_a_large_model(monkeypatch): + monkeypatch.setattr( + pi_executor, "_resolve_pi_config", lambda operation: _pi_config(None) + ) + + config = pi_executor.PiTimelineExecutor({"max_tokens": 32000})._final_stage_config( + None + ) + + assert config.max_tokens == 32000 + + +def test_timeline_preflight_refuses_before_a_day_is_queued(monkeypatch): + monkeypatch.setattr( + timeline_executor, + "settings_dict", + lambda: {"executor": "pi", "pi": {"max_tokens": 32000}}, + ) + monkeypatch.setattr( + timeline_executor, + "get_models_registry", + lambda: _registry(_model("openai-llm", 16384)), + ) + + with pytest.raises(OutputLimitExceeded, match="model 'openai-llm'"): + timeline_executor.check_output_limits() + + +def test_timeline_preflight_ignores_the_codex_executor(monkeypatch): + monkeypatch.setattr( + timeline_executor, + "settings_dict", + lambda: {"executor": "codex", "pi": {"max_tokens": 32000}}, + ) + monkeypatch.setattr( + timeline_executor, + "get_models_registry", + lambda: _registry(_model("openai-llm", 16384)), + ) + + timeline_executor.check_output_limits() + + +def test_shipped_openai_models_declare_their_output_limits(): + models = {m["name"]: m for m in yaml.safe_load(DEFAULTS_YML.read_text())["models"]} + + assert models["openai-llm"]["model_name"] == "gpt-4.1-mini" + assert models["openai-llm"]["max_output_tokens"] == 32768 + assert models["fallback-llm"]["model_name"] == "gpt-5-nano" + assert models["fallback-llm"]["max_output_tokens"] == 128000 + + +def test_config_diagnostics_ask_for_a_bigger_model(monkeypatch): + # Imported here to keep the controller's import graph out of the other tests. + import backend.controllers.system_controller as system_controller + + monkeypatch.setattr( + system_controller, + "load_config", + lambda: {"timeline": {"pi": {"max_tokens": 32000}}}, + ) + registry = _registry(_model("openai-llm", 16384)) + + issues = system_controller._output_limit_issues(registry) + + assert len(issues) == 1 + assert issues[0]["severity"] == "error" + assert "needs a model with at least 32000 output tokens" in issues[0]["message"] + assert "accepts at most 16384" in issues[0]["message"] + assert issues[0]["resolution"].startswith("Settings > AI Model Settings") diff --git a/backend/tests/test_streaming_end_stream_closed.py b/backend/tests/test_streaming_end_stream_closed.py new file mode 100644 index 00000000..b8a57cb7 --- /dev/null +++ b/backend/tests/test_streaming_end_stream_closed.py @@ -0,0 +1,52 @@ +"""Ending a stream whose provider socket already closed. + +Deepgram closes an idle stream (NET-0001) after about 10 seconds without audio. +When the session then ends, the CloseStream send hits a dead socket. That must +end the stream cleanly, not raise and leave the stream registered. +""" + +import pytest +from websockets.exceptions import ConnectionClosedError +from websockets.frames import Close + +from backend.services.transcription import RegistryStreamingTranscriptionProvider + +IDLE_CLOSE = Close( + 1011, "Deepgram did not receive audio data within the timeout window." +) + + +class ClosedSocket: + def __init__(self): + self.closed_called = False + + async def send(self, _payload): + raise ConnectionClosedError(IDLE_CLOSE, IDLE_CLOSE, rcvd_then_sent=True) + + async def recv(self): + raise ConnectionClosedError(IDLE_CLOSE, IDLE_CLOSE, rcvd_then_sent=True) + + async def close(self): + self.closed_called = True + + +def _provider_with(ws, pending=b""): + provider = object.__new__(RegistryStreamingTranscriptionProvider) + provider.model = type( + "Model", (), {"operations": {"end": {"message": {"type": "CloseStream"}}}} + )() + provider._streams = {"s1": {"ws": ws, "pending_audio": bytearray(pending)}} + return provider + + +@pytest.mark.parametrize("pending", [b"", b"\x00" * 64]) +async def test_end_stream_on_provider_closed_socket_returns_empty_and_unregisters( + pending, +): + ws = ClosedSocket() + provider = _provider_with(ws, pending) + + result = await provider.end_stream("s1") + + assert result == {"text": "", "words": [], "segments": []} + assert "s1" not in provider._streams diff --git a/backend/webui/src/components/AutomationSettings.test.tsx b/backend/webui/src/components/AutomationSettings.test.tsx index c2a14239..96887b40 100644 --- a/backend/webui/src/components/AutomationSettings.test.tsx +++ b/backend/webui/src/components/AutomationSettings.test.tsx @@ -3,17 +3,19 @@ import '@testing-library/jest-dom/vitest' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import AutomationSettings from './AutomationSettings' +import { formatDateTime, setDisplayTimezone } from '../utils/datetime' const state = vi.hoisted(() => ({ next: '2026-09-14T04:30:00+00:00' as string | null, update: vi.fn() })) vi.mock('../hooks/useFinetuning', () => ({ useCronJobs: () => ({ data: [{ job_id: 'daily', description: '', enabled: true, schedule: '30 4 * * *', last_run: null, next_run: state.next }], isLoading: false, refetch: vi.fn() }), useToggleCronJob: () => ({ mutateAsync: vi.fn() }), useRunCronJob: () => ({ mutateAsync: vi.fn() }), useUpdateCronSchedule: () => ({ mutateAsync: state.update }), })) -beforeEach(() => { state.next = '2026-09-14T04:30:00+00:00'; state.update.mockReset().mockResolvedValue({}) }) -afterEach(cleanup) -it('shows the UTC next-run instant in IST while preserving the UTC expression when edited', async () => { +beforeEach(() => { setDisplayTimezone('Asia/Kolkata'); state.next = '2026-09-14T04:30:00+00:00'; state.update.mockReset().mockResolvedValue({}) }) +afterEach(() => { cleanup(); setDisplayTimezone(null) }) +it('shows the UTC next-run instant in the display timezone while preserving the UTC expression when edited', async () => { render() - expect(screen.getByText(/Next:/)).toHaveTextContent(/10:00 am IST/i) + expect(screen.getByText(/Next:/)).toHaveTextContent(formatDateTime('2026-09-14T04:30:00Z')) + expect(screen.getByText(/Next:/)).toHaveTextContent(/10:00/) fireEvent.click(screen.getByText('Schedule and last run')) expect(screen.getByText(/At 04:30 AM/)).toHaveTextContent('(UTC)') fireEvent.click(screen.getByRole('button', { name: 'Edit schedule' })) diff --git a/backend/webui/src/components/AutomationSettings.tsx b/backend/webui/src/components/AutomationSettings.tsx index fbd39fb6..27479af8 100644 --- a/backend/webui/src/components/AutomationSettings.tsx +++ b/backend/webui/src/components/AutomationSettings.tsx @@ -3,6 +3,7 @@ import { Clock, ToggleLeft, ToggleRight, Edit3, Check, X, Play, RefreshCw, Eye } import cronstrue from 'cronstrue' import { useCronJobs, useToggleCronJob, useUpdateCronSchedule, useRunCronJob } from '../hooks/useFinetuning' import { Alert, Button, Card, IconButton, StateBadge, StateTone } from './ui' +import { formatDateTime, useDisplayTimezone } from '../utils/datetime' // Human-friendly names + what kind of automation each job is. Trigger-now lives // on the Training page; this card owns only "should it run / when". @@ -34,10 +35,11 @@ function humanCron(expr: string): string { function formatTs(iso: string | null): string { if (!iso) return 'Never' - return `${new Date(iso).toLocaleString('en-IN', { timeZone: 'Asia/Kolkata', dateStyle: 'medium', timeStyle: 'short' })} IST` + return formatDateTime(iso) } export default function AutomationSettings({ isAdmin }: { isAdmin: boolean }) { + const timezone = useDisplayTimezone() const { data: jobs = [], isLoading, refetch } = useCronJobs() const toggleJob = useToggleCronJob() const updateSchedule = useUpdateCronSchedule() @@ -96,7 +98,7 @@ export default function AutomationSettings({ isAdmin }: { isAdmin: boolean }) { Automation & Schedules

- Next runs are shown in IST. Enabling or disabling a job takes effect immediately. + Next runs are shown in {timezone}. Enabling or disabling a job takes effect immediately.

{error && ( diff --git a/backend/webui/src/components/ChatRunViewer.tsx b/backend/webui/src/components/ChatRunViewer.tsx index db7c2c19..994a6383 100644 --- a/backend/webui/src/components/ChatRunViewer.tsx +++ b/backend/webui/src/components/ChatRunViewer.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef } from 'react' import { useQuery } from '@tanstack/react-query' import { X } from 'lucide-react' import { chatApi } from '../services/api' +import { formatDateTime } from '../utils/datetime' export interface ChatRun { run_id: string @@ -26,9 +27,9 @@ interface RunStep { response_unavailable?: boolean } -const stamp = (value: string) => new Date(value).toLocaleString('en-IN', { - timeZone: 'Asia/Kolkata', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', -}) + ' IST' +const stamp = (value: string) => formatDateTime(value, { + day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', timeZoneName: 'short', +}) function Payload({ label, value }: { label: string; value: unknown }) { if (value === undefined) return null diff --git a/backend/webui/src/components/DateTime.tsx b/backend/webui/src/components/DateTime.tsx new file mode 100644 index 00000000..d03554e4 --- /dev/null +++ b/backend/webui/src/components/DateTime.tsx @@ -0,0 +1,27 @@ +import { formatDate, formatDateTime, formatTime, toDate, useDisplayTimezone, type DateInput, type FormatOptions } from '../utils/datetime' + +const FORMATTERS = { datetime: formatDateTime, date: formatDate, time: formatTime } + +interface DateTimeProps { + value: DateInput + /** Defaults to "datetime". */ + format?: keyof typeof FORMATTERS + options?: FormatOptions + className?: string +} + +/** A timestamp shown in the user's display timezone; hover shows the full date and time. */ +export default function DateTime({ value, format = 'datetime', options, className }: DateTimeProps) { + useDisplayTimezone() + const date = toDate(value) + if (Number.isNaN(date.getTime())) return null + return ( + + ) +} diff --git a/backend/webui/src/components/RecordingMemoryContext.tsx b/backend/webui/src/components/RecordingMemoryContext.tsx index 7742a615..bba679a1 100644 --- a/backend/webui/src/components/RecordingMemoryContext.tsx +++ b/backend/webui/src/components/RecordingMemoryContext.tsx @@ -1,4 +1,3 @@ -import { sourceDate } from "../utils/sourceTime"; import { useState } from "react"; import { Link, useSearchParams } from "react-router-dom"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; @@ -13,6 +12,7 @@ import { Button } from "./ui"; import { CandidateChanges } from "./timeline/ReviewDesk"; import ContextRefreshes from "./ContextRefreshes"; import { sourceLabel } from "./timeline/SessionMemoryBoard"; +import { formatDateTime, formatTime, useDisplayTimezone } from '../utils/datetime' interface Context { organization_requests?: { request_id?: string }[]; @@ -54,15 +54,16 @@ export default function RecordingMemoryContext({ const client = useQueryClient(); const [params] = useSearchParams(); const space = params.get("memory_space_id") || undefined; + const timezone = useDisplayTimezone(); const [clarification, setClarification] = useState(""); const [requestId, setRequestId] = useState(); const [inspect, setInspect] = useState(false); const query = useQuery({ - queryKey: ["recording-context", recordingId, space], + queryKey: ["recording-context", recordingId, space, timezone], queryFn: async () => ( await api.get(`/api/recordings/${recordingId}/context`, { - params: { timezone: "Asia/Kolkata", memory_space_id: space }, + params: { timezone, memory_space_id: space }, }) ).data, refetchInterval: 5000, @@ -80,7 +81,7 @@ export default function RecordingMemoryContext({ mutationFn: (day: string) => api.post(`/api/recordings/${recordingId}/organize-day`, { local_date: day, - timezone: "Asia/Kolkata", + timezone, }), onSuccess: (response) => { setRequestId(response.data.request_id); @@ -170,10 +171,8 @@ export default function RecordingMemoryContext({ {!data.event_date_known && (

Recording date unknown. Uploaded{" "} - {sourceDate(data.uploaded_at).toLocaleString("en-IN", { - timeZone: "Asia/Kolkata", - })}{" "} - IST. This session stays undated. + {formatDateTime(data.uploaded_at)}. This session stays + undated.

)} {data.event_date_known && !data.sessions.length && ( @@ -220,18 +219,11 @@ export default function RecordingMemoryContext({

{s.title}

- {sourceDate(s.started_at).toLocaleTimeString("en-IN", { - timeZone: "Asia/Kolkata", - hour: "numeric", + {formatTime(s.started_at, { + hour: "2-digit", minute: "2-digit", })} - – - {sourceDate(s.ended_at).toLocaleTimeString("en-IN", { - timeZone: "Asia/Kolkata", - hour: "numeric", - minute: "2-digit", - })}{" "} - IST + –{formatTime(s.ended_at)}

{s.summary} @@ -423,7 +415,7 @@ export default function RecordingMemoryContext({

{session.total_sources > 0 && (busy || session.state === 'paused') &&

{session.completed_sources} of {session.total_sources} source groups complete · {({ account: 'Building the session account', combining: 'Combining source accounts', checking_claims: 'Independent account review', memory: 'Preparing note changes' } as Record)[session.stage || 'account']}

} - {busy && activityLabel(session) &&

{activityLabel(session)} · last activity {clock(session.investigation_activity!.updated_at, 'Asia/Kolkata')} IST

} + {busy && activityLabel(session) &&

{activityLabel(session)} · last activity {formatTime(session.investigation_activity!.updated_at)}

} {session.error && session.state !== 'generating' &&

{session.state === 'paused' ? (session.failure_kind === 'repeated_tool_call' ? 'Repeated identical tool calls stopped this investigation. Saved source reads and drafts remain inspectable. Restart begins a fresh attempt; no automatic retry is scheduled.' : 'The investigation reached its work limit. Restart to begin a new attempt with completed source groups retained; no automatic retry is scheduled. Earlier exchanges remain available below.') : session.state === 'failed' ? 'Preparation stopped before a reviewed draft was completed. Retry preparation, or inspect the details below.' : session.state === 'stale' ? 'This draft needs refreshing against the current sources before it can be approved.' : session.failure_kind === 'time_slice' ? 'Saved work will continue in the queue.' : session.error}

{session.state === 'failed' &&
Technical details
{session.error}
} @@ -152,7 +153,7 @@ function SessionRow({ session, day, timezone }: { session: MemorySession; day: s {(decide.error || generate.error || restart.error || correction.error) &&

{errorMessage(decide.error || generate.error || restart.error || correction.error)}

} {notice &&

{notice}

} {open &&
- {session.investigation_activity?.event &&
Investigation activity

{session.investigation_activity.tool_calls} tool calls · {session.investigation_activity.rounds} model rounds · Pi {session.investigation_activity.runtime_version}

{session.investigation_activity.checkpoint_saved ? 'Native session checkpoint saved' : 'Awaiting first complete checkpoint'}{session.investigation_activity.resumed ? ' · resumed saved work' : ''}

Last activity {clock(session.investigation_activity.updated_at, 'Asia/Kolkata')} IST

} + {session.investigation_activity?.event &&
Investigation activity

{session.investigation_activity.tool_calls} tool calls · {session.investigation_activity.rounds} model rounds · Pi {session.investigation_activity.runtime_version}

{session.investigation_activity.checkpoint_saved ? 'Native session checkpoint saved' : 'Awaiting first complete checkpoint'}{session.investigation_activity.resumed ? ' · resumed saved work' : ''}

Last activity {formatTime(session.investigation_activity.updated_at)}

} {proposal && reviewing && } {questions.map(question =>

{question}

)} {questions.length > 0 &&