The platform for continuously improving AI agents.
Fix tenancy, invalid-input and stuck-work bugs from the system test (#368)
Freyam Mehtae9732aad38c3
diff --git a/.agents/skills/backend-architecture/references/capabilities.md b/.agents/skills/backend-architecture/references/capabilities.mdindex b3cc288d..fa9ffd5b 100644--- a/.agents/skills/backend-architecture/references/capabilities.md+++ b/.agents/skills/backend-architecture/references/capabilities.md@@ -4,7 +4,7 @@ The agent is the project itself: one graph per project, with no table. `Capabili## Identity-- OTLP ingest never creates a capability; a connector import with `auto_create` in its capability mapping creates `observed` rows. `services/capabilities/identity.lookup` resolves IDs, names and slugs through `IdentityAlias` (renames included). A span with no resolvable identity binds to its trace's capability when the trace has exactly one; otherwise it stays unbound, and `tasks/capability_rebind.py` re-binds the backlog after scans and hand-made rows.+- OTLP ingest never creates a capability; a connector import with `auto_create` in its capability mapping creates `observed` rows. `services/capabilities/identity.lookup` resolves IDs, names and slugs through `IdentityAlias` (renames included) for the API and Console; ingest, instrumentation checks and the rebind task use `identity.lookup_id`, which takes a current capability's UUID only. A span with no resolvable identity binds to its trace's current capability when the trace has exactly one; otherwise it stays unbound, and `tasks/capability_rebind.py` re-binds the backlog after scans and hand-made rows.- On OTLP spans, wire identity is `overmind.capability.id` alone; connector spans bind through the credential's capability mapping. `overmind.agent.*` attributes are not read, and `overmind.capability.name` is a display label that never resolves. The `overmind/<uuid>` model alias never changes.- A scan never deletes. An absent capability becomes `status=leftover` and reactivates in place when the code returns; `observed` rows (made by hand or by a connector `auto_create`) are exempt.- `DELETE /api/capabilities/{id}/` is a soft delete (`status=deleted`): the row and its data stay but are invisible to lists, scans and identity lookup, so a later scan mints a fresh row. There is no merge, split, retire or history.diff --git a/.agents/skills/backend-architecture/references/evaluation.md b/.agents/skills/backend-architecture/references/evaluation.mdindex db610d17..d251dcb4 100644--- a/.agents/skills/backend-architecture/references/evaluation.md+++ b/.agents/skills/backend-architecture/references/evaluation.md@@ -8,7 +8,7 @@ An `EvalRun` scores one target (`mode` `recorded` or `generate`) over one pinned- `dataset.DatasetRowProcessor` scores rows with the live span evaluators and saves each `EvalScore(source_type=dataset_row)` as it is written, only while the run's `scoring_task_id` is the scorer's own. The scorer beats `updated_at` every 30 s; `runs.reap_stalled` hands a silent one to a new scorer that skips saved rows (up to `SCORING_ATTEMPTS`), sends a pending run's start again after 10 minutes and fails it after 60.- A row stands for the capability's answer: it takes every frozen row whose `span_type` is blank or `llm_call`, whatever its `span_name`. `tool_call`, `retrieval` and `workflow` rows stay live-only.- A training job reuses its first run's matrix for its later evaluations.-- `comparison.compare` pairs the latest score per row that both runs scored into wins, losses and ties (`EPSILON` 0.005), and labels per-metric and overall means improved, regressed or unchanged; added and removed mark a metric present in only one run. It also reports trust.+- `comparison.compare` pairs the latest score per row that both runs scored into wins, losses and ties (`EPSILON` 0.005), and labels per-metric and overall means improved, regressed or unchanged; a metric or the overall score with no row scored in both runs, including a metric only one run has, is unmeasured. It also reports trust.- Replayed rows snapshot the runner's initial request (`replay.RunResult.request`). A token-limited generation keeps its partial answer and usage, is marked degraded, and is excluded from trusted scores rather than scored as zero.## Judges and context estimatesdiff --git a/frontend/src/components/evaluations/run-comparison.tsx b/frontend/src/components/evaluations/run-comparison.tsxindex 0dcde47f..bee800ae 100644--- a/frontend/src/components/evaluations/run-comparison.tsx+++ b/frontend/src/components/evaluations/run-comparison.tsx@@ -63,6 +63,7 @@ const STATUS_TONE: Record<string, StatusTone> = {regressed: "error",removed: "warning",unchanged: "neutral",+ unmeasured: "neutral",};const STATUS_LABEL: Record<string, string> = {@@ -71,6 +72,7 @@ const STATUS_LABEL: Record<string, string> = {regressed: "Regressed",removed: "Lost coverage",unchanged: "Unchanged",+ unmeasured: "No paired scores",};function StatusPill({ status }: { status: string }) {diff --git a/frontend/src/openapi/apis/TracesApi.ts b/frontend/src/openapi/apis/TracesApi.tsindex 1b4d7beb..d2cc43f5 100644--- a/frontend/src/openapi/apis/TracesApi.ts+++ b/frontend/src/openapi/apis/TracesApi.ts@@ -46,7 +46,6 @@ export interface TracesListRequest {page?: number;pageSize?: number;project?: string;- projectId?: number;receivedAtGte?: Date;receivedAtLte?: Date;search?: string;@@ -93,7 +92,6 @@ export interface TracesServicesListRequest {page?: number;pageSize?: number;project?: string;- projectId?: number;receivedAtGte?: Date;receivedAtLte?: Date;search?: string;@@ -194,10 +192,6 @@ export class TracesApi extends runtime.BaseAPI {queryParameters['project'] = requestParameters['project'];}- if (requestParameters['projectId'] != null) {- queryParameters['project_id'] = requestParameters['projectId'];- }-if (requestParameters['receivedAtGte'] != null) {queryParameters['received_at__gte'] = (requestParameters['receivedAtGte'] as any).toISOString();}@@ -503,10 +497,6 @@ export class TracesApi extends runtime.BaseAPI {queryParameters['project'] = requestParameters['project'];}- if (requestParameters['projectId'] != null) {- queryParameters['project_id'] = requestParameters['projectId'];- }-if (requestParameters['receivedAtGte'] != null) {queryParameters['received_at__gte'] = (requestParameters['receivedAtGte'] as any).toISOString();}diff --git a/frontend/src/openapi/models/Capability.ts b/frontend/src/openapi/models/Capability.tsindex dc60ee4f..dc1abe3b 100644--- a/frontend/src/openapi/models/Capability.ts+++ b/frontend/src/openapi/models/Capability.ts@@ -124,7 +124,7 @@ export interface Capability {* @type {boolean}* @memberof Capability*/- observed?: boolean;+ readonly observed: boolean;/**** @type {any}@@ -196,13 +196,13 @@ export interface Capability {* @type {any}* @memberof Capability*/- usageStats?: any | null;+ readonly usageStats: any | null;/**** @type {Date}* @memberof Capability*/- lastActivityAt?: Date | null;+ readonly lastActivityAt: Date | null;/**** @type {Date}@@ -259,9 +259,12 @@ export function instanceOfCapability(value: object): value is Capability {if (!('flow' in value) || value['flow'] === undefined) return false;if (!('name' in value) || value['name'] === undefined) return false;if (!('slug' in value) || value['slug'] === undefined) return false;+ if (!('observed' in value) || value['observed'] === undefined) return false;if (!('activeModelActivatedAt' in value) || value['activeModelActivatedAt'] === undefined) return false;if (!('firstApplicationRequestAt' in value) || value['firstApplicationRequestAt'] === undefined) return false;if (!('lastApplicationRequestAt' in value) || value['lastApplicationRequestAt'] === undefined) return false;+ if (!('usageStats' in value) || value['usageStats'] === undefined) return false;+ if (!('lastActivityAt' in value) || value['lastActivityAt'] === undefined) return false;if (!('createdAt' in value) || value['createdAt'] === undefined) return false;if (!('updatedAt' in value) || value['updatedAt'] === undefined) return false;if (!('project' in value) || value['project'] === undefined) return false;@@ -292,7 +295,7 @@ export function CapabilityFromJSONTyped(json: any, ignoreDiscriminator: boolean)'model': json['model'] == null ? undefined : json['model'],'cliVersion': json['cli_version'] == null ? undefined : json['cli_version'],'status': json['status'] == null ? undefined : CapabilityStatusEnumFromJSON(json['status']),- 'observed': json['observed'] == null ? undefined : json['observed'],+ 'observed': json['observed'],'footprint': json['footprint'] == null ? undefined : json['footprint'],'inputSchema': json['input_schema'] == null ? undefined : json['input_schema'],'outputFields': json['output_fields'] == null ? undefined : json['output_fields'],@@ -304,8 +307,8 @@ export function CapabilityFromJSONTyped(json: any, ignoreDiscriminator: boolean)'firstApplicationRequestAt': (json['first_application_request_at'] == null ? null : new Date(json['first_application_request_at'])),'lastApplicationRequestAt': (json['last_application_request_at'] == null ? null : new Date(json['last_application_request_at'])),'improvementMetadata': json['improvement_metadata'] == null ? undefined : json['improvement_metadata'],- 'usageStats': json['usage_stats'] == null ? undefined : json['usage_stats'],- 'lastActivityAt': json['last_activity_at'] == null ? undefined : (new Date(json['last_activity_at'])),+ 'usageStats': json['usage_stats'],+ 'lastActivityAt': (json['last_activity_at'] == null ? null : new Date(json['last_activity_at'])),'createdAt': (new Date(json['created_at'])),'updatedAt': (new Date(json['updated_at'])),'project': json['project'],@@ -320,7 +323,7 @@ export function CapabilityToJSON(json: any): Capability {return CapabilityToJSONTyped(json, false);}-export function CapabilityToJSONTyped(value?: Omit<Capability, 'id'|'activation'|'dataset_size'|'flow'|'slug'|'active_model_activated_at'|'first_application_request_at'|'last_application_request_at'|'created_at'|'updated_at'|'previous_active_model'> | null, ignoreDiscriminator: boolean = false): any {+export function CapabilityToJSONTyped(value?: Omit<Capability, 'id'|'activation'|'dataset_size'|'flow'|'slug'|'observed'|'active_model_activated_at'|'first_application_request_at'|'last_application_request_at'|'usage_stats'|'last_activity_at'|'created_at'|'updated_at'|'previous_active_model'> | null, ignoreDiscriminator: boolean = false): any {if (value == null) {return value;}@@ -335,7 +338,6 @@ export function CapabilityToJSONTyped(value?: Omit<Capability, 'id'|'activation''model': value['model'],'cli_version': value['cliVersion'],'status': CapabilityStatusEnumToJSON(value['status']),- 'observed': value['observed'],'footprint': value['footprint'],'input_schema': value['inputSchema'],'output_fields': value['outputFields'],@@ -344,8 +346,6 @@ export function CapabilityToJSONTyped(value?: Omit<Capability, 'id'|'activation''tools_summary': value['toolsSummary'],'decision_logic': value['decisionLogic'],'improvement_metadata': value['improvementMetadata'],- 'usage_stats': value['usageStats'],- 'last_activity_at': value['lastActivityAt'] == null ? value['lastActivityAt'] : value['lastActivityAt'].toISOString(),'project': value['project'],'active_eval_set': value['activeEvalSet'],'active_model': value['activeModel'],diff --git a/frontend/src/openapi/models/CapabilityRequest.ts b/frontend/src/openapi/models/CapabilityRequest.tsindex 72edee26..94930977 100644--- a/frontend/src/openapi/models/CapabilityRequest.ts+++ b/frontend/src/openapi/models/CapabilityRequest.ts@@ -75,12 +75,6 @@ export interface CapabilityRequest {* @memberof CapabilityRequest*/status?: CapabilityStatusEnum;- /**- *- * @type {boolean}- * @memberof CapabilityRequest- */- observed?: boolean;/**** @type {any}@@ -129,18 +123,6 @@ export interface CapabilityRequest {* @memberof CapabilityRequest*/improvementMetadata?: any | null;- /**- *- * @type {any}- * @memberof CapabilityRequest- */- usageStats?: any | null;- /**- *- * @type {Date}- * @memberof CapabilityRequest- */- lastActivityAt?: Date | null;/**** @type {string}@@ -196,7 +178,6 @@ export function CapabilityRequestFromJSONTyped(json: any, ignoreDiscriminator: b'model': json['model'] == null ? undefined : json['model'],'cliVersion': json['cli_version'] == null ? undefined : json['cli_version'],'status': json['status'] == null ? undefined : CapabilityStatusEnumFromJSON(json['status']),- 'observed': json['observed'] == null ? undefined : json['observed'],'footprint': json['footprint'] == null ? undefined : json['footprint'],'inputSchema': json['input_schema'] == null ? undefined : json['input_schema'],'outputFields': json['output_fields'] == null ? undefined : json['output_fields'],@@ -205,8 +186,6 @@ export function CapabilityRequestFromJSONTyped(json: any, ignoreDiscriminator: b'toolsSummary': json['tools_summary'] == null ? undefined : json['tools_summary'],'decisionLogic': json['decision_logic'] == null ? undefined : json['decision_logic'],'improvementMetadata': json['improvement_metadata'] == null ? undefined : json['improvement_metadata'],- 'usageStats': json['usage_stats'] == null ? undefined : json['usage_stats'],- 'lastActivityAt': json['last_activity_at'] == null ? undefined : (new Date(json['last_activity_at'])),'project': json['project'],'activeEvalSet': json['active_eval_set'] == null ? undefined : json['active_eval_set'],'activeModel': json['active_model'] == null ? undefined : json['active_model'],@@ -233,7 +212,6 @@ export function CapabilityRequestToJSONTyped(value?: CapabilityRequest | null, i'model': value['model'],'cli_version': value['cliVersion'],'status': CapabilityStatusEnumToJSON(value['status']),- 'observed': value['observed'],'footprint': value['footprint'],'input_schema': value['inputSchema'],'output_fields': value['outputFields'],@@ -242,8 +220,6 @@ export function CapabilityRequestToJSONTyped(value?: CapabilityRequest | null, i'tools_summary': value['toolsSummary'],'decision_logic': value['decisionLogic'],'improvement_metadata': value['improvementMetadata'],- 'usage_stats': value['usageStats'],- 'last_activity_at': value['lastActivityAt'] == null ? value['lastActivityAt'] : value['lastActivityAt'].toISOString(),'project': value['project'],'active_eval_set': value['activeEvalSet'],'active_model': value['activeModel'],diff --git a/frontend/src/openapi/models/ConnectorCredential.ts b/frontend/src/openapi/models/ConnectorCredential.tsindex e88fa4e6..995eb4b4 100644--- a/frontend/src/openapi/models/ConnectorCredential.ts+++ b/frontend/src/openapi/models/ConnectorCredential.ts@@ -180,7 +180,7 @@ export interface ConnectorCredential {* @type {any}* @memberof ConnectorCredential*/- capabilityMapping?: any | null;+ readonly capabilityMapping: any | null;/**** @type {ConnectorActiveConfig}@@ -224,6 +224,7 @@ export function instanceOfConnectorCredential(value: object): value is Connectorif (!('totalSpansImported' in value) || value['totalSpansImported'] === undefined) return false;if (!('totalTracesImported' in value) || value['totalTracesImported'] === undefined) return false;if (!('nextPollAt' in value) || value['nextPollAt'] === undefined) return false;+ if (!('capabilityMapping' in value) || value['capabilityMapping'] === undefined) return false;if (!('activeConfig' in value) || value['activeConfig'] === undefined) return false;if (!('createdAt' in value) || value['createdAt'] === undefined) return false;if (!('updatedAt' in value) || value['updatedAt'] === undefined) return false;@@ -260,7 +261,7 @@ export function ConnectorCredentialFromJSONTyped(json: any, ignoreDiscriminator:'totalSpansImported': json['total_spans_imported'],'totalTracesImported': json['total_traces_imported'],'nextPollAt': (json['next_poll_at'] == null ? null : new Date(json['next_poll_at'])),- 'capabilityMapping': json['capability_mapping'] == null ? undefined : json['capability_mapping'],+ 'capabilityMapping': json['capability_mapping'],'activeConfig': ConnectorActiveConfigFromJSON(json['active_config']),'createdAt': (new Date(json['created_at'])),'updatedAt': (new Date(json['updated_at'])),@@ -271,7 +272,7 @@ export function ConnectorCredentialToJSON(json: any): ConnectorCredential {return ConnectorCredentialToJSONTyped(json, false);}-export function ConnectorCredentialToJSONTyped(value?: Omit<ConnectorCredential, 'id'|'api_key_hint'|'is_active'|'last_synced_at'|'sync_status'|'backfill_imported'|'backfill_total'|'sync_progress'|'sync_error'|'api_version'|'verified_at'|'total_spans_imported'|'total_traces_imported'|'next_poll_at'|'active_config'|'created_at'|'updated_at'> | null, ignoreDiscriminator: boolean = false): any {+export function ConnectorCredentialToJSONTyped(value?: Omit<ConnectorCredential, 'id'|'api_key_hint'|'is_active'|'last_synced_at'|'sync_status'|'backfill_imported'|'backfill_total'|'sync_progress'|'sync_error'|'api_version'|'verified_at'|'total_spans_imported'|'total_traces_imported'|'next_poll_at'|'capability_mapping'|'active_config'|'created_at'|'updated_at'> | null, ignoreDiscriminator: boolean = false): any {if (value == null) {return value;}@@ -284,6 +285,5 @@ export function ConnectorCredentialToJSONTyped(value?: Omit<ConnectorCredential,'base_url': value['baseUrl'],'auto_sync_enabled': value['autoSyncEnabled'],'poll_interval_seconds': value['pollIntervalSeconds'],- 'capability_mapping': value['capabilityMapping'],};}diff --git a/frontend/src/openapi/models/ConnectorCredentialRequest.ts b/frontend/src/openapi/models/ConnectorCredentialRequest.tsindex ce2a530e..c008e5de 100644--- a/frontend/src/openapi/models/ConnectorCredentialRequest.ts+++ b/frontend/src/openapi/models/ConnectorCredentialRequest.ts@@ -75,12 +75,6 @@ export interface ConnectorCredentialRequest {* @memberof ConnectorCredentialRequest*/pollIntervalSeconds?: number;- /**- *- * @type {any}- * @memberof ConnectorCredentialRequest- */- capabilityMapping?: any | null;}@@ -113,7 +107,6 @@ export function ConnectorCredentialRequestFromJSONTyped(json: any, ignoreDiscrim'apiSecret': json['api_secret'] == null ? undefined : json['api_secret'],'autoSyncEnabled': json['auto_sync_enabled'] == null ? undefined : json['auto_sync_enabled'],'pollIntervalSeconds': json['poll_interval_seconds'] == null ? undefined : json['poll_interval_seconds'],- 'capabilityMapping': json['capability_mapping'] == null ? undefined : json['capability_mapping'],};}@@ -136,6 +129,5 @@ export function ConnectorCredentialRequestToJSONTyped(value?: ConnectorCredentia'api_secret': value['apiSecret'],'auto_sync_enabled': value['autoSyncEnabled'],'poll_interval_seconds': value['pollIntervalSeconds'],- 'capability_mapping': value['capabilityMapping'],};}diff --git a/frontend/src/openapi/models/FinetuningJob.ts b/frontend/src/openapi/models/FinetuningJob.tsindex 08901a5b..89c00119 100644--- a/frontend/src/openapi/models/FinetuningJob.ts+++ b/frontend/src/openapi/models/FinetuningJob.ts@@ -318,7 +318,7 @@ export interface FinetuningJob {* @type {number}* @memberof FinetuningJob*/- maxRetries?: number;+ readonly maxRetries: number;/**** @type {string}@@ -427,6 +427,7 @@ export function instanceOfFinetuningJob(value: object): value is FinetuningJob {if (!('result' in value) || value['result'] === undefined) return false;if (!('errorMessage' in value) || value['errorMessage'] === undefined) return false;if (!('retryCount' in value) || value['retryCount'] === undefined) return false;+ if (!('maxRetries' in value) || value['maxRetries'] === undefined) return false;if (!('celeryTaskId' in value) || value['celeryTaskId'] === undefined) return false;if (!('costUsd' in value) || value['costUsd'] === undefined) return false;if (!('billedMinutes' in value) || value['billedMinutes'] === undefined) return false;@@ -492,7 +493,7 @@ export function FinetuningJobFromJSONTyped(json: any, ignoreDiscriminator: boole'result': json['result'],'errorMessage': json['error_message'],'retryCount': json['retry_count'],- 'maxRetries': json['max_retries'] == null ? undefined : json['max_retries'],+ 'maxRetries': json['max_retries'],'celeryTaskId': json['celery_task_id'],'costUsd': json['cost_usd'],'billedMinutes': json['billed_minutes'],@@ -509,7 +510,7 @@ export function FinetuningJobToJSON(json: any): FinetuningJob {return FinetuningJobToJSONTyped(json, false);}-export function FinetuningJobToJSONTyped(value?: Omit<FinetuningJob, 'requested_configuration'|'record'|'native_evaluation'|'id'|'cell_info'|'triggered_by'|'status'|'provider'|'model_weights_location'|'output_model_name'|'deployed_model_id'|'decision_job_id'|'progress'|'result'|'error_message'|'retry_count'|'celery_task_id'|'cost_usd'|'billed_minutes'|'cost_synced_at'|'created_at'|'updated_at'|'started_at'|'completed_at'|'events'> | null, ignoreDiscriminator: boolean = false): any {+export function FinetuningJobToJSONTyped(value?: Omit<FinetuningJob, 'requested_configuration'|'record'|'native_evaluation'|'id'|'cell_info'|'triggered_by'|'status'|'provider'|'model_weights_location'|'output_model_name'|'deployed_model_id'|'decision_job_id'|'progress'|'result'|'error_message'|'retry_count'|'max_retries'|'celery_task_id'|'cost_usd'|'billed_minutes'|'cost_synced_at'|'created_at'|'updated_at'|'started_at'|'completed_at'|'events'> | null, ignoreDiscriminator: boolean = false): any {if (value == null) {return value;}@@ -543,6 +544,5 @@ export function FinetuningJobToJSONTyped(value?: Omit<FinetuningJob, 'requested_'hyperparameters': value['hyperparameters'],'group_id': value['groupId'],'model_tier': value['modelTier'],- 'max_retries': value['maxRetries'],};}diff --git a/frontend/src/openapi/models/FinetuningJobRequest.ts b/frontend/src/openapi/models/FinetuningJobRequest.tsindex 1587e549..6723821e 100644--- a/frontend/src/openapi/models/FinetuningJobRequest.ts+++ b/frontend/src/openapi/models/FinetuningJobRequest.ts@@ -189,12 +189,6 @@ export interface FinetuningJobRequest {* @memberof FinetuningJobRequest*/modelTier?: FinetuningJobRequestModelTierEnum;- /**- *- * @type {number}- * @memberof FinetuningJobRequest- */- maxRetries?: number;}@@ -273,7 +267,6 @@ export function FinetuningJobRequestFromJSONTyped(json: any, ignoreDiscriminator'hyperparameters': json['hyperparameters'] == null ? undefined : json['hyperparameters'],'groupId': json['group_id'] == null ? undefined : json['group_id'],'modelTier': json['model_tier'] == null ? undefined : json['model_tier'],- 'maxRetries': json['max_retries'] == null ? undefined : json['max_retries'],};}@@ -315,6 +308,5 @@ export function FinetuningJobRequestToJSONTyped(value?: FinetuningJobRequest | n'hyperparameters': value['hyperparameters'],'group_id': value['groupId'],'model_tier': value['modelTier'],- 'max_retries': value['maxRetries'],};}diff --git a/frontend/src/openapi/models/PatchedCapabilityRequest.ts b/frontend/src/openapi/models/PatchedCapabilityRequest.tsindex 7f3fc888..f17c2320 100644--- a/frontend/src/openapi/models/PatchedCapabilityRequest.ts+++ b/frontend/src/openapi/models/PatchedCapabilityRequest.ts@@ -75,12 +75,6 @@ export interface PatchedCapabilityRequest {* @memberof PatchedCapabilityRequest*/status?: CapabilityStatusEnum;- /**- *- * @type {boolean}- * @memberof PatchedCapabilityRequest- */- observed?: boolean;/**** @type {any}@@ -129,18 +123,6 @@ export interface PatchedCapabilityRequest {* @memberof PatchedCapabilityRequest*/improvementMetadata?: any | null;- /**- *- * @type {any}- * @memberof PatchedCapabilityRequest- */- usageStats?: any | null;- /**- *- * @type {Date}- * @memberof PatchedCapabilityRequest- */- lastActivityAt?: Date | null;/**** @type {string}@@ -194,7 +176,6 @@ export function PatchedCapabilityRequestFromJSONTyped(json: any, ignoreDiscrimin'model': json['model'] == null ? undefined : json['model'],'cliVersion': json['cli_version'] == null ? undefined : json['cli_version'],'status': json['status'] == null ? undefined : CapabilityStatusEnumFromJSON(json['status']),- 'observed': json['observed'] == null ? undefined : json['observed'],'footprint': json['footprint'] == null ? undefined : json['footprint'],'inputSchema': json['input_schema'] == null ? undefined : json['input_schema'],'outputFields': json['output_fields'] == null ? undefined : json['output_fields'],@@ -203,8 +184,6 @@ export function PatchedCapabilityRequestFromJSONTyped(json: any, ignoreDiscrimin'toolsSummary': json['tools_summary'] == null ? undefined : json['tools_summary'],'decisionLogic': json['decision_logic'] == null ? undefined : json['decision_logic'],'improvementMetadata': json['improvement_metadata'] == null ? undefined : json['improvement_metadata'],- 'usageStats': json['usage_stats'] == null ? undefined : json['usage_stats'],- 'lastActivityAt': json['last_activity_at'] == null ? undefined : (new Date(json['last_activity_at'])),'project': json['project'] == null ? undefined : json['project'],'activeEvalSet': json['active_eval_set'] == null ? undefined : json['active_eval_set'],'activeModel': json['active_model'] == null ? undefined : json['active_model'],@@ -231,7 +210,6 @@ export function PatchedCapabilityRequestToJSONTyped(value?: PatchedCapabilityReq'model': value['model'],'cli_version': value['cliVersion'],'status': CapabilityStatusEnumToJSON(value['status']),- 'observed': value['observed'],'footprint': value['footprint'],'input_schema': value['inputSchema'],'output_fields': value['outputFields'],@@ -240,8 +218,6 @@ export function PatchedCapabilityRequestToJSONTyped(value?: PatchedCapabilityReq'tools_summary': value['toolsSummary'],'decision_logic': value['decisionLogic'],'improvement_metadata': value['improvementMetadata'],- 'usage_stats': value['usageStats'],- 'last_activity_at': value['lastActivityAt'] == null ? value['lastActivityAt'] : value['lastActivityAt'].toISOString(),'project': value['project'],'active_eval_set': value['activeEvalSet'],'active_model': value['activeModel'],diff --git a/frontend/src/openapi/models/PatchedConnectorCredentialRequest.ts b/frontend/src/openapi/models/PatchedConnectorCredentialRequest.tsindex 8ffb7f61..115d1425 100644--- a/frontend/src/openapi/models/PatchedConnectorCredentialRequest.ts+++ b/frontend/src/openapi/models/PatchedConnectorCredentialRequest.ts@@ -75,12 +75,6 @@ export interface PatchedConnectorCredentialRequest {* @memberof PatchedConnectorCredentialRequest*/pollIntervalSeconds?: number;- /**- *- * @type {any}- * @memberof PatchedConnectorCredentialRequest- */- capabilityMapping?: any | null;}@@ -110,7 +104,6 @@ export function PatchedConnectorCredentialRequestFromJSONTyped(json: any, ignore'apiSecret': json['api_secret'] == null ? undefined : json['api_secret'],'autoSyncEnabled': json['auto_sync_enabled'] == null ? undefined : json['auto_sync_enabled'],'pollIntervalSeconds': json['poll_interval_seconds'] == null ? undefined : json['poll_interval_seconds'],- 'capabilityMapping': json['capability_mapping'] == null ? undefined : json['capability_mapping'],};}@@ -133,6 +126,5 @@ export function PatchedConnectorCredentialRequestToJSONTyped(value?: PatchedConn'api_secret': value['apiSecret'],'auto_sync_enabled': value['autoSyncEnabled'],'poll_interval_seconds': value['pollIntervalSeconds'],- 'capability_mapping': value['capabilityMapping'],};}diff --git a/frontend/src/openapi/models/PatchedFinetuningJobRequest.ts b/frontend/src/openapi/models/PatchedFinetuningJobRequest.tsindex a71cb9b4..3f96e988 100644--- a/frontend/src/openapi/models/PatchedFinetuningJobRequest.ts+++ b/frontend/src/openapi/models/PatchedFinetuningJobRequest.ts@@ -189,12 +189,6 @@ export interface PatchedFinetuningJobRequest {* @memberof PatchedFinetuningJobRequest*/modelTier?: PatchedFinetuningJobRequestModelTierEnum;- /**- *- * @type {number}- * @memberof PatchedFinetuningJobRequest- */- maxRetries?: number;}@@ -270,7 +264,6 @@ export function PatchedFinetuningJobRequestFromJSONTyped(json: any, ignoreDiscri'hyperparameters': json['hyperparameters'] == null ? undefined : json['hyperparameters'],'groupId': json['group_id'] == null ? undefined : json['group_id'],'modelTier': json['model_tier'] == null ? undefined : json['model_tier'],- 'maxRetries': json['max_retries'] == null ? undefined : json['max_retries'],};}@@ -312,6 +305,5 @@ export function PatchedFinetuningJobRequestToJSONTyped(value?: PatchedFinetuning'hyperparameters': value['hyperparameters'],'group_id': value['groupId'],'model_tier': value['modelTier'],- 'max_retries': value['maxRetries'],};}diff --git a/frontend/src/openapi/models/PatchedProjectRequest.ts b/frontend/src/openapi/models/PatchedProjectRequest.tsindex 4984e766..b0a812b4 100644--- a/frontend/src/openapi/models/PatchedProjectRequest.ts+++ b/frontend/src/openapi/models/PatchedProjectRequest.ts@@ -45,18 +45,6 @@ export interface PatchedProjectRequest {* @memberof PatchedProjectRequest*/integrationType?: IntegrationTypeEnum;- /**- *- * @type {boolean}- * @memberof PatchedProjectRequest- */- isActive?: boolean;- /**- *- * @type {any}- * @memberof PatchedProjectRequest- */- settings?: any | null;}@@ -81,8 +69,6 @@ export function PatchedProjectRequestFromJSONTyped(json: any, ignoreDiscriminato'name': json['name'] == null ? undefined : json['name'],'slug': json['slug'] == null ? undefined : json['slug'],'integrationType': json['integration_type'] == null ? undefined : IntegrationTypeEnumFromJSON(json['integration_type']),- 'isActive': json['is_active'] == null ? undefined : json['is_active'],- 'settings': json['settings'] == null ? undefined : json['settings'],};}@@ -100,7 +86,5 @@ export function PatchedProjectRequestToJSONTyped(value?: PatchedProjectRequest |'name': value['name'],'slug': value['slug'],'integration_type': IntegrationTypeEnumToJSON(value['integrationType']),- 'is_active': value['isActive'],- 'settings': value['settings'],};}diff --git a/frontend/src/openapi/models/Project.ts b/frontend/src/openapi/models/Project.tsindex c4d06e0e..9269515e 100644--- a/frontend/src/openapi/models/Project.ts+++ b/frontend/src/openapi/models/Project.ts@@ -68,13 +68,13 @@ export interface Project {* @type {boolean}* @memberof Project*/- isActive?: boolean;+ readonly isActive: boolean;/**** @type {any}* @memberof Project*/- settings?: any | null;+ readonly settings: any | null;/**** @type {Date}@@ -106,6 +106,8 @@ export function instanceOfProject(value: object): value is Project {if (!('memberEmails' in value) || value['memberEmails'] === undefined) return false;if (!('name' in value) || value['name'] === undefined) return false;if (!('slug' in value) || value['slug'] === undefined) return false;+ if (!('isActive' in value) || value['isActive'] === undefined) return false;+ if (!('settings' in value) || value['settings'] === undefined) return false;if (!('createdAt' in value) || value['createdAt'] === undefined) return false;if (!('updatedAt' in value) || value['updatedAt'] === undefined) return false;if (!('owner' in value) || value['owner'] === undefined) return false;@@ -128,8 +130,8 @@ export function ProjectFromJSONTyped(json: any, ignoreDiscriminator: boolean): P'name': json['name'],'slug': json['slug'],'integrationType': json['integration_type'] == null ? undefined : IntegrationTypeEnumFromJSON(json['integration_type']),- 'isActive': json['is_active'] == null ? undefined : json['is_active'],- 'settings': json['settings'] == null ? undefined : json['settings'],+ 'isActive': json['is_active'],+ 'settings': json['settings'],'createdAt': (new Date(json['created_at'])),'updatedAt': (new Date(json['updated_at'])),'owner': json['owner'],@@ -140,7 +142,7 @@ export function ProjectToJSON(json: any): Project {return ProjectToJSONTyped(json, false);}-export function ProjectToJSONTyped(value?: Omit<Project, 'id'|'member_count'|'member_emails'|'created_at'|'updated_at'|'owner'> | null, ignoreDiscriminator: boolean = false): any {+export function ProjectToJSONTyped(value?: Omit<Project, 'id'|'member_count'|'member_emails'|'is_active'|'settings'|'created_at'|'updated_at'|'owner'> | null, ignoreDiscriminator: boolean = false): any {if (value == null) {return value;}@@ -150,7 +152,5 @@ export function ProjectToJSONTyped(value?: Omit<Project, 'id'|'member_count'|'me'name': value['name'],'slug': value['slug'],'integration_type': IntegrationTypeEnumToJSON(value['integrationType']),- 'is_active': value['isActive'],- 'settings': value['settings'],};}diff --git a/frontend/src/openapi/models/ProjectRequest.ts b/frontend/src/openapi/models/ProjectRequest.tsindex f355cd06..02f738a9 100644--- a/frontend/src/openapi/models/ProjectRequest.ts+++ b/frontend/src/openapi/models/ProjectRequest.ts@@ -45,18 +45,6 @@ export interface ProjectRequest {* @memberof ProjectRequest*/integrationType?: IntegrationTypeEnum;- /**- *- * @type {boolean}- * @memberof ProjectRequest- */- isActive?: boolean;- /**- *- * @type {any}- * @memberof ProjectRequest- */- settings?: any | null;}@@ -83,8 +71,6 @@ export function ProjectRequestFromJSONTyped(json: any, ignoreDiscriminator: bool'name': json['name'],'slug': json['slug'],'integrationType': json['integration_type'] == null ? undefined : IntegrationTypeEnumFromJSON(json['integration_type']),- 'isActive': json['is_active'] == null ? undefined : json['is_active'],- 'settings': json['settings'] == null ? undefined : json['settings'],};}@@ -102,7 +88,5 @@ export function ProjectRequestToJSONTyped(value?: ProjectRequest | null, ignoreD'name': value['name'],'slug': value['slug'],'integration_type': IntegrationTypeEnumToJSON(value['integrationType']),- 'is_active': value['isActive'],- 'settings': value['settings'],};}diff --git a/overbae/api/auth_keys.py b/overbae/api/auth_keys.pyindex 587768f0..2ca511ae 100644--- a/overbae/api/auth_keys.py+++ b/overbae/api/auth_keys.py@@ -22,6 +22,7 @@ class APITokenScopeSerializer(serializers.Serializer):permission = serializers.ListField(child=serializers.ChoiceField(choices=["read", "write"]),required=False,+ allow_empty=False,)def validate(self, data):@@ -36,8 +37,6 @@ class APITokenScopeSerializer(serializers.Serializer):{"resourceIds": "Account scope cannot include resourceIds."})data["permission"] = list(data.get("permission") or ["read", "write"])- if not data["permission"]:- raise serializers.ValidationError({"permission": "Must not be empty."})data["resourceIds"] = resource_idsreturn data@@ -69,6 +68,11 @@ class APITokenCreateRequestSerializer(serializers.Serializer):project = serializers.UUIDField(required=False)scope = APITokenScopeSerializer(required=False)+ def validate(self, data):+ if "project" in data and "scope" in data:+ raise serializers.ValidationError("Send project or scope, not both.")+ return data+class APITokenCreateResponseSerializer(serializers.Serializer):id = serializers.UUIDField()@@ -82,6 +86,16 @@ class APITokenCreateResponseSerializer(serializers.Serializer):created_at = serializers.DateTimeField()+def reachable_keys(request):+ """The caller's keys. A project key manages only the project keys of its own project."""+ keys = APIToken.objects.filter(user=request.user)+ if isinstance(request.auth, APIToken) and not request.auth.is_account_scoped:+ keys = keys.filter(project_id__in=request.auth.allowed_project_ids()).exclude(+ scope__scope="account"+ )+ return keys++class APITokenListCreateView(generics.ListCreateAPIView):permission_classes = [IsAuthenticated]serializer_class = APITokenMetadataSerializer@@ -91,7 +105,7 @@ class APITokenListCreateView(generics.ListCreateAPIView):def get_queryset(self):if getattr(self, "swagger_fake_view", False):return APIToken.objects.none()- return APIToken.objects.filter(user=self.request.user)+ return reachable_keys(self.request)def get_serializer_class(self):if self.request.method == "POST":@@ -219,7 +233,7 @@ class APITokenDestroyView(generics.DestroyAPIView):lookup_field = "id"def get_queryset(self):- return APIToken.objects.filter(user=self.request.user)+ return reachable_keys(self.request)@extend_schema(summary="Revoke API token", description="Permanently revoke an API token.")def delete(self, request, *args, **kwargs):diff --git a/overbae/api/auth_registration.py b/overbae/api/auth_registration.pyindex 0a78b72c..f5fe9c5c 100644--- a/overbae/api/auth_registration.py+++ b/overbae/api/auth_registration.py@@ -1,3 +1,4 @@+import hashlibimport uuidfrom django.db import transaction@@ -6,6 +7,7 @@ from rest_framework import serializers, statusfrom rest_framework.exceptions import APIException, PermissionDeniedfrom rest_framework.permissions import AllowAnyfrom rest_framework.response import Response+from rest_framework.throttling import SimpleRateThrottlefrom rest_framework.views import APIViewfrom rest_framework_simplejwt.tokens import RefreshToken@@ -27,8 +29,20 @@ class InvalidCredentials(APIException):default_code = "authentication_failed"+class LocalSessionThrottle(SimpleRateThrottle):+ # Each attempt checks a password: the limit is what stops guessing one. It counts per+ # address tried, which a client cannot vary the way it can a forwarded-for header.+ rate = "10/minute"+ scope = "local_session"++ def get_cache_key(self, request, view):+ email = str(request.data.get("email") or "").strip().lower()+ ident = hashlib.sha256(email.encode()).hexdigest() if email else self.get_ident(request)+ return self.cache_format % {"scope": self.scope, "ident": ident}++class LocalSessionSerializer(serializers.Serializer):- email = serializers.EmailField()+ email = serializers.EmailField(max_length=254)password = serializers.CharField(write_only=True, min_length=8, max_length=128)def validate_email(self, value):@@ -154,6 +168,7 @@ def local_session(*, email: str, password: str) -> tuple[User, bool]:class LocalSessionView(APIView):authentication_classes: list = []permission_classes = [AllowAny]+ throttle_classes = [LocalSessionThrottle]def post(self, request):serializer = LocalSessionSerializer(data=request.data)diff --git a/overbae/api/billing.py b/overbae/api/billing.pyindex 47b63b73..04407838 100644--- a/overbae/api/billing.py+++ b/overbae/api/billing.py@@ -22,7 +22,7 @@ from overbae.api.serializers import (CreditTopUpConfirmRequestSerializer,CreditTopUpRequestSerializer,)-from overbae.models import BillingService, BillingTelemetry+from overbae.models import APIToken, BillingService, BillingTelemetryfrom overbae.services.billing_ledger import account_payloadfrom overbae.services.credit_purchases import (WEBHOOK_EVENTS,@@ -69,9 +69,12 @@ class BillingLedgerView(generics.ListAPIView):return self.list(request, *args, **kwargs)def get_queryset(self):+ rows = BillingTelemetry.objects.filter(user=self.request.user)+ if isinstance(self.request.auth, APIToken) and not self.request.auth.is_account_scoped:+ # A project key reads its project's entries, not the whole account's.+ rows = rows.filter(project_id__in=self.request.auth.allowed_project_ids())return (- BillingTelemetry.objects.filter(user=self.request.user)- .select_related("project")+ rows.select_related("project").annotate(service_name=Case(*[diff --git a/overbae/api/completions.py b/overbae/api/completions.pyindex cee4ff9b..69e15a44 100644--- a/overbae/api/completions.py+++ b/overbae/api/completions.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport jsonimport logging+import mathimport timeimport uuidfrom decimal import Decimal@@ -369,6 +370,8 @@ def chat_completions(request: Request) -> Response | StreamingHttpResponse:stream = bool(data.get("stream", False))try:temperature = float(data.get("temperature", 1.0) or 0.0)+ if not math.isfinite(temperature):+ raise ValueError("temperature")max_tokens = reserve_output(data)["max_tokens"]except (TypeError, ValueError):return Response(@@ -386,7 +389,7 @@ def chat_completions(request: Request) -> Response | StreamingHttpResponse:{"error": {"message": "model is required.", "type": "invalid_request_error"}},status=status.HTTP_400_BAD_REQUEST,)- if not messages:+ if not messages or not isinstance(messages, list):return Response({"error": {"message": "messages is required.", "type": "invalid_request_error"}},status=status.HTTP_400_BAD_REQUEST,diff --git a/overbae/api/exception_handler.py b/overbae/api/exception_handler.pyindex e0738b7f..1f4db896 100644--- a/overbae/api/exception_handler.py+++ b/overbae/api/exception_handler.py@@ -11,6 +11,7 @@ import loggingimport uuidfrom django.conf import settings+from django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.db import IntegrityErrorfrom rest_framework import statusfrom rest_framework.response import Response@@ -38,6 +39,13 @@ def api_exception_handler(exc, context):view = context.get("view")view_name = type(view).__name__ if view is not None else "unknown view"+ # A lookup with a value its column cannot hold, such as ``filter(pk="not-a-uuid")``.+ if isinstance(exc, DjangoValidationError):+ return Response(+ {"detail": "A value in this request is not valid.", "code": "invalid"},+ status=status.HTTP_400_BAD_REQUEST,+ )+if isinstance(exc, IntegrityError):logger.warning("IntegrityError in %s: %s", view_name, exc)return Response(diff --git a/overbae/api/filters.py b/overbae/api/filters.pyindex 94afd05e..5667366e 100644--- a/overbae/api/filters.py+++ b/overbae/api/filters.py@@ -155,7 +155,6 @@ class SpanFilter(LLMActivityFilterMixin, filters.FilterSet):total_cost__gte = filters.NumberFilter(method="filter_total_cost_gte")total_cost__lte = filters.NumberFilter(method="filter_total_cost_lte")all_spans = filters.BooleanFilter(method="filter_all_spans")- project_id = filters.NumberFilter(field_name="project_id", lookup_expr="exact")session = filters.UUIDFilter(field_name="conversation_id")# The model lives in child-span ``attributes``, so match trace ids first.model = filters.CharFilter(method="filter_model")diff --git a/overbae/api/otlp.py b/overbae/api/otlp.pyindex d8cf3460..33ba1b5e 100644--- a/overbae/api/otlp.py+++ b/overbae/api/otlp.py@@ -9,11 +9,12 @@ from __future__ import annotationsimport base64import jsonimport logging+import uuidimport zlib-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Any-from django.db import transaction+from django.db import DataError, transactionfrom django.http import HttpResponseBase, JsonResponsefrom django.utils import timezonefrom drf_spectacular.utils import extend_schema@@ -21,6 +22,7 @@ from google.protobuf import json_formatfrom opentelemetry.proto.collector.trace.v1 import trace_service_pb2from opentelemetry.proto.trace.v1.trace_pb2 import ResourceSpansfrom rest_framework.decorators import api_view, permission_classes+from rest_framework.exceptions import PermissionDeniedfrom rest_framework.permissions import IsAuthenticatedfrom overbae.api import overmind_attrs as oc_attrs@@ -61,6 +63,8 @@ def _get_attr(mapping: dict[str, Any] | None, primary: str, *legacy: str) -> Any# OTel marks "no parent" with eight zero bytes._EMPTY_PARENT_SPAN_ID = b"\x00" * 8+# An end time this far ahead of the server clock is not used as the last activity.+_CLOCK_SKEW = timedelta(minutes=5)def _any_value_to_python(value) -> Any:@@ -204,7 +208,7 @@ def _classify_span_type(span_name: str, attrs: dict[str, Any]) -> str:if oi_kind in _OPENINFERENCE_SPAN_TYPES:return _OPENINFERENCE_SPAN_TYPES[oi_kind]- op = (attrs.get("gen_ai.operation.name") or "").strip().lower()+ op = str(attrs.get("gen_ai.operation.name") or "").strip().lower()if op == "execute_tool" or attrs.get(oc_attrs.TOOL_NAME):return Span.SpanType.TOOL_CALL@@ -226,19 +230,23 @@ def _operation_from(span_proto, attrs: dict[str, Any]) -> str:def resolve_project_for_ingest(request, resource_attrs: dict[str, Any]) -> Project | None:- """Project-scoped keys pin ingest; account keys and sessions resolve from attrs or membership."""+ """Project-scoped keys pin ingest; account keys and sessions resolve from attrs or membership.+ A named project the caller cannot reach is refused, never replaced by another one."""if isinstance(request.auth, APIToken) and not request.auth.is_account_scoped:return request.auth.projectexplicit_id = _get_attr(resource_attrs, oc_attrs.PROJECT_ID, "overmind.project_id")if explicit_id:try:- project = Project.objects.get(id=explicit_id)- except Project.DoesNotExist:- project = None- else:- if ProjectMembership.objects.filter(user=request.user, project=project).exists():- return project+ project_id = uuid.UUID(str(explicit_id))+ except ValueError:+ raise PermissionDenied("Project access denied.") from None+ project = Project.objects.filter(+ id=project_id, id__in=project_ids_for(request.user, request.auth)+ ).first()+ if project is None:+ raise PermissionDenied("Project access denied.")+ return projectmembership = (ProjectMembership.objects.filter(user=request.user)@@ -354,7 +362,7 @@ def _find_existing_capability_for_trace(trace_id: str, project: Project) -> Capa)if len(capability_ids) != 1:return None- return Capability.objects.filter(pk=capability_ids[0], project=project).first()+ return Capability.objects.filter(pk=capability_ids[0], project=project).current().first()def _resolve_capability(@@ -379,7 +387,7 @@ def _resolve_capability(for probe in (span_level_id, resource_id):if not probe:continue- resolved = identity.lookup(project.id, str(probe))+ resolved = identity.lookup_id(project.id, str(probe))if resolved is not None:return resolvedif tagged_id or resource_id:@@ -509,6 +517,9 @@ def _apply_runtime_summaries(if span.end_time_ns:end_dt = datetime.fromtimestamp(span.end_time_ns / 1_000_000_000, tz=UTC)+ # ``last_activity_at`` only moves forward: one span from a clock ahead would pin it.+ if end_dt > timezone.now() + _CLOCK_SKEW:+ return dirtyif capability.last_activity_at is None or end_dt > capability.last_activity_at:capability.last_activity_at = end_dtdirty = True@@ -536,7 +547,14 @@ def process_span(span_id: str, project_id: str | None = None):with transaction.atomic():capability = _resolve_capability(project, resource_attrs, overmind_tags)- if capability is None:+ named = any(+ attrs.get(key)+ for attrs in (resource_attrs, overmind_tags)+ for key in (oc_attrs.CAPABILITY_ID, oc_attrs.CAPABILITY_NAME)+ )+ # Only a span that names no capability joins its trace's: one that names another+ # stays unbound rather than bound to the wrong one.+ if capability is None and not named:capability = _find_existing_capability_for_trace(span.trace_id, project)if capability is not None:dirty = _record_cli_version(capability, span.scope_version)@@ -578,7 +596,7 @@ def _build_span() -> Span:start = span_proto.start_time_unix_nanoend = span_proto.end_time_unix_nano- duration = end - start if end and start else 0+ duration = max(end - start, 0) if end and start else 0attrs = _coalesce_genai_attrs(_kv_list_to_dict(span_proto.attributes))stamp_span_cost(attrs, start_time_ns=start)@@ -758,11 +776,14 @@ def otlp_traces(request):continueall_spans.extend(spans)- rejected = 0+ storable = [span for span in all_spans if _storable(span)]+ rejected = len(all_spans) - len(storable)+ all_spans = storableunscored: list[Span] = []if all_spans:with transaction.atomic():- all_spans, unscored, rejected = _persist_owned_spans(all_spans)+ all_spans, unscored, refused = _persist_storable_spans(all_spans)+ rejected += refusedfor project_id in {span.project_id for span in all_spans}:record(@@ -793,6 +814,42 @@ def otlp_traces(request):)+_TEXT_FIELDS = (+ "name",+ "span_type",+ "operation",+ "status_message",+ "service_name",+ "scope_name",+ "scope_version",+)+++def _storable(span: Span) -> bool:+ """span_id is the primary key across projects: an absent or all-zero id would make one+ row every exporter overwrites. PostgreSQL text holds no NUL byte."""+ return bool(+ span.span_id.strip("0")+ and span.trace_id.strip("0")+ and not any("\x00" in getattr(span, field) for field in _TEXT_FIELDS)+ )+++def _persist_storable_spans(spans: list[Span]) -> tuple[list[Span], list[Span], int]:+ """A span whose JSON PostgreSQL refuses (a NUL escape) is rejected alone: the batch is+ retried in halves until only refused spans are left out."""+ try:+ with transaction.atomic():+ return _persist_owned_spans(spans)+ except DataError:+ if len(spans) == 1:+ return [], [], 1+ middle = len(spans) // 2+ kept, unscored, rejected = _persist_storable_spans(spans[:middle])+ more, pending, refused = _persist_storable_spans(spans[middle:])+ return kept + more, unscored + pending, rejected + refused++def _persist_owned_spans(spans: list[Span]) -> tuple[list[Span], list[Span], int]:"""``span_id`` is the primary key across projects. Insert-or-skip, then update onlyrows this batch's project owns, so a concurrent first writer keeps its span.diff --git a/overbae/api/serializers.py b/overbae/api/serializers.pyindex c58a1d4b..e9bdf073 100644--- a/overbae/api/serializers.py+++ b/overbae/api/serializers.py@@ -1,4 +1,5 @@import logging+import mathfrom datetime import timedeltafrom types import SimpleNamespace@@ -61,6 +62,7 @@ from overbae.services.training_contract import (contract,dataset_objective,validate_effective_batch,+ validate_numbers,)from overbae.services.training_monitoring import resolve as resolve_monitoring_policyfrom overbae.services.training_policies import profile_options@@ -71,14 +73,17 @@ logger = logging.getLogger(__name__)def _first_float(attrs: dict, *keys: str) -> float | None:+ """The first finite number among ``keys``; exporters send text such as "n/a" or "1e999"."""for key in keys:raw = attrs.get(key)if raw in (None, ""):continuetry:- return float(raw)+ value = float(raw)except (TypeError, ValueError):continue+ if math.isfinite(value):+ return valuereturn None@@ -145,15 +150,9 @@ def _total_cost_from_span_attributes(attrs: dict | None) -> float | None:what cost filters threshold against."""if not attrs:return None- for key in ("cost", "response_cost", "gen_ai.usage.cost", "genai.cost", "overmind.cost"):- raw = attrs.get(key)- if raw is None or raw == "":- continue- try:- return float(raw)- except (TypeError, ValueError):- continue- return None+ return _first_float(+ attrs, "cost", "response_cost", "gen_ai.usage.cost", "genai.cost", "overmind.cost"+ )def _spans_with_usage(*, project_ids, **field_in):@@ -218,6 +217,15 @@ def _leaf_usage_rows(rows) -> list[tuple]:return [(entry[0], entry[1], entry[7]) for _idx, entry in surviving]+def span_usage(attrs: dict | None) -> dict:+ """One span's own usage, by the same keys :func:`trace_usage_totals` sums."""+ return {+ "total_tokens": _total_tokens_from_span_attributes(attrs),+ "total_cost": _total_cost_from_span_attributes(attrs),+ "model": _model_from_span_attributes(attrs),+ }++def trace_usage_totals(project_ids, trace_ids: list[str]) -> dict[str, dict]:"""Summed across ALL spans in one query: usage lives on child LLM spans, notthe root. ``None`` (never a fabricated ``0``) when no span reported a metric;@@ -351,7 +359,8 @@ class ProjectSerializer(serializers.ModelSerializer):class Meta:model = Projectfields = "__all__"- read_only_fields = ["id", "owner", "created_at", "updated_at"]+ # Server-owned: workers and MCP gate on ``is_active``; sync writes ``settings``.+ read_only_fields = ["id", "owner", "is_active", "settings", "created_at", "updated_at"]# ``_unique_project_slug`` resolves collisions; the auto# ``UniqueTogetherValidator`` would hard-400 them first.validators = []@@ -403,11 +412,11 @@ class ProjectInviteSerializer(serializers.ModelSerializer):class ProjectInviteCreateSerializer(serializers.Serializer):- email = serializers.EmailField(required=True)+ email = serializers.EmailField(required=True, max_length=254)class ProjectMembershipCreateSerializer(serializers.Serializer):- email = serializers.EmailField(required=True)+ email = serializers.EmailField(required=True, max_length=254)def get_user(self) -> User:email = self.validated_data.get("email", "").strip().lower()@@ -733,6 +742,10 @@ class CapabilitySerializer(serializers.ModelSerializer):"slug","created_at","updated_at",+ # Measured by ingest; ``observed`` decides whether a scan may retire the row.+ "usage_stats",+ "last_activity_at",+ "observed","previous_active_model","active_model_activated_at","first_application_request_at",@@ -770,6 +783,9 @@ class CapabilitySerializer(serializers.ModelSerializer):return build_capability_flow(obj)def validate_project(self, value):+ # A capability stays in its project: its spans, eval sets and models live there.+ if self.instance is not None and value != self.instance.project:+ raise serializers.ValidationError("A capability cannot move to another project.")return _validate_project_ownership(self, value)def validate_active_model(self, value):@@ -789,6 +805,12 @@ class CapabilitySerializer(serializers.ModelSerializer):)return value+ def validate_active_eval_set(self, value):+ project_id = self.instance.project_id if self.instance else self.initial_data.get("project")+ if value is not None and str(value.project_id) != str(project_id):+ raise serializers.ValidationError("The eval set must belong to this project.")+ return value+def validate_benchmark_model(self, value):if value is None:return value@@ -1365,6 +1387,7 @@ class FinetuningJobSerializer(serializers.ModelSerializer):"result","error_message","retry_count",+ "max_retries","celery_task_id","cost_usd","billed_minutes",@@ -1399,6 +1422,10 @@ class FinetuningJobSerializer(serializers.ModelSerializer):def validate_hyperparameters(self, value):if not isinstance(value, dict):raise serializers.ValidationError("Use a JSON object for hyperparameters.")+ try:+ validate_numbers(value)+ except InputValidationError as exc:+ raise serializers.ValidationError(exc.detail) from excif settings.FINETUNING_BACKEND == "modal":try:validate_effective_batch(value)@@ -1574,6 +1601,17 @@ class FinetuningJobSerializer(serializers.ModelSerializer):validation_dataset = attrs.get("validation_dataset")if "validation_dataset" not in attrs and self.instance is not None:validation_dataset = self.instance.validation_dataset+ eval_dataset = attrs.get("eval_dataset") or getattr(self.instance, "eval_dataset", None)+ # A version is checked through its dataset, and the dataset against the project:+ # alone, any project's version would be accepted and echoed back.+ for cell_field, owner in (+ ("validation_cell", validation_dataset),+ ("eval_cell", eval_dataset),+ ):+ if attrs.get(cell_field) is not None and owner is None:+ raise serializers.ValidationError(+ {cell_field: "Send the dataset this version belongs to."}+ )if dataset and project and dataset.project_id != project.id:raise serializers.ValidationError(@@ -2063,6 +2101,15 @@ class FinetuningEstimateRequestSerializer(serializers.Serializer):n_epochs = serializers.IntegerField(min_value=1)use_lora = serializers.BooleanField()+ def validate_hyperparameters(self, value):+ if not isinstance(value, dict):+ raise serializers.ValidationError("Use a JSON object for hyperparameters.")+ try:+ validate_numbers(value)+ except InputValidationError as exc:+ raise serializers.ValidationError(exc.detail) from exc+ return value+class FinetuningModelDefaultsRequestSerializer(serializers.Serializer):dataset_id = serializers.UUIDField()@@ -2184,9 +2231,13 @@ class ConnectorActiveConfigSerializer(serializers.Serializer):class ConnectorSyncConfigWriteSerializer(serializers.Serializer):- source_project_id = serializers.CharField(required=False, allow_blank=True, default="")+ source_project_id = serializers.CharField(+ required=False, allow_blank=True, default="", max_length=128+ )target_project_id = serializers.UUIDField(required=False, allow_null=True)- lookback_days = serializers.IntegerField(required=False, allow_null=True)+ lookback_days = serializers.IntegerField(+ required=False, allow_null=True, min_value=1, max_value=365+ )backfill_from = serializers.DateTimeField(required=False, allow_null=True)backfill_to = serializers.DateTimeField(required=False, allow_null=True)@@ -2206,7 +2257,9 @@ class ConnectorSyncConfigCreateResponseSerializer(serializers.Serializer):class ConnectorPreviewRequestSerializer(serializers.Serializer):- lookback_days = serializers.IntegerField(required=False, allow_null=True)+ lookback_days = serializers.IntegerField(+ required=False, allow_null=True, min_value=1, max_value=365+ )source_project_id = serializers.CharField(required=False, allow_blank=True, default="")backfill_from = serializers.DateTimeField(required=False, allow_null=True)backfill_to = serializers.DateTimeField(required=False, allow_null=True)@@ -2360,6 +2413,8 @@ class ConnectorCredentialSerializer(serializers.ModelSerializer):"total_spans_imported","total_traces_imported","next_poll_at",+ # Written by the capability-mapping action, which resolves its targets and relabels.+ "capability_mapping","active_config",]# Only connected integrations own a name; a soft-disconnected row (kept@@ -2412,6 +2467,27 @@ class ConnectorCredentialSerializer(serializers.ModelSerializer):def validate_poll_interval_seconds(self, value: int) -> int:return max(60, min(value, 86400))+ def validate(self, attrs):+ """A stored secret goes only to the vendor and host it was entered for."""+ stored = self.instance+ if stored is None:+ return attrs+ if attrs.get("connector_type", stored.connector_type) != stored.connector_type:+ raise serializers.ValidationError(+ {"connector_type": "Create a new connector for another provider."}+ )+ moved = "base_url" in attrs and self._normalize_base_url(+ attrs["base_url"]+ ) != self._normalize_base_url(stored.base_url)+ reentered = bool(attrs.get("api_key")) and bool(+ attrs.get("api_secret") or not stored.api_secret+ )+ if moved and not reentered:+ raise serializers.ValidationError(+ {"base_url": "Enter the provider credentials again to change the host."}+ )+ return attrs+def _apply_credential_fields(self, instance: ConnectorCredential, validated_data: dict) -> None:"""Write api_key / api_secret only when non-blank values are provided."""api_key = validated_data.pop("api_key", None)diff --git a/overbae/api/span_ordering.py b/overbae/api/span_ordering.pyindex 64e87ddd..2766612a 100644--- a/overbae/api/span_ordering.py+++ b/overbae/api/span_ordering.py@@ -81,7 +81,12 @@ def _text_expr(attrs: str, key: str) -> str:def _numeric_expr(attrs: str, key: str) -> str:if connection.vendor == "postgresql":- return f"NULLIF({attrs}->>'{key}','')::double precision"+ # Attribute text is whatever an exporter sent: casting "n/a" or "1e999" fails the query.+ text = f"{attrs}->>'{key}'"+ return (+ f"CASE WHEN {text} ~ '^[-+]?([0-9]{{1,15}}([.][0-9]*)?|[.][0-9]+)"+ f"([eE][-+]?[0-9]{{1,2}})?$' THEN ({text})::double precision END"+ )return f"CAST(json_extract({attrs}, '$.\"{key}\"') AS REAL)"diff --git a/overbae/api/sync.py b/overbae/api/sync.pyindex c6a1e7c2..5397e650 100644--- a/overbae/api/sync.py+++ b/overbae/api/sync.py@@ -10,6 +10,7 @@ from rest_framework.views import APIViewfrom overbae.api.authentication import APITokenBackendfrom overbae.api.scoping import project_ids_for+from overbae.core.errors import InputValidationErrorfrom overbae.innermind import checksfrom overbae.models import APIToken, Projectfrom overbae.services.sync import apply_snapshot, snapshot_of@@ -38,12 +39,12 @@ class DeclaredExpectationSerializer(serializers.Serializer):class CapabilitySerializer(serializers.Serializer):id = serializers.UUIDField(required=False, allow_null=True)- slug = serializers.SlugField()- name = serializers.CharField()+ slug = serializers.SlugField(max_length=255)+ name = serializers.CharField(max_length=255)description = serializers.CharField(required=False, allow_blank=True)- entrypoint_fn = serializers.CharField(required=False, allow_blank=True)- model = serializers.CharField(required=False, allow_blank=True)- source_path = serializers.CharField(required=False, allow_blank=True)+ entrypoint_fn = serializers.CharField(required=False, allow_blank=True, max_length=255)+ model = serializers.CharField(required=False, allow_blank=True, max_length=128)+ source_path = serializers.CharField(required=False, allow_blank=True, max_length=512)system_prompt = serializers.CharField(required=False, allow_blank=True)tools_summary = serializers.CharField(required=False, allow_blank=True)decision_logic = serializers.CharField(required=False, allow_blank=True)@@ -89,6 +90,14 @@ class SyncSnapshotSerializer(serializers.Serializer):last_synced_at = serializers.DateTimeField(read_only=True, allow_null=True)capabilities = CapabilitySerializer(many=True)+ def validate_capabilities(self, capabilities):+ # Two blocks naming one row would be folded into it, the last one winning.+ for field in ("slug", "id"):+ named = [body[field] for body in capabilities if body.get(field)]+ if len(named) != len(set(named)):+ raise serializers.ValidationError(f"Each capability {field} may appear once.")+ return capabilities+class SyncView(APIView):"""Two-way ``overmind.toml`` sync.@@ -139,7 +148,10 @@ class SyncView(APIView):project = _project_for(request, data["project_id"])if isinstance(project, Response):return project- applied = apply_snapshot(project, data)+ try:+ applied = apply_snapshot(project, data)+ except InputValidationError as exc:+ raise serializers.ValidationError({"capabilities": exc.detail}) from excreturn Response(SyncSnapshotSerializer(snapshot_of(project, capabilities=applied)).data)diff --git a/overbae/api/views.py b/overbae/api/views.pyindex df474750..b80a2092 100644--- a/overbae/api/views.py+++ b/overbae/api/views.py@@ -175,8 +175,11 @@ class ProjectViewSet(viewsets.ModelViewSet):def get_queryset(self):if getattr(self, "swagger_fake_view", False):return Project.objects.none()+ # A deactivated project is hidden here as it is from MCP.return (- Project.objects.filter(id__in=project_ids_for(self.request.user, self.request.auth))+ Project.objects.filter(+ id__in=project_ids_for(self.request.user, self.request.auth), is_active=True+ ).annotate(member_count=Count("memberships")).prefetch_related("memberships__user"))@@ -795,6 +798,15 @@ class FinetuningJobViewSet(viewsets.ModelViewSet):returnFinetuningJob.objects.filter(pk=job.pk).update(celery_task_id=result.id)+ @transaction.atomic+ def perform_destroy(self, instance):+ # A run still working holds a GPU and meters it; deleting the row would orphan both.+ # Read under the row lock: a retry may have queued it since the page loaded.+ held = FinetuningJob.objects.select_for_update().get(pk=instance.pk)+ if not held.is_terminal and held.status != FinetuningJob.Status.AWAITING_LAUNCH:+ raise drf_serializers.ValidationError({"detail": "Cancel the run before deleting it."})+ held.delete()+@extend_schema(summary="List training runs — whole runs per page",description=(@@ -1623,6 +1635,10 @@ class ConnectorCredentialViewSet(viewsets.ModelViewSet):rotated = bool(data.get("api_key") or data.get("api_secret"))from overbae.services.connectors import get_adapter, registered_sources+ # New credentials or a new host start a sync, which writes into every import target.+ if {"api_key", "api_secret", "base_url"} & set(data):+ self._importing_credential()+if rotated and instance.connector_type in registered_sources():from copy import copy@@ -1641,11 +1657,28 @@ class ConnectorCredentialViewSet(viewsets.ModelViewSet):ConnectorCredential.objects.filter(pk=credential.pk).update(sync_error="", sync_retry_count=0)- if credential.auto_sync_enabled and ({"api_key", "api_secret", "base_url"} & changed):+ if (+ credential.auto_sync_enabled+ and credential.active_config() is not None+ and ({"api_key", "api_secret", "base_url"} & changed)+ ):from overbae.services.connectors.sync import enqueue_connector_syncenqueue_connector_sync(credential)+ def _importing_credential(self):+ """For actions that write or delete imported spans: those land in every project+ the connector imports into, and this caller must reach each one."""+ from overbae.services.connectors.sync import import_projects++ credential = self.get_object()+ reachable = set(project_ids_for(self.request.user, self.request.auth))+ if not import_projects(credential) <= reachable:+ raise PermissionDenied(+ "This connector imports into a project this credential cannot reach."+ )+ return credential+@extend_schema(summary="Trigger a background sync for this connector now",request=None,@@ -1655,7 +1688,10 @@ class ConnectorCredentialViewSet(viewsets.ModelViewSet):def sync(self, request, id=None):from overbae.services.connectors.sync import enqueue_connector_sync- enqueue_connector_sync(self.get_object())+ try:+ enqueue_connector_sync(self._importing_credential())+ except InputValidationError as exc:+ raise drf_serializers.ValidationError({"detail": exc.detail}) from excreturn Response({"status": "queued"}, status=status.HTTP_202_ACCEPTED)@extend_schema(@@ -1707,7 +1743,7 @@ class ConnectorCredentialViewSet(viewsets.ModelViewSet):)@action(detail=True, methods=["post"], url_path="config")def config(self, request, id=None):- credential = self.get_object()+ credential = self._importing_credential()from overbae.services.connectors.feedforward import save_sync_configwrite = ConnectorSyncConfigWriteSerializer(data=request.data)@@ -1816,7 +1852,12 @@ class ConnectorCredentialViewSet(viewsets.ModelViewSet):key = request.query_params.get("key") or mapping.get("key")raw_lookback = request.query_params.get("lookback_days")if raw_lookback is not None and str(raw_lookback).strip() != "":- lookback_days = max(1, min(int(raw_lookback), 365))+ try:+ lookback_days = max(1, min(int(raw_lookback), 365))+ except ValueError:+ raise drf_serializers.ValidationError(+ {"lookback_days": "A valid integer is required."}+ ) from Noneelse:cfg = credential.active_config()lookback_days = (cfg.lookback_days if cfg and cfg.lookback_days else None) or 30@@ -1863,16 +1904,19 @@ class ConnectorCredentialViewSet(viewsets.ModelViewSet):capability_source_error,relabel_connector_capabilities,)+ from overbae.services.connectors.capabilities import resolve_mapping_targets- credential = self.get_object()+ credential = self._importing_credential()write = ConnectorCapabilityMappingWriteSerializer(data=request.data)write.is_valid(raise_exception=True)mapping = {k: v for k, v in write.validated_data.items() if v is not None}unsupported = capability_source_error(credential.connector_type, mapping.get("source"))if unsupported:return Response({"source": [unsupported]}, status=status.HTTP_400_BAD_REQUEST)- if "fallback_capability_id" in mapping:- mapping["fallback_capability_id"] = str(mapping["fallback_capability_id"])+ try:+ mapping = resolve_mapping_targets(credential.project, mapping)+ except InputValidationError as exc:+ raise drf_serializers.ValidationError({"assignments": exc.detail}) from exccredential.capability_mapping = mappingcredential.pending_capability_mapping = {}credential.capability_mapping_confirmed = Truediff --git a/overbae/core/utils.py b/overbae/core/utils.pyindex 2e7eca96..e693f0d6 100644--- a/overbae/core/utils.py+++ b/overbae/core/utils.py@@ -15,7 +15,7 @@ def fingerprint(value: Any) -> str:def safe_int(val, default: int = 0) -> int:try:return int(float(val))- except (TypeError, ValueError):+ except (TypeError, ValueError, OverflowError):return defaultdiff --git a/overbae/innermind/comparison.py b/overbae/innermind/comparison.pyindex 2b8c198f..2d8d3a8a 100644--- a/overbae/innermind/comparison.py+++ b/overbae/innermind/comparison.py@@ -14,8 +14,10 @@ REGRESSED = "regressed"UNCHANGED = "unchanged"ADDED = "added"REMOVED = "removed"+# Neither run has a paired score: there is nothing to call unchanged.+UNMEASURED = "unmeasured"# Attention order: regressions and lost coverage first, then gains, then noise.-STATUS_ORDER = {REGRESSED: 0, REMOVED: 1, ADDED: 2, IMPROVED: 3, UNCHANGED: 4}+STATUS_ORDER = {REGRESSED: 0, REMOVED: 1, ADDED: 2, IMPROVED: 3, UNCHANGED: 4, UNMEASURED: 5}def headline(summary: dict | None) -> float | None:@@ -28,7 +30,7 @@ def classify(baseline: float | None, candidate: float | None) -> tuple[float | Nif candidate is None and baseline is not None:return None, REMOVEDif candidate is None and baseline is None:- return None, UNCHANGED+ return None, UNMEASUREDdelta = candidate - baselineif delta > EPSILON:return delta, IMPROVEDdiff --git a/overbae/innermind/deterministic.py b/overbae/innermind/deterministic.pyindex 7336c158..f267b388 100644--- a/overbae/innermind/deterministic.py+++ b/overbae/innermind/deterministic.py@@ -93,6 +93,20 @@ FORBIDDEN_ATTRS = frozenset("popen","spawn","fork",+ # A traceback, generator or coroutine leads to the runner's own frames.+ "tb_frame",+ "tb_next",+ "gi_frame",+ "gi_code",+ "cr_frame",+ "cr_code",+ "ag_frame",+ "ag_code",+ "f_back",+ "f_builtins",+ "f_globals",+ "f_locals",+ "f_code",})@@ -365,9 +379,12 @@ def audit(source: str) -> str | None:for node in ast.walk(tree):if isinstance(node, (ast.Import, ast.ImportFrom)):violations.append("import is not allowed")- elif isinstance(node, ast.Attribute):- if node.attr.startswith("_") or node.attr in FORBIDDEN_ATTRS:- violations.append(f"attribute {node.attr!r} is not allowed")+ elif isinstance(node, (ast.Attribute, ast.MatchClass)):+ # A class pattern reads attributes by keyword: the same access, other syntax.+ names = [node.attr] if isinstance(node, ast.Attribute) else node.kwd_attrs+ for name in names:+ if name.startswith("_") or name in FORBIDDEN_ATTRS:+ violations.append(f"attribute {name!r} is not allowed")elif isinstance(node, ast.Name) and node.id.startswith("_"):violations.append(f"name {node.id!r} is not allowed")elif isinstance(node, ast.JoinedStr):diff --git a/overbae/innermind/evals.py b/overbae/innermind/evals.pyindex 8a035c45..dd83bf27 100644--- a/overbae/innermind/evals.py+++ b/overbae/innermind/evals.py@@ -12,6 +12,7 @@ from overbae.core.model_registry import TaskType, model_chain, resolve_modelfrom overbae.innermind import deterministic, evidencefrom overbae.innermind.metrics import REASON_BELOW, Metricfrom overbae.models import EvalMatrix, Span+from overbae.services.transcripts.envelope import MAX_EXPECTATIONSlogger = logging.getLogger(__name__)@@ -56,12 +57,15 @@ def matches(row: EvalMatrix, span: Span) -> bool:def expectation_rows(span: Span) -> list[EvalMatrix]:return [EvalMatrix(name=expectation, type=EvalMatrix.Type.LLM, source=expectation)- for expectation in dict.fromkeys(- [- *evidence.read_expectations(span.attributes or {}),- *evidence.declared_constraints(span),- ]- )+ # Each one is a judge call the platform pays for: the cap holds for both sources.+ for expectation in list(+ dict.fromkeys(+ [+ *evidence.read_expectations(span.attributes or {}),+ *evidence.declared_constraints(span),+ ]+ )+ )[:MAX_EXPECTATIONS]]diff --git a/overbae/innermind/evidence.py b/overbae/innermind/evidence.pyindex 3e37b6d1..195ebcd7 100644--- a/overbae/innermind/evidence.py+++ b/overbae/innermind/evidence.py@@ -15,7 +15,7 @@ from typing import Anyfrom overbae.models import Spanfrom overbae.models.traces import is_tool_operationfrom overbae.services.transcripts import chatml-from overbae.services.transcripts.envelope import extract_envelope+from overbae.services.transcripts.envelope import MAX_EXPECTATIONS, extract_envelopefrom overbae.services.transcripts.span_evidence import unwrap_payloadARG_PREFIX = "overmind.arg."@@ -155,7 +155,9 @@ def read_expectations(attributes: dict) -> list[str]:if isinstance(value, str):value = [value]if isinstance(value, (list, tuple)):- return [item.strip() for item in value if isinstance(item, str) and item.strip()]+ # Each one is a judge call the platform pays for; events are capped the same way.+ texts = [item.strip() for item in value if isinstance(item, str) and item.strip()]+ return texts[:MAX_EXPECTATIONS]expect = first_text(attributes, "overmind.expect", "expect")return [expect] if expect else []diff --git a/overbae/innermind/instrumentation.py b/overbae/innermind/instrumentation.pyindex 75315c47..0cc26afd 100644--- a/overbae/innermind/instrumentation.py+++ b/overbae/innermind/instrumentation.py@@ -131,7 +131,7 @@ def build_spans(project_id, payload: list[dict]) -> tuple[list[Span], list[dict]def resolve_identity(project_id, span: Span) -> Capability | None:for attrs in (span.attributes or {}, span.resource_attrs or {}):if found := attrs.get(oc_attrs.CAPABILITY_ID):- return identity.lookup(project_id, str(found))+ return identity.lookup_id(project_id, str(found))return Nonediff --git a/overbae/innermind/signals.py b/overbae/innermind/signals.pyindex 1010bc68..5772602a 100644--- a/overbae/innermind/signals.py+++ b/overbae/innermind/signals.py@@ -489,7 +489,9 @@ class LeakSignal(Signal):"api key": re.compile(r"\b(?:sk-[A-Za-z0-9_-]{20,}|phx_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{36})\b"),- "email": re.compile(r"\b[\w.+-]+@[\w-]+\.[A-Za-z]{2,}\b"),+ # Possessive and anchored on the left: the plain form rescans every suffix of a+ # long dotted run, which took minutes and stalled live scoring.+ "email": re.compile(r"(?<![\w.+-])[\w.+-]++@[\w-]+\.[A-Za-z]{2,}\b"),"card number": re.compile(r"\b(?:\d[ -]?){13,15}\d\b"),}@@ -614,6 +616,8 @@ class SignalFactory:if signal_type not in self.signals:raise ValueError(f"Unknown signal type: {signal_type}")cls = self.signals[signal_type]+ if not isinstance(config, dict):+ raise ValueError("config must be an object.")for key, value in config.items():if key not in cls.params:raise ValueError(f"'{signal_type}' has no parameter '{key}'.")diff --git a/overbae/innermind/trajectory.py b/overbae/innermind/trajectory.pyindex f6ea83fe..708655d1 100644--- a/overbae/innermind/trajectory.py+++ b/overbae/innermind/trajectory.py@@ -96,16 +96,21 @@ class EfficiencyEvaluator(TrajectoryEvaluator):for i, span in enumerate(spans))llm_calls = [span for span in spans if evidence.is_llm(span)]- tokens = sum(evidence.tokens(span) or 0 for span in llm_calls)- cost = sum(evidence.cost(span) or 0 for span in llm_calls)+ tokens = [n for span in llm_calls if (n := evidence.tokens(span)) is not None]+ cost = [n for span in llm_calls if (n := evidence.cost(span)) is not None]seconds = sum(evidence.seconds(span) for span in llm_calls)+ # Usage no span reported is left out: "0 tokens, $0" would read as a measurement.+ measured = [+ f"{redundant} redundant calls",+ f"{unrecovered} unrecovered errors",+ *([f"{sum(tokens):g} tokens"] if tokens else []),+ *([f"${sum(cost):g}"] if cost else []),+ f"{seconds:g}s in LLM calls",+ ]return Metric(self.expectation,score=max(0.0, 1 - (redundant + unrecovered) / len(spans)),- reason=(- f"{redundant} redundant calls, {unrecovered} unrecovered errors, "- f"{tokens:g} tokens, ${cost:g}, {seconds:g}s in LLM calls"- ),+ reason=", ".join(measured),)diff --git a/overbae/services/capabilities/identity.py b/overbae/services/capabilities/identity.pyindex 9ea97158..7b210a38 100644--- a/overbae/services/capabilities/identity.py+++ b/overbae/services/capabilities/identity.py@@ -31,8 +31,8 @@ def lookup(project_id, value: str, *, include_leftover: bool = False) -> CapabilReturns only current capabilities unless ``include_leftover`` is set; asoft-deleted row never resolves. Never creates one. Case-insensitive; also- tries the slugified form so a typed name and a scan slug meet. Ingest- passes ids only; name and slug resolution serve the API and Console."""+ tries the slugified form so a typed name and a scan slug meet. Name and slug+ resolution serve the API and Console; telemetry resolves through ``lookup_id``."""probe = (value or "").strip()if not probe:return None@@ -57,6 +57,15 @@ def lookup(project_id, value: str, *, include_leftover: bool = False) -> Capabilreturn _settle(alias.capability, include_leftover)+def lookup_id(project_id, value: str) -> Capability | None:+ """The current capability with this UUID. Telemetry binds by id alone: a name or slug+ sent as ``overmind.capability.id`` never binds a span."""+ probe = (value or "").strip()+ if not _is_uuid(probe):+ return None+ return Capability.objects.filter(project_id=project_id, id=probe).current().first()++def _settle(capability: Capability, include_leftover: bool) -> Capability | None:if capability.status == Capability.Status.CURRENT:return capabilitydiff --git a/overbae/services/connectors/capabilities.py b/overbae/services/connectors/capabilities.pyindex 1a63f4c9..6a0d1f72 100644--- a/overbae/services/connectors/capabilities.py+++ b/overbae/services/connectors/capabilities.py@@ -21,6 +21,7 @@ from typing import Anyfrom django.db.models import Qfrom django.utils.text import slugify+from overbae.core.errors import InputValidationErrorfrom overbae.services.connectors.records import ObservationRecordfrom overbae.services.connectors.schema import (CONNECTOR_CAPABILITY_KEY_ATTR,@@ -241,6 +242,29 @@ def discover_capabilities(return results+def resolve_mapping_targets(project, mapping: dict[str, Any]) -> dict[str, Any]:+ """The mapping with each assignment and the fallback stored as a capability id of this+ project. A target the project does not have is refused, never kept to bind nothing."""+ from overbae.services.capabilities import identity++ resolved = dict(mapping)+ if "assignments" in mapping:+ resolved["assignments"] = {}+ for key, reference in (mapping.get("assignments") or {}).items():+ capability = identity.lookup(project.id, str(reference))+ if capability is None:+ raise InputValidationError(+ "A capability mapping target was not found in this project."+ )+ resolved["assignments"][str(key)] = str(capability.id)+ if mapping.get("fallback_capability_id"):+ capability = identity.lookup(project.id, str(mapping["fallback_capability_id"]))+ if capability is None:+ raise InputValidationError("The fallback capability was not found in this project.")+ resolved["fallback_capability_id"] = str(capability.id)+ return resolved++def resolve_capability(agent_key: str | None, mapping: CapabilityMapping | dict[str, Any], project):"""Map a discovered provider key to a capability, or None.diff --git a/overbae/services/connectors/feedforward.py b/overbae/services/connectors/feedforward.pyindex 1758ec55..1d7d0a5e 100644--- a/overbae/services/connectors/feedforward.py+++ b/overbae/services/connectors/feedforward.py@@ -4,6 +4,7 @@ from __future__ import annotationsfrom typing import Any+from django.db import transactionfrom django.utils import timezonefrom overbae.services.connectors.sync import restart_connector_import@@ -20,36 +21,42 @@ def save_sync_config(backfill_from: Any = _UNSET,backfill_to: Any = _UNSET,) -> Any:- """Create the next config version and restart the import for it. Returns the new- ConnectorSyncConfig."""+ """Create the next config version and restart the import for it. A save that changes+ nothing returns the config in force, and the import carries on."""from overbae.models import ConnectorSyncConfigprev = credential.active_config()- version = (prev.version + 1) if prev else 1- config = ConnectorSyncConfig.objects.create(- credential=credential,- version=version,- source_project_id=source_project_id or (prev.source_project_id if prev else ""),- target_project=target_project or (prev.target_project if prev else None),- lookback_days=lookback_days+ values = {+ "source_project_id": source_project_id or (prev.source_project_id if prev else ""),+ "target_project": target_project or (prev.target_project if prev else None),+ "lookback_days": lookback_daysif lookback_days is not _UNSETelse (prev.lookback_days if prev else None),- backfill_from=prev.backfill_from+ "backfill_from": prev.backfill_fromif backfill_from is _UNSET and prevelse (None if backfill_from is _UNSET else backfill_from),- backfill_to=prev.backfill_to+ "backfill_to": prev.backfill_toif backfill_to is _UNSET and prevelse (None if backfill_to is _UNSET else backfill_to),- effective_from=timezone.now(),- )-- if prev is not None:- # Each save compares with the version it replaced, so concurrent saves still see- # a source change.- restart_connector_import(- credential, source_changed=config.source_project_id != prev.source_project_id+ }+ if prev is not None and all(getattr(prev, field) == value for field, value in values.items()):+ return prev+ # The new version and the restart land together: a version whose import never+ # restarted would be skipped by every later retry.+ with transaction.atomic():+ config = ConnectorSyncConfig.objects.create(+ credential=credential,+ version=(prev.version + 1) if prev else 1,+ effective_from=timezone.now(),+ **values,)- elif credential.auto_sync_enabled:+ if prev is not None:+ # Each save compares with the version it replaced, so concurrent saves still see+ # a source change.+ restart_connector_import(+ credential, source_changed=config.source_project_id != prev.source_project_id+ )+ if prev is None and credential.auto_sync_enabled:# First config + auto-sync: kick a normal backfill.from overbae.tasks.connector_sync import sync_connector_chunkdiff --git a/overbae/services/connectors/sync.py b/overbae/services/connectors/sync.pyindex ec53fa43..d5635752 100644--- a/overbae/services/connectors/sync.py+++ b/overbae/services/connectors/sync.py@@ -7,6 +7,7 @@ import uuidfrom django.db.models import Q+from overbae.core.errors import InputValidationErrorfrom overbae.services.connectors.schema import CONNECTOR_CREDENTIAL_ID_ATTR@@ -29,6 +30,15 @@ def will_recarve(credential) -> bool:return stored != boundary_import_key(credential.capability_mapping)+def import_projects(credential) -> set:+ """Every project whose spans a sync, a new config or a remap of this connector writes+ or deletes: its own and each config's target."""+ targets = credential.configs.exclude(target_project=None).values_list(+ "target_project_id", flat=True+ )+ return {credential.project_id, *targets}++def connector_imported_spans(credential):from django.db import connection@@ -120,6 +130,9 @@ def enqueue_connector_sync(credential) -> None:from overbae.models import ConnectorCredentialfrom overbae.tasks.connector_sync import sync_connector_chunk+ # The chunk skips either connector, so a queued one would show "backfilling" for good.+ if not credential.is_active or credential.active_config() is None:+ raise InputValidationError("Connect and configure this connector before syncing.")updates = {"next_poll_at": None,"sync_error": "",diff --git a/overbae/services/datasets/land.py b/overbae/services/datasets/land.pyindex d8958c00..76dc4084 100644--- a/overbae/services/datasets/land.py+++ b/overbae/services/datasets/land.py@@ -453,15 +453,19 @@ def _delivered(spans: list[Span]) -> Any:return None-def _first(usage: dict[str, Any], keys: tuple[str, ...]) -> float:- for key in keys:- value = usage.get(key)- if value is not None:+def _reported(spans: list[Span], keys: tuple[str, ...]) -> float | None:+ """Summed over the spans that report it; ``None`` when none does, never zero."""+ total = None+ for span in spans:+ usage = span.usage or {}+ for key in keys:try:- return float(value)- except (TypeError, ValueError):+ value = float(usage[key])+ except (KeyError, TypeError, ValueError):continue- return 0.0+ total = (total or 0.0) + value+ break+ return totaldef _usage(spans: list[Span]) -> dict[str, Any]:@@ -469,21 +473,19 @@ def _usage(spans: list[Span]) -> dict[str, Any]:as sent (``genai.prompt_tokens``, ``gen_ai.usage.input_tokens``, ...)."""from overbae.services.transcripts import chatml- prompt = completion = 0- cost = 0.0+ prompt = _reported(spans, chatml.PROMPT_TOKEN_KEYS)+ completion = _reported(spans, chatml.COMPLETION_TOKEN_KEYS)+ cost = _reported(spans, chatml.COST_KEYS)models: list[str] = []for span in spans:usage = span.usage or {}- prompt += int(_first(usage, chatml.PROMPT_TOKEN_KEYS))- completion += int(_first(usage, chatml.COMPLETION_TOKEN_KEYS))- cost += _first(usage, chatml.COST_KEYS)model = next((usage.get(k) for k in chatml.MODEL_KEYS if usage.get(k)), None)if model and str(model) not in models:models.append(str(model))return {- "prompt_tokens": prompt,- "completion_tokens": completion,- "cost_usd": round(cost, 6),+ "prompt_tokens": None if prompt is None else int(prompt),+ "completion_tokens": None if completion is None else int(completion),+ "cost_usd": None if cost is None else round(cost, 6),"model": models[-1] if models else None,}diff --git a/overbae/services/datasets/store.py b/overbae/services/datasets/store.pyindex 58a86e54..a37f60d9 100644--- a/overbae/services/datasets/store.py+++ b/overbae/services/datasets/store.py@@ -469,6 +469,8 @@ def _filter_sql(filters: list[dict[str, Any]], names: set[str]) -> tuple[str, liclauses: list[str] = []params: list[Any] = []for flt in filters or []:+ if not isinstance(flt, dict):+ raise StoreError("Each filter is an object with field, op and value.")field = str(flt.get("field") or "")op = str(flt.get("op") or "contains")value = flt.get("value")@@ -498,8 +500,12 @@ def _filter_sql(filters: list[dict[str, Any]], names: set[str]) -> tuple[str, li)else:symbol = {"gt": ">", "gte": ">=", "lt": "<", "lte": "<="}[op]+ try:+ number = float(value)+ except (TypeError, ValueError, OverflowError):+ raise StoreError(f"Filter {op!r} compares with a number.") from Noneclauses.append(f"TRY_CAST({col} AS DOUBLE) {symbol} ?")- params.append(float(value))+ params.append(number)return (" AND ".join(clauses) if clauses else "TRUE"), paramsdiff --git a/overbae/services/experiments/document.py b/overbae/services/experiments/document.pyindex 011d9be4..5853c5df 100644--- a/overbae/services/experiments/document.py+++ b/overbae/services/experiments/document.py@@ -7,6 +7,7 @@A saved revision may be unfinished; ``problems`` lists what a run needs first."""+import mathimport refrom copy import deepcopy@@ -25,6 +26,21 @@ def _refuse(message: str):raise InputValidationError(message)+def _storable(value) -> None:+ """jsonb holds no NUL in text and no infinite or NaN number; a JSON body can carry both."""+ if isinstance(value, str) and "\x00" in value:+ _refuse("Text cannot contain the NUL character.")+ if isinstance(value, float) and not math.isfinite(value):+ _refuse("Numbers must be finite.")+ if isinstance(value, dict):+ for key, item in value.items():+ _storable(key)+ _storable(item)+ elif isinstance(value, list):+ for item in value:+ _storable(item)++def binding(text) -> tuple[str, str]:node, _, port = str(text).partition(".")return node, port@@ -36,6 +52,7 @@ def normalize(document) -> dict:read of the final holdout by a stage that is not its one, last evaluation."""if not isinstance(document, dict):_refuse("The flow document is a JSON object.")+ _storable(document)unknown = set(document) - set(EMPTY)if unknown:_refuse(f"The flow document has no field {sorted(unknown)[0]}.")@@ -288,6 +305,7 @@ def run_parameters(document: dict, given: dict) -> dict:"""The values a run takes: those given, else the defaults. Every parameter needs one."""if not isinstance(given, dict):_refuse("parameters maps each parameter's name to its value.")+ _storable(given)declared = {parameter["name"]: parameter for parameter in document["parameters"]}unknown = set(given) - set(declared)if unknown:diff --git a/overbae/services/experiments/runs.py b/overbae/services/experiments/runs.pyindex c6a19a78..64d5b4ed 100644--- a/overbae/services/experiments/runs.py+++ b/overbae/services/experiments/runs.py@@ -794,7 +794,10 @@ def _observe_flow(run, step, node, settings) -> bool:if node["kind"] == "iterate":until = settings.get("until") or {}met = [stages.holds(c, until) for c in stages.candidates(outputs.get("scores"))]- if not (met and all(met)) and len(children) < (settings.get("max_iterations") or 3):+ limit = settings.get("max_iterations")+ if not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= 20:+ limit = 3+ if not (met and all(met)) and len(children) < limit:target, revision = _flow_revision(run, node, settings)carried = {key: value for key, value in outputs.items() if key in ("data", "model")}parameters = _child_parameters(diff --git a/overbae/services/experiments/stages.py b/overbae/services/experiments/stages.pyindex 695215dc..39c92d23 100644--- a/overbae/services/experiments/stages.py+++ b/overbae/services/experiments/stages.py@@ -479,12 +479,19 @@ def metric(candidate: dict, name: str):def holds(candidate: dict, predicate: dict) -> bool | None:- """Whether a measured value meets the predicate; None when it was not measured."""- value = metric(candidate, predicate.get("metric", ""))- compare = OPERATORS.get(predicate.get("op") or ">=")- if value is None or compare is None or predicate.get("value") is None:+ """Whether a measured value meets the predicate; None when it was not measured or the+ predicate names no metric, comparison and number."""+ if not isinstance(predicate, dict):return None- return compare(value, predicate["value"])+ name, op, target = predicate.get("metric"), predicate.get("op") or ">=", predicate.get("value")+ if not isinstance(name, str) or not isinstance(op, str):+ return None+ if not isinstance(target, int | float) or isinstance(target, bool):+ return None+ value, compare = metric(candidate, name), OPERATORS.get(op)+ if value is None or compare is None:+ return None+ return compare(value, target)def _condition(stage: Stage):diff --git a/overbae/services/inference_client.py b/overbae/services/inference_client.pyindex 60236896..766636f3 100644--- a/overbae/services/inference_client.py+++ b/overbae/services/inference_client.py@@ -23,6 +23,7 @@ from modal_shared.context_budget import (from modal_shared.modelfam import serve_image_keyfrom modal_shared.shared import WEIGHTS_PATH_HEADERfrom modal_shared.shared import routing_headers as _routing_headers+from overbae.services import dedicatedfrom overbae.services.deployment import saved_base_identity, serving_gpu@@ -228,8 +229,13 @@ class InferenceClient:An adapter deployment owns only its adapter — ``weights_path`` is a base shared withevery other adapter on that model, so deleting it would break all of them."""- from overbae.models import DeployedModel+ from overbae.models import DedicatedDeployment, DeployedModel+ # A dedicated pool serves this model on GPUs it meters by the minute: it stops too.+ for pool in DedicatedDeployment.objects.filter(+ deployed_model__model_id=model_id, status__in=DedicatedDeployment.LIVE+ ):+ dedicated.stop(pool)# Fence pending stage results before changing remote serving state.DeployedModel.objects.filter(model_id=model_id).update(status=DeployedModel.Status.DELETING,diff --git a/overbae/services/mcp/__init__.py b/overbae/services/mcp/__init__.pyindex 46e8c3b4..f7d563f3 100644--- a/overbae/services/mcp/__init__.py+++ b/overbae/services/mcp/__init__.py@@ -1,3 +1,3 @@"""MCP protocol and catalog services."""-CONTRACT_VERSION = "12.3.0"+CONTRACT_VERSION = "12.4.0"diff --git a/overbae/services/mcp/contracts/evaluations.py b/overbae/services/mcp/contracts/evaluations.pyindex 081b56c3..9b3f6fa0 100644--- a/overbae/services/mcp/contracts/evaluations.py+++ b/overbae/services/mcp/contracts/evaluations.py@@ -18,7 +18,7 @@ from overbae.services.mcp.contracts.common import (MatrixType = Literal["deterministic", "llm"]TargetMode = Literal["recorded", "generate"]RunStatus = Literal["pending", "running", "completed", "failed", "cancelled"]-ComparisonStatus = Literal["improved", "regressed", "unchanged", "added", "removed"]+ComparisonStatus = Literal["improved", "regressed", "unchanged", "added", "removed", "unmeasured"]MAX_TARGETS = 6_SENSITIVE_KEY_PARTS = {diff --git a/overbae/services/mcp/tools_connectors.py b/overbae/services/mcp/tools_connectors.pyindex 1ec0b899..cc5522ef 100644--- a/overbae/services/mcp/tools_connectors.py+++ b/overbae/services/mcp/tools_connectors.py@@ -6,6 +6,7 @@ from asgiref.sync import sync_to_asyncfrom django.db import connection, transactionfrom overbae.api.serializers import ConnectorCapabilityMappingWriteSerializer+from overbae.core.errors import InputValidationErrorfrom overbae.models import Capability, ConnectorCredentialfrom overbae.services.connectors import (capabilities_for,@@ -14,6 +15,7 @@ from overbae.services.connectors import (registered_sources,relabel_connector_capabilities,)+from overbae.services.connectors.capabilities import resolve_mapping_targetsfrom overbae.services.connectors.capability_resolution import (drop_nested_mapping_names,mapping_from_suggested,@@ -23,8 +25,12 @@ from overbae.services.connectors.capability_resolution import ()from overbae.services.connectors.feedforward import save_sync_configfrom overbae.services.connectors.profiling import profile_capability_candidates-from overbae.services.connectors.sync import enqueue_connector_sync, will_recarve-from overbae.services.mcp.context import MCPContext+from overbae.services.connectors.sync import (+ enqueue_connector_sync,+ import_projects,+ will_recarve,+)+from overbae.services.mcp.context import MCPContext, accessible_projectsfrom overbae.services.mcp.contracts.connectors import (AvailableConnectorType,ConfigureConnectorInput,@@ -108,6 +114,17 @@ def _connector_ref(value: str) -> str:return value+def _require_import_reach(context: MCPContext, connector: ConnectorCredential) -> None:+ """A sync, config or remap writes or deletes spans in every project the connector+ imports into; this connection must reach each of them."""+ reachable = set(accessible_projects(context).values_list("pk", flat=True))+ if not import_projects(connector) <= reachable:+ raise MCPError(+ "permission_denied",+ "This connector imports into a project this connection cannot reach.",+ )++def _resolve_connector(context: MCPContext, reference: str) -> ConnectorCredential:reference = _connector_ref(reference)query = ConnectorCredential.objects.filter(project=context.project)@@ -421,29 +438,10 @@ def _mapping_payload(mapping) -> dict:def _resolve_mapping_capabilities(context: MCPContext, connector_type: str, mapping) -> tuple[dict, str | None]:- payload = _mapping_payload(mapping)- assignments = payload.get("assignments") or {}- resolved: dict[str, str] = {}- for source_value, reference in assignments.items():- capability = _resolve_capability(context, reference)- if capability is None:- raise MCPError(- "capability_not_found",- "A capability mapping target was not found in this project.",- )- resolved[str(source_value)] = str(capability.id)- if "assignments" in payload:- payload["assignments"] = resolved-- fallback = payload.get("fallback_capability_id")- if fallback:- capability = _resolve_capability(context, fallback)- if capability is None:- raise MCPError(- "capability_not_found",- "The fallback capability was not found in this project.",- )- payload["fallback_capability_id"] = str(capability.id)+ try:+ payload = resolve_mapping_targets(context.project, _mapping_payload(mapping))+ except InputValidationError as exc:+ raise MCPError("capability_not_found", exc.detail) from excserializer = ConnectorCapabilityMappingWriteSerializer(data=payload)if not serializer.is_valid():@@ -468,12 +466,6 @@ def _parent_only_mapping(return drop_nested_mapping_names(mapping, shapes)-def _resolve_capability(context: MCPContext, reference: str) -> Capability | None:- from overbae.services.capabilities import identity-- return identity.lookup(context.project.id, str(reference))--def _inspect_connectors_sync(payload: InspectConnectorsInput, context: MCPContext) -> InspectConnectorsOutput:@@ -572,6 +564,7 @@ def _configure_connector_sync()if connector.connector_type not in registered_sources():raise MCPError("connector_unsupported", "This connector type cannot be synced.")+ _require_import_reach(context, connector)normalized_mapping = Noneif payload.capability_mapping is not None:@@ -738,6 +731,7 @@ def _sync_connector_sync(payload: SyncConnectorInput, context: MCPContext) -> Syhuman_action=_mapping_action(),resource_links=[link],)+ _require_import_reach(context, connector)recarving = will_recarve(connector)try:enqueue_connector_sync(connector)diff --git a/overbae/services/mcp/tools_observability.py b/overbae/services/mcp/tools_observability.pyindex 5dca97e3..cb295fbd 100644--- a/overbae/services/mcp/tools_observability.py+++ b/overbae/services/mcp/tools_observability.py@@ -11,7 +11,7 @@ from django.http import QueryDictfrom django.utils import timezonefrom overbae.api.filters import SpanFilter-from overbae.api.serializers import trace_status_map, trace_usage_totals+from overbae.api.serializers import span_usage, trace_status_map, trace_usage_totalsfrom overbae.innermind import healthfrom overbae.models import (Capability,@@ -284,7 +284,12 @@ def _query_traces_sync(payload: QueryTracesInput, context: MCPContext) -> QueryTtotal = query.count()spans = list(query[offset : offset + payload.limit])trace_ids = [span.trace_id for span in spans]- usage = trace_usage_totals([context.project.id], trace_ids)+ # As in the REST list: a span row carries its own usage, a trace row the trace's total.+ if payload.all_spans:+ usage = {span.span_id: span_usage(span.attributes) for span in spans}+ else:+ totals = trace_usage_totals([context.project.id], trace_ids)+ usage = {span.span_id: totals.get(span.trace_id) or {} for span in spans}statuses = trace_status_map([context.project.id], list(dict.fromkeys(trace_ids)))rows = [TraceRow(@@ -299,9 +304,9 @@ def _query_traces_sync(payload: QueryTracesInput, context: MCPContext) -> QueryTduration_ms=round(span.duration_ns / 1_000_000, 1),start_time_ns=span.start_time_ns,received_at=span.received_at,- total_tokens=(usage.get(span.trace_id) or {}).get("total_tokens"),- total_cost=(usage.get(span.trace_id) or {}).get("total_cost"),- model=(usage.get(span.trace_id) or {}).get("model"),+ total_tokens=usage[span.span_id].get("total_tokens"),+ total_cost=usage[span.span_id].get("total_cost"),+ model=usage[span.span_id].get("model"),trace_status=statuses.get(span.trace_id, "live"),eval_score=(span.eval_attributes or {}).get("score"),trajectory_score=((span.eval_attributes or {}).get("trajectory") or {}).get("score"),diff --git a/overbae/services/sync.py b/overbae/services/sync.pyindex d313b0c8..906bbb36 100644--- a/overbae/services/sync.py+++ b/overbae/services/sync.py@@ -14,6 +14,7 @@ from typing import Anyfrom django.db import transactionfrom django.utils import timezone+from overbae.core.errors import InputValidationErrorfrom overbae.innermind import default_setfrom overbae.models import Capability, Projectfrom overbae.services.activity import repository_synced@@ -159,6 +160,9 @@ def apply_snapshot(project: Project, snapshot: dict) -> list[Capability]:applied: list[Capability] = []for data in incoming:existing = _resolve(project, data)+ # One block by slug and another by id can name the same row: the last would win.+ if existing is not None and existing.pk in seen:+ raise InputValidationError("Two capability blocks name the same capability.")created = existing is Noneremounted = (existing is not Nonediff --git a/overbae/services/training_contract.py b/overbae/services/training_contract.pyindex f7c9782f..38ca2b71 100644--- a/overbae/services/training_contract.py+++ b/overbae/services/training_contract.py@@ -1,5 +1,6 @@import hashlibimport json+import mathfrom modal_shared.decisions import DECISION_OBJECTIVE, DECISION_OBJECTIVES, TEXT_OBJECTIVEfrom overbae.core.errors import InputValidationError@@ -37,6 +38,35 @@ def validate_effective_batch(hyperparameters):)+# Each optimizer setting a client may send, with the smallest value it takes and whether+# that bound is open: a learning rate of 0 trains nothing.+_OPTIMIZER_RANGES = {+ "learning_rate": (0.0, True, None),+ "lr": (0.0, True, None),+ "warmup_ratio": (0.0, False, 1.0),+ "weight_decay": (0.0, False, None),+}+++def validate_numbers(hyperparameters):+ """Optimizer settings are finite numbers in range: "NaN" parses as a float."""+ for key, (low, open_low, high) in _OPTIMIZER_RANGES.items():+ if key not in hyperparameters or hyperparameters[key] is None:+ continue+ raw = hyperparameters[key]+ try:+ value = float(raw) if not isinstance(raw, bool) else math.nan+ except (TypeError, ValueError, OverflowError):+ value = math.nan+ if (+ not math.isfinite(value)+ or value < low+ or (open_low and value == low)+ or (high is not None and value > high)+ ):+ raise InputValidationError(f"{key} must be a finite number in range.")++def contract(cell, hyperparameters=None):objective = (hyperparameters or {}).get("objective") or dataset_objective(cell)native = objective in DECISION_OBJECTIVESdiff --git a/overbae/tasks/capability_rebind.py b/overbae/tasks/capability_rebind.pyindex 10549599..b2b6c9b6 100644--- a/overbae/tasks/capability_rebind.py+++ b/overbae/tasks/capability_rebind.py@@ -3,7 +3,7 @@Ingest never creates a capability: a span whose ``overmind.capability.id``the project does not know stays unbound. A scan or a hand-made capability canlater make that identity resolvable; this task binds the backlog in place and-re-projects the touched graph edges. Idempotent — ``identity.lookup`` only ever+re-projects the touched graph edges. Idempotent — ``identity.lookup_id`` only everreturns an existing row."""from __future__ import annotations@@ -61,7 +61,7 @@ def rebind_unbound_spans(*, project_id: str) -> dict:for probe in _probes(span):key = probe.lower()if key not in cache:- cache[key] = identity.lookup(project_id, probe)+ cache[key] = identity.lookup_id(project_id, probe)if cache[key] is not None:span.capability = cache[key]batch.append(span)diff --git a/overbae/tasks/connector_sync.py b/overbae/tasks/connector_sync.pyindex 0f8af4ae..92b26b69 100644--- a/overbae/tasks/connector_sync.py+++ b/overbae/tasks/connector_sync.py@@ -477,14 +477,17 @@ def sweep_abandoned_drafts() -> dict:@shared_task(name="overbae.tasks.connector_sync.poll_connectors")def poll_connectors() -> dict:- """Beat entry point: enqueue a poll chunk for every due active credential."""+ """Beat entry point: enqueue a chunk for every due auto-sync or backfilling credential."""from overbae.models import ConnectorCredentialfrom overbae.services.connectors import registered_sourcesnow = timezone.now()- due = ConnectorCredential.objects.filter(is_active=True, auto_sync_enabled=True).filter(- Q(next_poll_at__isnull=True) | Q(next_poll_at__lte=now)- )+ # A backfill chains its own chunks; once its worker dies, only this poll resumes it.+ # The chunk claims its lease by compare-and-set, so a second message is skipped.+ due = ConnectorCredential.objects.filter(+ Q(auto_sync_enabled=True) | Q(sync_status=ConnectorCredential.SyncStatus.BACKFILLING),+ is_active=True,+ ).filter(Q(next_poll_at__isnull=True) | Q(next_poll_at__lte=now))sources = registered_sources()enqueued = 0for credential in due:diff --git a/overbae/tasks/datasets.py b/overbae/tasks/datasets.pyindex 9f1d59a4..cec952f2 100644--- a/overbae/tasks/datasets.py+++ b/overbae/tasks/datasets.py@@ -337,11 +337,20 @@ def _execute_landing({"completed": total, "total": total, "stage": "publishing", "rows": len(read.rows)})if source.get("llm_calls") is not None:- if not _land_llm_calls(- targets, read, user=user, split=split, infer_capability=infer_capability- ):- return {"status": "failed"}- return _landed(targets)+ if split or not attachment_request:+ if not _land_llm_calls(+ targets, read, user=user, split=split, infer_capability=infer_capability+ ):+ return {"status": "failed"}+ return _landed(targets)+ # More calls for an existing dataset are its next version, like any other+ # attached source: the version a job or evaluation used stays as it was.+ read = landing.Landing(+ llm_calls.shape(read.rows, dataset.intent),+ kind=Dataset.SourceKind.LLM_CALLS,+ spec=read.spec,+ manifest=llm_calls.manifest_for(dataset.intent),+ )if split:cut = {"eval_percent": int(split["eval_percent"]),diff --git a/overmind/CHANGELOG.md b/overmind/CHANGELOG.mdindex 64e52a2c..aaa3dcd5 100644--- a/overmind/CHANGELOG.md+++ b/overmind/CHANGELOG.md@@ -8,6 +8,8 @@ entries here cover the SDK surface.### Fixed+- Refuse `overmind chassis --root` on a missing directory with a usage error, not+ a traceback.- Bind saved SDK credentials to their API endpoint. `init()` disables tracingwith a warning when they meet another endpoint, and raises in strict mode.- Preserve tool calls in SDK chat responses. `CompletionMessage.content` isdiff --git a/overmind/overmind/__init__.py b/overmind/overmind/__init__.pyindex 2baf1c88..b1c269b1 100644--- a/overmind/overmind/__init__.py+++ b/overmind/overmind/__init__.py@@ -9,7 +9,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Any-__version__ = "0.1.132"+__version__ = "0.1.133"from .client import Client, ModelDeleted, OvermindInferenceErrordiff --git a/overmind/overmind/chassis.py b/overmind/overmind/chassis.pyindex f58e8394..d998fb9d 100644--- a/overmind/overmind/chassis.py+++ b/overmind/overmind/chassis.py@@ -281,7 +281,7 @@ def declared_expectations(repo_root: str | Path) -> dict[str, list[dict[str, strdef chassis(- root: Annotated[Path, typer.Option(help="Repository root to parse")] = Path("."),+ root: Annotated[Path, typer.Option(help="Repository root to parse", exists=True, file_okay=False)] = Path("."),language: Annotated[str | None,typer.Option(help="python, typescript (JavaScript included); default: the repository's majority language"),diff --git a/overmind/pyproject.toml b/overmind/pyproject.tomlindex dc4e0eb3..068bd783 100644--- a/overmind/pyproject.toml+++ b/overmind/pyproject.toml@@ -46,7 +46,7 @@ license = { text = "MIT" }name = "overmind"readme = "README.md"requires-python = ">=3.10,<4" # todo; remove the upper bound-version = "0.1.132"+version = "0.1.133"[project.urls]"Agent setup" = "https://console.overmindlab.ai/setup.md"diff --git a/overmind/skills/overmind-evaluations/SKILL.md b/overmind/skills/overmind-evaluations/SKILL.mdindex 2b9c929a..36eba788 100644--- a/overmind/skills/overmind-evaluations/SKILL.md+++ b/overmind/skills/overmind-evaluations/SKILL.md@@ -185,8 +185,10 @@ reason, and the run's `summary` (`score`, per-metric means, failures and errors,`trust`).`compare_evaluations` takes a candidate run; the baseline defaults to its group's-baseline. Status is `improved`, `regressed`, `unchanged`, `added` or `removed`;-deltas within half a point are `unchanged`.+baseline. Each status compares rows both runs scored: `improved`, `regressed` or+`unchanged` (deltas within half a point). The overall status is `unmeasured` when no+row has a score in both runs; a metric's is `unmeasured` when no row has that metric+scored in both runs, even when the overall comparison is measured.Fine-tuning before/after evaluations grade with the capability's active set unlessgiven another and keep the same rows for their whole run, so confirm the set beforediff --git a/overmind/tests/test_chassis.py b/overmind/tests/test_chassis.pyindex b436a616..7a05086b 100644--- a/overmind/tests/test_chassis.py+++ b/overmind/tests/test_chassis.py@@ -139,3 +139,15 @@ def test_declarations_keep_the_entrypoint_module_when_class_names_repeat(tmp_patname: [{"expectation": f"{name} result is accurate", "span_name": f"Agent.{name}_result"}]for name in ("browser", "helper")}+++def test_the_chassis_command_refuses_a_missing_root_without_a_traceback(tmp_path):+ from typer.testing import CliRunner++ from overmind.__main__ import app++ result = CliRunner().invoke(app, ["chassis", "--root", str(tmp_path / "missing")])++ assert result.exit_code == 2+ assert result.exception is None or isinstance(result.exception, SystemExit)+ assert not (tmp_path / "missing").exists()diff --git a/overmind/uv.lock b/overmind/uv.lockindex 1f4d557a..01a29fe2 100644--- a/overmind/uv.lock+++ b/overmind/uv.lock@@ -923,7 +923,7 @@ wheels = [[[package]]name = "overmind"-version = "0.1.132"+version = "0.1.133"source = { editable = "." }dependencies = [{ name = "packaging" },diff --git a/sales-dashboard/src/lib/format.ts b/sales-dashboard/src/lib/format.tsindex 93e23fe9..1c3d80b2 100644--- a/sales-dashboard/src/lib/format.ts+++ b/sales-dashboard/src/lib/format.ts@@ -9,7 +9,11 @@ const date = new Intl.DateTimeFormat("en-GB", {const day = new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", timeZone: "UTC" });export const formatInt = (value: number) => integer.format(value);-export const formatUsd = (value: string | number) => usd.format(Number(value));+// A balance of -0.001 formats as "-$0.00": only that negative zero is normalised.+export const formatUsd = (value: string | number) => {+ const text = usd.format(Number(value) || 0);+ return text === usd.format(-0) ? usd.format(0) : text;+};export const formatDate = (iso: string) => date.format(new Date(iso));export const formatDay = (iso: string) => day.format(new Date(iso));diff --git a/sales-dashboard/tests/format.test.ts b/sales-dashboard/tests/format.test.tsnew file mode 100644index 00000000..f3e85830--- /dev/null+++ b/sales-dashboard/tests/format.test.ts@@ -0,0 +1,11 @@+import { expect, test } from "bun:test";++import { formatUsd } from "../src/lib/format";++test("a balance that rounds to zero cents prints without a sign", () => {+ expect(formatUsd("-0.001")).toBe("$0.00");+ expect(formatUsd(-0.004)).toBe("$0.00");+ expect(formatUsd("-1.5")).toBe("-$1.50");+ expect(formatUsd(12.345)).toBe("$12.35");+ expect(formatUsd(-12.345)).toBe("-$12.35");+});diff --git a/tests/test_api_tokens.py b/tests/test_api_tokens.pyindex 116a24c9..906cc64a 100644--- a/tests/test_api_tokens.py+++ b/tests/test_api_tokens.py@@ -258,3 +258,53 @@ def test_project_key_cannot_read_sibling_trace():response = client.get("/api/traces/", {"project": str(sibling.pk)})assert response.status_code == 200assert response.data["results"] == []+++def test_create_refuses_an_empty_permission_and_a_project_beside_a_scope():+ user, project = make_user(), make_project()+ ProjectMembership.objects.create(user=user, project=project)+ pinned = {"scope": "project", "resourceIds": [str(project.id)], "permission": ["read"]}+ for body in (+ {"scope": {"scope": "account", "permission": []}},+ {"project": str(project.id), "scope": pinned},+ ):+ r = _jwt(user).post("/api/auth/api-keys/", body, format="json")+ assert r.status_code == status.HTTP_400_BAD_REQUEST, body+ assert not APIToken.objects.filter(user=user).exists()++[email protected]("tenancy")+def test_project_key_manages_only_its_projects_keys():+ user = make_user()+ own, sibling = make_project(member=user), make_project(member=user)+ client, _ = _api_key_client(user, project=own)+ _, sibling_key = APIToken.create_for_user(user, project=sibling)+ _, account_key = APIToken.create_for_user(user)++ listed = {row["id"] for row in client.get("/api/auth/api-keys/").data["results"]}+ assert listed == {+ str(pk)+ for pk in APIToken.objects.filter(user=user, project=own).values_list("pk", flat=True)+ }+ for other in (sibling_key, account_key):+ assert client.delete(f"/api/auth/api-keys/{other.pk}/").status_code == 404+ other.refresh_from_db()+ assert other.is_active++[email protected]("tenancy")+def test_project_key_reads_only_its_projects_ledger():+ from decimal import Decimal++ from overbae.models import BillingService, BillingTelemetry++ user = make_user()+ own, sibling = make_project(member=user), make_project(member=user)+ for project in (own, sibling, None):+ BillingTelemetry.objects.create(+ user=user, project=project, amount=Decimal("1"), service=BillingService.choices[0][0]+ )+ client, _ = _api_key_client(user, project=own)++ rows = client.get("/api/billing/ledger/").data["results"]+ assert [row["project_id"] for row in rows] == [str(own.pk)]diff --git a/tests/test_capabilities_api.py b/tests/test_capabilities_api.pyindex dd0b3b57..a77f3d09 100644--- a/tests/test_capabilities_api.py+++ b/tests/test_capabilities_api.py@@ -49,6 +49,52 @@ def test_benchmark_rejects_other_projects_and_evaluation_infrastructure():assert "benchmark_model" in response.json()[email protected]("tenancy")+def test_a_client_cannot_point_at_a_foreign_eval_set_or_write_measured_fields():+ from overbae.models import EvalSet++ project, other = _project(), _project()+ capability = _capability(project, "Support")+ foreign = EvalSet.objects.create(+ project=other, capability=_capability(other, "Other"), name="Private"+ )+ client = _client(project)++ refused = client.patch(+ f"/api/capabilities/{capability.id}/", {"active_eval_set": str(foreign.id)}, format="json"+ )+ assert refused.status_code == 400+ assert "active_eval_set" in refused.json()+ # Nor by moving the capability to the eval set's project in the same request.+ ProjectMembership.objects.create(+ user=User.objects.get(project_memberships__project=project), project=other+ )+ moved = client.patch(+ f"/api/capabilities/{capability.id}/",+ {"project": str(other.id), "active_eval_set": str(foreign.id)},+ format="json",+ )+ assert moved.status_code == 400+ capability.refresh_from_db()+ assert capability.project_id == project.id++ client.patch(+ f"/api/capabilities/{capability.id}/",+ {+ "observed": True,+ "usage_stats": {"span_count": 9},+ "last_activity_at": "2099-01-01T00:00Z",+ },+ format="json",+ )+ capability.refresh_from_db()+ assert (capability.observed, capability.usage_stats, capability.last_activity_at) == (+ False,+ {},+ None,+ )++def _project() -> Project:return Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")diff --git a/tests/test_capability_identity.py b/tests/test_capability_identity.pyindex 5dfd55ae..a91798d4 100644--- a/tests/test_capability_identity.py+++ b/tests/test_capability_identity.py@@ -75,6 +75,9 @@ def test_ingest_binds_by_id_only_and_never_mints():# The name is a display label: it never resolves, however exact.assert _bound(project, {"overmind.capability.name": "Ledgerline Invoice Triage"}) is Noneassert _bound(project, {"overmind.capability.id": str(uuid.uuid4())}) is None+ # A name or slug sent in the id attribute is still not an id.+ assert _bound(project, {"overmind.capability.id": "Ledgerline Invoice Triage"}) is None+ assert _bound(project, {"overmind.capability.id": capability.slug}) is Noneassert Capability.objects.filter(project=project).count() == 1@@ -139,6 +142,19 @@ def test_identity_less_spans_join_the_trace_capability_only_when_unambiguous():assert _bound(project, {}, trace_id=trace_id) is None+def test_a_span_naming_another_capability_does_not_join_its_trace_capability():+ project = make_project()+ first = _capability(project, "First")+ trace_id = uuid.uuid4().hex+ _bound(project, {"overmind.capability.id": str(first.id)}, trace_id=trace_id)++ # Unknown here, so unbound: never folded into the capability the trace began with.+ unknown = {"overmind.capability.id": str(uuid.uuid4())}+ assert _bound(project, unknown, trace_id=trace_id) is None+ assert _bound(project, {"overmind.capability.name": "Other"}, trace_id=trace_id) is None+ assert _bound(project, {}, trace_id=trace_id) == first++def test_resolve_capability_follows_renames():from overbae.services.entity_resolution import resolve_capability@@ -176,3 +192,13 @@ def test_connector_assignment_and_fallback_resolve_through_aliases():assert connector_resolve("svc-a", mapping, project) == capabilityassert connector_resolve(None, mapping, project) == capabilityassert connector_resolve("svc-unknown", mapping, project) == capability+++def test_identity_less_spans_never_join_a_deleted_trace_capability():+ project = make_project()+ gone = _capability(project, "Gone")+ trace_id = uuid.uuid4().hex+ _bound(project, {"overmind.capability.id": str(gone.id)}, trace_id=trace_id)+ gone.set_status(Capability.Status.DELETED)++ assert _bound(project, {}, trace_id=trace_id) is Nonediff --git a/tests/test_capability_rebind.py b/tests/test_capability_rebind.pyindex 0a7fdfb0..785a3773 100644--- a/tests/test_capability_rebind.py+++ b/tests/test_capability_rebind.py@@ -31,11 +31,12 @@ def test_backlog_binds_by_id_only_and_is_idempotent():by_id = _span(project, attributes={"overmind.capability.id": str(capability.id)})by_name = _span(project, attributes={"overmind.capability.name": "Triage"})by_span_name = _span(project, name="Triage")+ slug_as_id = _span(project, attributes={"overmind.capability.id": "triage"})assert rebind_unbound_spans(project_id=str(project.id)) == {"bound": 1}by_id.refresh_from_db()assert by_id.capability_id == capability.id- for span in (by_name, by_span_name):+ for span in (by_name, by_span_name, slug_as_id):span.refresh_from_db()assert span.capability_id is Nonediff --git a/tests/test_completions_api.py b/tests/test_completions_api.pyindex 67c3064a..4e4e1dab 100644--- a/tests/test_completions_api.py+++ b/tests/test_completions_api.py@@ -399,6 +399,19 @@ class TestChatCompletionsEndpoint:r = _jwt_client(u).post(self.URL, {"model": "ft-abc"}, format="json")assert r.status_code == status.HTTP_400_BAD_REQUEST+ def test_a_non_finite_temperature_or_non_list_messages_returns_400(self):+ u, p = _user(), _project()+ _membership(u, p)+ client = _jwt_client(u)+ bodies = (+ '{"model": "ft-abc", "messages": [{"role": "user", "content": "Hi"}], '+ '"temperature": 1e999}',+ '{"model": "ft-abc", "messages": "Hi"}',+ )+ for body in bodies:+ r = client.post(self.URL, data=body, content_type="application/json")+ assert r.status_code == status.HTTP_400_BAD_REQUEST, body+def test_unknown_finetuned_model_returns_404(self):u, p = _user(), _project()_membership(u, p)diff --git a/tests/test_connector_poll.py b/tests/test_connector_poll.pyindex ce7358d1..ded82aeb 100644--- a/tests/test_connector_poll.py+++ b/tests/test_connector_poll.py@@ -519,3 +519,115 @@ def test_a_chunk_without_new_traces_keeps_the_import_active(credential, langfusewith time_machine.travel(timezone.now() + timedelta(minutes=10), tick=False):checkpoint_progress(credential, credential.sync_cursor["progress"], gained=0, done=False)assert sync_progress(credential).state != "waiting"+++def test_the_poller_resumes_a_backfill_whose_worker_died_with_auto_sync_off(+ credential, continuations+):+ ConnectorCredential.objects.filter(id=credential.id).update(+ sync_status=ConnectorCredential.SyncStatus.BACKFILLING,+ next_poll_at=timezone.now() - timedelta(minutes=1),+ )++ assert connector_sync.poll_connectors()["enqueued"] == 1+ assert continuations == [str(credential.id)]+++def test_saving_the_same_settings_again_keeps_the_running_import(credential):+ cursor = {"mode": "live", "watermark": "2026-01-01T00:00:00Z"}+ ConnectorCredential.objects.filter(pk=credential.pk).update(sync_cursor=cursor)+ active = credential.active_config()++ saved = save_sync_config(credential, lookback_days=active.lookback_days)++ credential.refresh_from_db()+ assert saved.pk == active.pk+ assert credential.sync_cursor == cursor++[email protected]("state", ["draft", "disconnected"])+def test_a_sync_of_an_unconfigured_or_disconnected_connector_is_refused(credential, state):+ if state == "draft":+ credential.configs.all().delete()+ else:+ ConnectorCredential.objects.filter(pk=credential.pk).update(is_active=False)++ response = member_client(credential.project).post(+ reverse("connectorcredential-sync", args=[credential.id])+ )++ assert response.status_code == 400+ credential.refresh_from_db()+ assert credential.sync_status != ConnectorCredential.SyncStatus.BACKFILLING++[email protected]("tenancy")+def test_a_member_cannot_sync_config_or_remap_into_a_project_they_cannot_reach(credential):+ from overbae.models import ConnectorSyncConfig++ elsewhere = make_project()+ ConnectorSyncConfig.objects.filter(credential=credential).update(target_project=elsewhere)+ client = member_client(credential.project)++ for name, body in (+ ("connectorcredential-sync", None),+ ("connectorcredential-config", {"lookback_days": 9}),+ ):+ assert (+ client.post(reverse(name, args=[credential.id]), body, format="json").status_code == 403+ )+ remap = client.put(+ reverse("connectorcredential-capability-mapping", args=[credential.id]),+ {"source": "trace_name", "names": ["x"]},+ format="json",+ )+ assert remap.status_code == 403+ # New credentials start a sync into every target, so they need the same reach.+ rotate = client.patch(+ reverse("connectorcredential-detail", args=[credential.id]),+ {"api_key": "pk-new", "api_secret": "sk-new"},+ format="json",+ )+ assert rotate.status_code == 403+ assert credential.configs.count() == 1++[email protected]("tenancy")+def test_a_stored_secret_is_not_sent_to_a_new_host_or_vendor(credential):+ client = member_client(credential.project)+ url = reverse("connectorcredential-detail", args=[credential.id])++ moved = client.patch(url, {"base_url": "https://collector.example"}, format="json")+ switched = client.patch(url, {"connector_type": "langsmith"}, format="json")++ assert (moved.status_code, switched.status_code) == (400, 400)+ credential.refresh_from_db()+ assert (credential.base_url, credential.connector_type) != (+ "https://collector.example",+ "langsmith",+ )+++def test_lookback_days_out_of_range_or_not_a_number_is_refused(credential):+ client = member_client(credential.project)+ config = client.post(+ reverse("connectorcredential-config", args=[credential.id]),+ {"lookback_days": 10**12},+ format="json",+ )+ discover = client.get(+ f"/api/connector-credentials/{credential.id}/discover-capabilities/",+ {"lookback_days": "a week"},+ )+ assert (config.status_code, discover.status_code) == (400, 400)+++def test_a_mapping_to_a_capability_the_project_does_not_have_is_refused(credential):+ response = member_client(credential.project).put(+ reverse("connectorcredential-capability-mapping", args=[credential.id]),+ {"source": "trace_name", "names": ["x"], "assignments": {"x": "No Such Capability"}},+ format="json",+ )+ assert response.status_code == 400+ credential.refresh_from_db()+ assert credential.capability_mapping == {}diff --git a/tests/test_dataset_land_traces.py b/tests/test_dataset_land_traces.pyindex 8bfe358b..28ff9a16 100644--- a/tests/test_dataset_land_traces.py+++ b/tests/test_dataset_land_traces.py@@ -128,6 +128,27 @@ def test_usage_sums_every_span_under_the_attribute_names_as_sent():assert row["model"] == "openai/gpt-5"+def test_usage_no_span_reported_lands_unknown_not_zero():+ project = make_project()+ trace = uuid.uuid4().hex+ root = _span(+ project, trace, span_type="entry_point", attrs={"overmind.span.type": "entry_point"}+ )+ inn, out = _messages("a")+ _span(+ project,+ trace,+ parent=root.span_id,+ start=NS + 10,+ attrs={"gen_ai.input.messages": inn, "gen_ai.output.messages": out},+ )+ _, df = _land(project, {"trace_ids": [trace]})+ row = df.iloc[0]+ assert all(+ pd.isna(row[column]) for column in ("prompt_tokens", "completion_tokens", "cost_usd")+ )++def test_delivered_output_wins_over_the_root_output():project = make_project()trace, root = _chat_trace(project, text="draft")diff --git a/tests/test_dataset_store.py b/tests/test_dataset_store.pyindex 40d7bc2f..0211cfad 100644--- a/tests/test_dataset_store.py+++ b/tests/test_dataset_store.py@@ -101,6 +101,13 @@ def test_page_sorts_filters_and_indexes(table):store.page(table, sort="nope")with pytest.raises(store.StoreError):store.page(table, filters=[{"field": "score", "op": "regex", "value": "x"}])+ for refused in (+ ["score"],+ [{"field": "score", "op": "gt", "value": "high"}],+ [{"field": "score", "op": "gt", "value": 10**309}],+ ):+ with pytest.raises(store.StoreError):+ store.page(table, filters=refused)def test_a_searched_page_keeps_file_positions_and_the_whole_total(tmp_path):diff --git a/tests/test_dedicated_deployment.py b/tests/test_dedicated_deployment.pyindex c85e0a7d..0e773935 100644--- a/tests/test_dedicated_deployment.py+++ b/tests/test_dedicated_deployment.py@@ -391,3 +391,31 @@ def test_dedicated_unknown_acknowledgement_is_never_replayed(fake_modal):request.refresh_from_db()assert request.state == "submission_unknown"assert fake_modal.spawns() == []++[email protected]("ledger")+def test_deleting_a_model_shuts_its_dedicated_pool_down(fake_modal, scripted):+ from overbae.models import ProjectMembership++ scripted("http://inference.test").reply(200, json_body={})+ refresh_rates()+ user = _user()+ project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:8]}")+ ProjectMembership.objects.create(user=user, project=project)+ deployed = _ready(project)+ fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)+ row = dedicated.start(deployed, user, gpu_type="H100")+ dedicated.advance(str(row.id))+ dedicated.advance(str(row.id))+ client = APIClient()+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {RefreshToken.for_user(user).access_token}")++ response = client.delete(f"/api/deployed-models/{deployed.id}/")++ assert response.status_code == 204+ row.refresh_from_db()+ assert row.status == DedicatedDeployment.Status.SHUTTING_DOWN+ fake_modal.worker_stats = {"num_total_runners": 0, "backlog": 0, "num_running_inputs": 0}+ dedicated.advance(str(row.id))+ row.refresh_from_db()+ assert row.status == DedicatedDeployment.Status.OFFLINEdiff --git a/tests/test_experiments.py b/tests/test_experiments.pyindex 4815e3ac..e90ee191 100644--- a/tests/test_experiments.py+++ b/tests/test_experiments.py@@ -754,6 +754,58 @@ def test_an_iteration_reads_what_the_previous_one_produced(setup):assert [item.parameters["data"] for item in iterations] == [str(cell.pk), str(produced.pk)]+def test_an_iteration_with_a_malformed_stop_rule_ends_instead_of_failing_each_advance(setup):+ context, cell = setup+ child = records.create(+ context.project,+ context.user,+ document={+ "parameters": [{"name": "data", "type": "data"}],+ "nodes": [{"id": "data", "kind": "data", "settings": {"cell": str(cell.pk)}}],+ "outputs": [{"node": "data", "port": "data"}],+ },+ )+ parent = records.create(+ context.project,+ context.user,+ document={+ "nodes": [+ {"id": "data", "kind": "data", "settings": {"cell": str(cell.pk)}},+ {+ "id": "loop",+ "kind": "iterate",+ "inputs": {"data": ["data.data"]},+ "settings": {+ "experiment": str(child.pk),+ "max_iterations": "two",+ "until": "accuracy above 0.9",+ },+ },+ ]+ },+ )+ run = runs.start(parent, context.user, origin="console")+ run.refresh_from_db()+ assert run.state == ExperimentRun.State.COMPLETED, run.result+ assert child.runs.count() == 3+++def test_flow_and_run_parameters_refuse_what_jsonb_cannot_store():+ data = {"id": "data", "kind": "data", "settings": {"cell": "x"}}+ for unstorable in (+ {"nodes": [{**data, "settings": {"cell": "a\x00b"}}]},+ {"nodes": [{**data, "settings": {"cell": "x", "limit": float("inf")}}]},+ {"nodes": [{**data, "notes": "a\x00b"}]},+ ):+ with pytest.raises(InputValidationError):+ document.normalize(unstorable)+ declared = document.normalize(+ {"parameters": [{"name": "note", "type": "string"}], "nodes": [data]}+ )+ with pytest.raises(InputValidationError):+ document.run_parameters(declared, {"note": "a\x00b"})++def test_a_halt_after_the_starter_left_names_the_work_it_did_not_stop(setup):context, _ = setupconnector = ConnectorCredential.objects.create(diff --git a/tests/test_finetuning.py b/tests/test_finetuning.pyindex 6710d947..46d5b579 100644--- a/tests/test_finetuning.py+++ b/tests/test_finetuning.py@@ -139,6 +139,25 @@ def test_create_rejects_capability_from_other_project():mock_apply.assert_not_called()+def test_create_refuses_a_version_sent_without_its_dataset():+ u, p, _, ds = _setup_project_with_dataset()+ foreign = _dataset(make_capability(make_project("foreign")))++ r = auth_client(u).post(+ reverse("finetuningjob-list"),+ _job_payload(+ project_id=str(p.id),+ dataset_id=str(ds.id),+ validation_cell=str(foreign.active_cell.id),+ ),+ format="json",+ )++ assert r.status_code == 400+ assert "validation_cell" in r.data+ assert not FinetuningJob.objects.filter(project=p).exists()++def test_retrieve_404_for_foreign_job():u, _, _, _ = _setup_project_with_dataset()_, p2, _, ds2 = _setup_project_with_dataset()@@ -195,3 +214,56 @@ def test_events_endpoint_returns_events_for_job():r = auth_client(u).get(reverse("finetuningjob-events", kwargs={"id": job.id}))assert r.status_code == 200assert {row["message"] for row in r.data} == {"one", "two"}++[email protected]("state-machines")+def test_a_run_still_working_is_not_deleted_and_max_retries_is_server_owned():+ u, p, _, ds = _setup_project_with_dataset()+ running = FinetuningJob.objects.create(+ project=p, dataset=ds, base_model="m", status=FinetuningJob.Status.RUNNING+ )+ ended = FinetuningJob.objects.create(+ project=p, dataset=ds, base_model="m", status=FinetuningJob.Status.CANCELLED+ )+ client = auth_client(u)++ refused = client.delete(reverse("finetuningjob-detail", kwargs={"id": running.id}))+ client.patch(+ reverse("finetuningjob-detail", kwargs={"id": running.id}),+ {"max_retries": 99},+ format="json",+ )+ deleted = client.delete(reverse("finetuningjob-detail", kwargs={"id": ended.id}))++ assert (refused.status_code, deleted.status_code) == (400, 204)+ running.refresh_from_db()+ assert running.max_retries == 0+ assert not FinetuningJob.objects.filter(pk=ended.pk).exists()+++def test_a_launch_or_estimate_with_an_unusable_optimizer_setting_is_refused():+ u, p, _, ds = _setup_project_with_dataset()+ client = auth_client(u)++ launch = client.post(+ reverse("finetuningjob-list"),+ _job_payload(+ project_id=str(p.id), dataset_id=str(ds.id), hyperparameters={"learning_rate": "NaN"}+ ),+ format="json",+ )+ estimate = client.post(+ reverse("finetuningjob-estimate"),+ {+ "dataset_id": str(ds.id),+ "base_model": "Qwen/Qwen3.5-4B",+ "n_epochs": 2,+ "use_lora": True,+ "hyperparameters": [1],+ },+ format="json",+ )++ assert (launch.status_code, estimate.status_code) == (400, 400)+ assert "hyperparameters" in launch.data and "hyperparameters" in estimate.data+ assert not FinetuningJob.objects.filter(project=p).exists()diff --git a/tests/test_llm_call_datasets.py b/tests/test_llm_call_datasets.pyindex c7fb1557..c6af87e1 100644--- a/tests/test_llm_call_datasets.py+++ b/tests/test_llm_call_datasets.py@@ -13,7 +13,7 @@ from conftest import read_tablefrom django.utils import timezonefrom overbae.models import Capability, Dataset, Project, Span-from overbae.services.datasets import dispatch, paths+from overbae.services.datasets import dispatch, paths, usefrom overbae.services.datasets.land import LandErrorfrom overbae.services.datasets.llm_calls import call_record, hash_split, shapefrom overbae.services.finetuning_validator import validate_rows@@ -230,6 +230,39 @@ def test_landing_settles_idle_without_a_workshop_turn(monkeypatch):assert frame.iloc[0]["origin_trace_id"][email protected]("lineage")+def test_more_calls_for_a_used_dataset_add_a_version_and_keep_the_used_one():+ project = _project()+ capability = Capability.objects.create(project=project, name="Support", slug="support")+ source = {+ "llm_calls": {+ "capability_id": str(capability.id),+ "since": (timezone.now() - timedelta(hours=1)).isoformat(),+ }+ }+ _call_span(project, capability, uuid.uuid4().hex[:16])+ dataset = dispatch.create_dataset(+ project=project,+ user=None,+ name="Calls",+ source=source,+ intent="eval",+ capability=capability,+ infer_capability=False,+ )+ dataset.refresh_from_db()+ used = use.use(dataset, "eval")+ pinned = (used.fingerprint, used.rows)++ _call_span(project, capability, uuid.uuid4().hex[:16])+ dispatch.attach_source(dataset, None, source)++ used.refresh_from_db()+ assert (used.fingerprint, used.rows) == pinned+ assert len(read_table(paths.cell_path(dataset.id, used.id))) == pinned[1]+ assert dataset.cells.count() == 2++def test_error_spans_leave_the_dataset_in_error():project = _project()capability = Capability.objects.create(project=project, name="Support", slug="support")diff --git a/tests/test_local_auth.py b/tests/test_local_auth.pyindex c67f4b84..e01e1acb 100644--- a/tests/test_local_auth.py+++ b/tests/test_local_auth.py@@ -136,3 +136,30 @@ def test_invite_create_without_clerk_skips_email():assert res.status_code == 201invite = ProjectInvite.objects.get(project=project, email="[email protected]")assert invite.clerk_invitation_id == ""+++def test_local_sign_in_attempts_are_limited_per_address():+ User.objects.create_user(email="[email protected]", password="password123")+ client = APIClient()+ statuses = [+ client.post(+ "/api/auth/local/",+ {"email": "[email protected]", "password": f"guess-{n:04d}"},+ format="json",+ # A client can send any forwarded-for value: the count follows the address tried.+ HTTP_X_FORWARDED_FOR=f"203.0.113.{n}",+ ).status_code+ for n in range(11)+ ]+ assert statuses[:10] == [401] * 10+ assert statuses[10] == 429+++def test_an_email_longer_than_the_account_column_is_refused():+ res = APIClient().post(+ "/api/auth/local/",+ {"email": "a" * 250 + "@ops.local", "password": "password123"},+ format="json",+ )+ assert res.status_code == 400+ assert not User.objects.filter(email__startswith="a" * 250).exists()diff --git a/tests/test_mcp_connectors.py b/tests/test_mcp_connectors.pyindex 400ceca7..a061daa4 100644--- a/tests/test_mcp_connectors.py+++ b/tests/test_mcp_connectors.py@@ -627,3 +627,21 @@ def test_prepare_connector_sync_adopts_empty_key_and_wipes_on_name_change():connector.refresh_from_db()assert connector.sync_cursor == {}assert connector.total_traces_imported == 0++[email protected]("tenancy")+def test_sync_and_configure_refuse_a_connector_importing_into_an_unreachable_project(queued):+ context = mcp_context(permission=["read", "write"])+ connector = _connector(context)+ elsewhere = Project.objects.create(name="Elsewhere", slug=f"else-{uuid.uuid4().hex[:6]}")+ ConnectorSyncConfig.objects.filter(credential=connector).update(target_project=elsewhere)++ sync = _call("sync_connector", {"connector": str(connector.id)}, context)+ configure = _call(+ "configure_connector", {"connector": str(connector.id), "lookback_days": 9}, context+ )++ assert sync.structuredContent["error"]["code"] == "permission_denied"+ assert configure.structuredContent["error"]["code"] == "permission_denied"+ assert queued == []+ assert connector.configs.count() == 1diff --git a/tests/test_mcp_observability.py b/tests/test_mcp_observability.pyindex 81161492..f24bf2bf 100644--- a/tests/test_mcp_observability.py+++ b/tests/test_mcp_observability.py@@ -181,6 +181,35 @@ def test_query_traces_exact_session_counts_root_traces():}+def test_query_traces_span_rows_carry_their_own_usage():+ context, capability, _ = _context()+ trace = "3" * 32+ calls = [("call-one", 10, 0.5), ("call-two", 30, 1.5)]+ Span.objects.bulk_create(+ [+ Span(+ span_id=span_id,+ trace_id=trace,+ project=context.project,+ capability=capability,+ name="chat",+ start_time_ns=index,+ attributes={"genai.total_tokens": tokens, "genai.cost": cost},+ usage={"genai.total_tokens": tokens, "genai.cost": cost},+ )+ for index, (span_id, tokens, cost) in enumerate(calls)+ ]+ )++ async def invoke(all_spans):+ return await CATALOG.call("query_traces", {"all_spans": all_spans, "limit": 10}, context)++ spans = async_to_sync(invoke)(True).structuredContent["traces"]+ assert {(r["span_id"], r["total_tokens"], r["total_cost"]) for r in spans} == set(calls)+ traces = async_to_sync(invoke)(False).structuredContent["traces"]+ assert [(r["total_tokens"], r["total_cost"]) for r in traces] == [(40, 2.0)]++@pytest.mark.parametrize("status", ["error", "2"])def test_error_status_aliases_return_error_traces(status):context, capability, _ = _context()diff --git a/tests/test_otlp_dialects.py b/tests/test_otlp_dialects.pyindex 9b8c6d4e..574f0bff 100644--- a/tests/test_otlp_dialects.py+++ b/tests/test_otlp_dialects.py@@ -253,3 +253,93 @@ def test_an_export_over_the_size_limit_is_refused_before_parsing(gzipped):)assert response.status_code == 413assert not Span.objects.filter(project=project).exists()+++def _post_json(project, spans):+ owner = make_user()+ make_member(owner, project)+ export = {"resourceSpans": [{"scopeSpans": [{"spans": spans}]}]}+ return api_key_client(owner, project).post(+ "/api/v1/traces", data=json.dumps(export), content_type="application/json"+ )+++def test_spans_that_cannot_be_stored_are_rejected_without_losing_the_batch():+ project = make_project()+ trace_id, good_id = uuid.uuid4().hex, uuid.uuid4().hex[:16]++ def span(**fields):+ return {"name": "run", "startTimeUnixNano": "1000", "endTimeUnixNano": "9000", **fields}++ response = _post_json(+ project,+ [+ span(traceId=trace_id, spanId=good_id),+ span(traceId="", spanId=""),+ span(traceId=trace_id, spanId="0" * 16),+ span(traceId="0" * 32, spanId=uuid.uuid4().hex[:16]),+ span(+ traceId=trace_id,+ spanId=uuid.uuid4().hex[:16],+ attributes=[{"key": "note", "value": {"stringValue": "a\x00b"}}],+ ),+ span(traceId=trace_id, spanId=uuid.uuid4().hex[:16], name="a\x00b"),+ span(+ traceId=trace_id,+ spanId=uuid.uuid4().hex[:16],+ attributes=[{"key": "type", "value": {"stringValue": "a\x00b"}}],+ ),+ ],+ )++ assert response.status_code == 200, response.content+ assert (response.json()["spans_ingested"], response.json()["spans_rejected"]) == (1, 6)+ assert list(Span.objects.filter(project=project).values_list("span_id", flat=True)) == [good_id]+++def test_measurements_no_clock_can_hold_are_stored_without_them():+ from django.utils import timezone++ project = make_project()+ capability = make_capability(project)+ trace_id = uuid.uuid4().hex+ bound = [{"key": "overmind.capability.id", "value": {"stringValue": str(capability.id)}}]++ def span(name, start, end, *attributes):+ return {+ "traceId": trace_id,+ "spanId": uuid.uuid4().hex[:16],+ "name": name,+ "startTimeUnixNano": str(start),+ "endTimeUnixNano": str(end),+ "attributes": bound + list(attributes),+ }++ response = _post_json(+ project,+ [+ span(+ "infinite tokens",+ 1_000,+ 9_000,+ {"key": "gen_ai.usage.input_tokens", "value": {"stringValue": "inf"}},+ ),+ span("ends before it starts", 9_000, 1_000),+ span(+ "numeric operation",+ 1_000,+ 9_000,+ {"key": "gen_ai.operation.name", "value": {"intValue": "5"}},+ ),+ span("ends in 2096", 1_000, 4_000_000_000_000_000_000),+ ],+ )++ assert response.status_code == 200, response.content+ assert response.json()["spans_ingested"] == 4+ stored = {s.name: s for s in Span.objects.filter(project=project)}+ assert stored["ends before it starts"].duration_ns == 0+ assert stored["numeric operation"].operation == "5"+ capability.refresh_from_db()+ assert capability.last_activity_at is not None+ assert capability.last_activity_at < timezone.now()diff --git a/tests/test_project_invites.py b/tests/test_project_invites.pyindex 282e1153..aed8a3f5 100644--- a/tests/test_project_invites.py+++ b/tests/test_project_invites.py@@ -146,3 +146,13 @@ def test_claim_converts_invites_to_memberships():assert ProjectMembership.objects.filter(user=joiner, project=p1).exists()assert ProjectMembership.objects.filter(user=joiner, project=p2).exists()assert not ProjectInvite.objects.exists()+++def test_an_invite_to_an_email_longer_than_its_column_is_refused():+ owner = make_user("[email protected]")+ project = _project_with(owner)+ r = auth_client(owner).post(+ _invites_url(project), {"email": "a" * 250 + "@person.ai"}, format="json"+ )+ assert r.status_code == 400+ assert not ProjectInvite.objects.filter(project=project).exists()diff --git a/tests/test_projects.py b/tests/test_projects.pyindex 9173ad67..6c004190 100644--- a/tests/test_projects.py+++ b/tests/test_projects.py@@ -203,6 +203,33 @@ def test_partial_update_project():assert r.data["name"] == "Updated"+def test_a_member_cannot_write_server_owned_project_fields():+ u = make_user("[email protected]")+ project = Project.objects.create(+ name="P", slug=f"p-{uuid.uuid4().hex[:6]}", settings={"last_synced_at": "then"}+ )+ ProjectMembership.objects.create(user=u, project=project)++ r = auth_client(u).patch(+ reverse("project-detail", kwargs={"id": project.id}),+ {"is_active": False, "settings": {"repository_snapshot": "forged"}},+ format="json",+ )+ assert r.status_code == 200+ project.refresh_from_db()+ assert (project.is_active, project.settings) == (True, {"last_synced_at": "then"})+++def test_a_deactivated_project_is_hidden_from_its_members():+ u = make_user("[email protected]")+ project = Project.objects.create(name="P", slug=f"p-{uuid.uuid4().hex[:6]}", is_active=False)+ ProjectMembership.objects.create(user=u, project=project)+ client = auth_client(u)++ assert client.get(reverse("project-list")).data["results"] == []+ assert client.get(reverse("project-detail", kwargs={"id": project.id})).status_code == 404++@pytest.mark.covers("ledger")def test_a_member_cannot_remove_the_projects_owner():owner = make_user("[email protected]")diff --git a/tests/test_scoring_isolation.py b/tests/test_scoring_isolation.pyindex 85e87912..51369e7a 100644--- a/tests/test_scoring_isolation.py+++ b/tests/test_scoring_isolation.py@@ -61,3 +61,69 @@ def test_trajectory_scores_only_the_admitted_project():other.refresh_from_db()assert root.eval_attributes["trajectory"]["score"] == pytest.approx(0.8)assert "trajectory" not in other.eval_attributes+++ ("usage", "reported"),+ [({"genai.total_tokens": 12, "genai.cost": 0.5}, "12 tokens, $0.5"), ({}, None)],+ ids=["reported", "unreported"],+)+def test_efficiency_reports_only_the_usage_spans_carry(usage, reported):+ spans = [+ Span(span_id="root", trace_id="t", name="run", start_time_ns=1, end_time_ns=5),+ Span(+ span_id="call",+ trace_id="t",+ parent_span_id="root",+ name="chat",+ span_type="llm_call",+ start_time_ns=2,+ end_time_ns=4,+ usage=usage or None,+ ),+ ]++ reason = async_to_sync(trajectory.EfficiencyEvaluator().score)(spans).reason++ if reported is None:+ assert "tokens" not in reason and "$" not in reason+ else:+ assert reported in reason+++def test_one_span_declares_at_most_the_envelope_cap_of_expectations():+ from overbae.services.transcripts.envelope import MAX_EXPECTATIONS++ attributes = {"overmind.expectations": [f"states fact {n}" for n in range(2000)]}+ assert len(evidence.read_expectations(attributes)) == MAX_EXPECTATIONS++[email protected]("sandbox")+ "body",+ [+ " try:\n 1 / 0\n except Exception as exc:\n match exc:\n"+ " case Exception(__traceback__=tb):\n return 0.0\n",+ " return span.tb.tb_frame.f_back.f_builtins\n",+ " gen = (x for x in [1])\n return gen.gi_frame.f_back.f_globals\n",+ ],+ ids=["match-keyword", "traceback-frame", "generator-frame"],+)+def test_evaluator_code_cannot_reach_the_runners_frames(body):+ assert deterministic.audit(f"def evaluate(span):\n{body}") is not None+++def test_a_comparison_with_no_paired_scores_is_unmeasured_not_unchanged():+ project = make_project()+ baseline = EvalRun.objects.create(project=project, name="baseline")+ candidate = EvalRun.objects.create(project=project, name="candidate")+ for run, row in ((baseline, "a"), (candidate, "b")):+ EvalScore.objects.create(+ project=project, run=run, source_id=row, source_type="dataset_row", score=None+ )++ result = comparison.compare(baseline, candidate)++ assert result["paired"] == 0+ assert result["overall"]["status"] == "unmeasured"diff --git a/tests/test_signals.py b/tests/test_signals.pyindex 5b0cd962..77522565 100644--- a/tests/test_signals.py+++ b/tests/test_signals.py@@ -1,3 +1,4 @@+import timeimport uuidfrom datetime import timedeltafrom types import SimpleNamespace@@ -72,6 +73,28 @@ def test_leak_signal_does_not_treat_timing_decimals_as_card_numbers():)[email protected]("capacity")+def test_leak_signal_scans_a_long_dotted_run_in_linear_time():+ signal = LeakSignal("test")+ text = "a." * 50_000 + " write to [email protected]"+ started = time.monotonic()+ found = async_to_sync(signal.check)([SimpleNamespace(name="run", attributes={"output": text})])+ assert time.monotonic() - started < 1+ assert found == "sensitive data in outputs: run (email)"+++def test_a_signal_config_that_is_not_an_object_is_refused(context):+ _, client = context+ response = client.post(+ "/api/signal-subscriptions/",+ {"project": str(context[0].project.id), "signal_type": "leak", "config": ["x"]},+ format="json",+ )+ assert response.status_code == 400+ assert "config" in response.json()++def test_defaults_generate_session_evidence_without_subscriptions_or_model_calls(context, monkeypatch):diff --git a/tests/test_span_tenancy.py b/tests/test_span_tenancy.pyindex f92f3a9c..67eac8c0 100644--- a/tests/test_span_tenancy.py+++ b/tests/test_span_tenancy.py@@ -81,3 +81,30 @@ def test_one_export_naming_the_same_new_span_for_two_projects_keeps_the_first():assert response.json()["spans_rejected"] == 1span = Span.objects.get(span_id=span_id)assert (span.project_id, span.name) == (first.id, "first.run")++[email protected]("named", ["another tenant's project", "not-a-uuid"])+def test_an_account_key_naming_a_project_it_cannot_reach_is_refused(named):+ user = make_user()+ own, foreign = make_project(member=user), make_project()+ project_id = str(foreign.id) if named == "another tenant's project" else named+ resource = Resource(+ attributes=[KeyValue(key="overmind.project.id", value=AnyValue(string_value=project_id))]+ )+ span = ProtoSpan(+ trace_id=bytes.fromhex(uuid.uuid4().hex),+ span_id=bytes.fromhex(uuid.uuid4().hex[:16]),+ name="run",+ start_time_unix_nano=1_000,+ end_time_unix_nano=9_000,+ )+ request = ExportTraceServiceRequest(+ resource_spans=[ResourceSpans(resource=resource, scope_spans=[ScopeSpans(spans=[span])])]+ )++ response = api_key_client(user).post(+ "/api/v1/traces", data=request.SerializeToString(), content_type="application/x-protobuf"+ )++ assert response.status_code == 403, response.content+ assert not Span.objects.filter(project__in=[own, foreign]).exists()diff --git a/tests/test_sync_api.py b/tests/test_sync_api.pyindex 81c7bae6..40999ac6 100644--- a/tests/test_sync_api.py+++ b/tests/test_sync_api.py@@ -260,3 +260,31 @@ def test_evaluation_definitions_distinguish_catalogue_code_config_and_custom(clirow.save(update_fields=["source"])response = client.get(f"/api/eval-matrix/{row.pk}/")assert response.data["definition_source"] == "unknown"+++ "capabilities",+ [+ [_cap(name="n" * 300)],+ [_cap(source_path="p" * 600)],+ [_cap(), _cap(name="Support Agent Two")],+ ],+ ids=["long-name", "long-path", "duplicate-slug"],+)+def test_a_snapshot_that_cannot_be_stored_as_given_is_refused(client, capabilities):+ response = client.post("/api/v1/sync", _snapshot(capabilities), format="json")+ assert response.status_code == 400+ assert not Capability.objects.filter(project_id=PROJECT_ID).exists()+++def test_two_blocks_that_name_one_capability_by_slug_and_by_id_are_refused(client):+ first = client.post("/api/v1/sync", _snapshot([_cap()]), format="json")+ assert first.status_code == 200, first.data+ cap = Capability.objects.get(project_id=PROJECT_ID)+ twice = [_cap(), _cap(id=str(cap.id), slug="renamed", name="Renamed")]+ response = client.post("/api/v1/sync", _snapshot(twice), format="json")+ assert response.status_code == 400+ cap.refresh_from_db()+ assert cap.name == "Support Agent"diff --git a/tests/test_trace_usage_aggregation.py b/tests/test_trace_usage_aggregation.pyindex d1cff968..2a3f1e09 100644--- a/tests/test_trace_usage_aggregation.py+++ b/tests/test_trace_usage_aggregation.py@@ -292,6 +292,34 @@ def test_list_orders_by_aggregated_total_tokens():assert desc_ids == [high, low]+def test_list_orders_and_filters_past_usage_text_that_is_not_a_number():+ client, project = _client_and_project()+ counted = uuid.uuid4().hex[:32]+ garbled = uuid.uuid4().hex[:32]+ _span(project, trace_id=counted, attributes={"genai.total_tokens": 10, "genai.cost": 0.5})+ _span(+ project, trace_id=garbled, attributes={"genai.total_tokens": "n/a", "genai.cost": "1e999"}+ )++ for params in (+ {"ordering": "-total_cost"},+ {"ordering": "total_tokens"},+ {"total_cost__gte": 0.1},+ {"total_tokens__gte": 1},+ ):+ response = client.get(TRACES_URL, {**params, "project": project.id})+ assert response.status_code == 200, params+ assert counted in {row["trace_id"] for row in response.json()["results"]}++[email protected]("http-api")+def test_a_lookup_by_a_value_its_column_cannot_hold_is_refused():+ client, _ = _client_and_project()+ response = client.get("/api/datasets/", {"project": "not-a-uuid"})+ assert response.status_code == 400+ assert response.json()["code"] == "invalid"++def test_list_orders_by_model_and_eval_score():client, project = _client_and_project()a = uuid.uuid4().hex[:32]