-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtasks.py
More file actions
1803 lines (1595 loc) · 65.7 KB
/
Copy pathtasks.py
File metadata and controls
1803 lines (1595 loc) · 65.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import json
import logging
from datetime import datetime
from typing import TYPE_CHECKING, Annotated, cast
from fastapi import (
APIRouter,
Depends,
Header,
HTTPException,
Query,
Request,
Response,
status,
)
from harbor.models.environment_type import EnvironmentType
from sqlalchemy import or_, select
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession
from cloud_policy import (
ALLOWED_CLOUD_ENVIRONMENTS,
get_default_cloud_environment,
)
from oddish.dispatch.backends.modal import ModalDispatcher
from oddish.dispatch.ports import WorkerHandle
from oddish.filters.trial_metrics import TrialMetricFilter
from oddish.core.endpoints import (
backfill_task_analysis_core,
browse_experiment_options_core,
browse_task_facets_core,
browse_tasks_core,
rerun_pre_trial_audit_core,
build_task_sweep_response,
cancel_task_qa_core,
combine_experiments_core,
create_task_sweep_batch_core,
create_task_sweep_core,
delete_experiment_core,
delete_task_core,
get_experiment_cost_totals,
get_task_detail_core,
get_task_for_org_core,
get_task_status_core,
get_task_version_core,
list_experiment_slim_tasks,
list_experiment_task_shells_core,
list_tasks_core,
replay_has_retryable_failed_trials,
list_task_versions_core,
rerun_task_qa_core,
set_task_default_version_core,
unlink_task_from_experiment_core,
)
from oddish.core.helpers import terminate_run_harvest
from oddish.core.dashboard import (
invalidate_dashboard_cache,
)
from oddish.core.experiments import (
list_experiment_probes_core,
list_org_probes_core,
)
from oddish.core.sharing.helpers import (
ensure_experiment_public,
get_task_file_content_s3,
list_task_files_s3,
make_task_files_ndjson_response,
stream_task_files_s3,
)
from oddish.core.idempotency import (
IdempotencyReplay,
SWEEP_ROUTE,
compute_request_hash,
probe_completed_replay,
)
from idempotency_store import SubmissionIdempotencyStore
from api.schemas import (
ExperimentShareResponse,
ExperimentUpdateRequest,
ExperimentUpdateResponse,
)
from auth import APIKeyScope, AuthContext, require_admin, require_auth
from api.routers.task_submission import (
apply_github_attribution,
maybe_publish_experiment,
require_connected_github_user,
require_experiment_publish_scope,
resolve_actor_user_string,
resolve_billed_user_id,
resolve_created_by_user_id,
resolve_experiment_owner_user_id,
resolve_submission_identity,
stamp_experiment_owner,
)
from dashboard_attribution import resolve_search_authors
from oddish.core.tasks import (
complete_task_upload,
initialize_task_upload,
)
from oddish.db import (
ExperimentModel,
TaskModel,
get_session,
utcnow,
)
from oddish.timing import TimingRecorder, add_server_timing_metric, elapsed_ms, now
from oddish.queue import (
cancel_tasks_runs,
)
from oddish.core.endpoints.collections import (
add_to_collection_core,
create_trial_collection_core,
remove_from_collection_core,
rename_collection_core,
)
from oddish.schemas import (
BackfillQARequest,
CollectionAddRequest,
CollectionMutationResponse,
CollectionRemoveRequest,
CollectionRenameRequest,
ExperimentCombineRequest,
ExperimentCombineResponse,
ExperimentCostTotals,
ExperimentOptionsResponse,
ExperimentProbeRow,
OrgProbeRow,
TaskBrowseFacets,
TaskBrowseResponse,
TaskBatchCancelRequest,
TaskDetailResponse,
TaskUploadCompleteRequest,
TaskUploadInitRequest,
TaskUploadInitResponse,
TaskResponse,
TaskStatusResponse,
TaskSweepBatchRequest,
TaskSweepBatchResponse,
TaskSweepSubmission,
TaskVersionResponse,
TrialCollectionRequest,
TrialCollectionResponse,
UploadResponse,
)
if TYPE_CHECKING:
from models import UserModel
router = APIRouter(tags=["Tasks"])
logger = logging.getLogger(__name__)
async def _spawn_gke_image_builds(session: AsyncSession, task_ids: list[str]) -> None:
"""Fire the upload-time image builder for GKE-classified tasks (post-commit).
Primary build path: the worker-side auto_build_missing_image fallback only
covers the race where a trial claims before this build lands. Best-effort
by design -- a spawn failure must never fail a committed submission (the
worker fallback and the clear missing-image error remain behind it).
"""
if not task_ids:
return
try:
import os
import modal
# Spawn by name: importing worker.functions here would re-run Modal
# function registration inside the API container. from_name resolves
# the deployed function directly; GKE-less deploys never register it
# and the NotFoundError lands in the catch below.
builder = modal.Function.from_name(
os.environ.get("MODAL_APP_NAME", "oddish"),
"build_gke_task_image",
environment_name=os.environ.get("MODAL_ENVIRONMENT") or None,
)
from oddish.db.models import TaskModel, TaskVersionModel, TrialModel
# Scoped to trials ON the task's current version: stale GKE trials
# from older versions must not trigger builds for content they never
# ran. If a concurrent submission bumps the version between commit and
# this query, the build targets the newer content and the older
# trials' worker-side auto-build fallback covers the gap.
gke_rows = await session.execute(
select(TrialModel.task_id, TaskVersionModel.version)
.join(TaskModel, TaskModel.id == TrialModel.task_id)
.join(
TaskVersionModel,
TaskVersionModel.id == TaskModel.current_version_id,
)
.where(
TrialModel.task_id.in_(task_ids),
TrialModel.task_version_id == TaskModel.current_version_id,
# Environment is the routing truth: allowlisted harbor-gke
# pins at non-blessed SHAs classify as the ephemeral variant
# yet still run on GKE and need the prebuilt image.
or_(
TrialModel.environment == "gke",
TrialModel.harbor_config["variant_id"].astext == "gke",
),
)
.distinct()
)
for task_id, version in gke_rows:
try:
await builder.spawn.aio(task_id=task_id, version=version)
except modal.exception.NotFoundError:
# GKE-less deploy: the builder function isn't registered, so
# every remaining spawn would fail identically -- let the
# outer catch log it once.
raise
except Exception:
logger.exception(
"GKE image build spawn failed for task %s v%s (non-fatal)",
task_id,
version,
)
continue
logger.info("spawned GKE image build for task %s v%s", task_id, version)
except Exception:
logger.exception("GKE image build spawn failed (non-fatal)")
def _make_timing_recorder(request: Request) -> TimingRecorder:
def _record(name: str, duration_ms: float, description: str | None = None) -> None:
add_server_timing_metric(request, name, duration_ms, description)
return _record
def _split_tag_csv(csv: str | None) -> list[str]:
return [s.strip() for s in (csv or "").split(",") if s.strip()]
async def _cancel_modal_function_calls(modal_fc_ids: list[str]) -> int:
"""Terminate in-flight Modal worker containers by function-call id.
Resolves the persisted handles to the registered ``ModalDispatcher`` rather
than reaching into ``modal.FunctionCall`` here, so the control-plane cancel
is host-agnostic (design spec §6.4). Behavior is unchanged — the dispatcher
runs the same batched ``cancel.aio(terminate_containers=True)``.
"""
handles = [
WorkerHandle(provider=ModalDispatcher.name, queue_key="", id=fc_id)
for fc_id in modal_fc_ids
if fc_id
]
return await ModalDispatcher().cancel(handles)
# =============================================================================
# Task Upload and Creation
# =============================================================================
@router.post("/tasks/upload/init", response_model=TaskUploadInitResponse)
async def init_task_upload(
payload: TaskUploadInitRequest,
auth: Annotated[AuthContext, Depends(require_auth)],
) -> TaskUploadInitResponse:
"""Prepare a task upload and return a presigned PUT URL when S3 is enabled."""
auth.require_scope(APIKeyScope.TASKS)
return await initialize_task_upload(
payload.name,
org_id=auth.org_id,
content_hash=payload.content_hash,
message=payload.message,
force_new_version=payload.force_new_version,
)
@router.post("/tasks/upload/complete", response_model=UploadResponse)
async def finalize_task_upload(
payload: TaskUploadCompleteRequest,
auth: Annotated[AuthContext, Depends(require_auth)],
) -> UploadResponse:
"""Finalize a direct task upload after the client PUTs the archive to S3."""
auth.require_scope(APIKeyScope.TASKS)
resolved_user = payload.user
if payload.register_task and not resolved_user:
async with get_session() as session:
resolved_user = await resolve_actor_user_string(
session,
auth,
explicit_user=payload.user,
explicit_github_username=None,
)
return await complete_task_upload(
task_id=payload.task_id,
task_name=payload.name,
version=payload.version,
content_hash=payload.content_hash,
message=payload.message,
org_id=auth.org_id,
created_by_user_id=auth.user_id,
register=payload.register_task,
user=resolved_user,
priority=payload.priority,
)
@router.post("/tasks/sweep", response_model=TaskResponse)
async def create_task_sweep(
submission: TaskSweepSubmission,
auth: Annotated[AuthContext, Depends(require_auth)],
idempotency_key: Annotated[str | None, Header(alias="Idempotency-Key")] = None,
) -> TaskResponse:
"""Submit a task sweep - expands a task_id into many trials.
A retried submission carrying the same ``Idempotency-Key`` replays the
original response instead of creating duplicate trials while its current
trial leaves are non-failed. Failed leaves turn the same declarative sweep
into immutable replacement trials.
"""
auth.require_scope(APIKeyScope.TASKS)
from oddish.core.sweeps import validate_sweep_submission
validate_sweep_submission(submission)
# Fingerprint the raw client submission BEFORE the backend mutates it
# (identity / GitHub attribution). Those defaults can resolve differently
# between attempts, so hashing post-mutation would spuriously 409 an honest
# retry; hashing the raw body keeps retries faithful.
request_hash = compute_request_hash(submission)
async with get_session() as session:
# A COMPLETED, hash-matched, unexpired idempotency record normally
# replays BEFORE the linkage gate: a faithful transport retry must not
# 403 just because linked-user state changed after submission. A failed
# current leaf is different: it makes this an intentional rerun, so it
# falls through the current linkage/billing gates and sweep reconcile.
if idempotency_key:
replay_json = await probe_completed_replay(
SubmissionIdempotencyStore(session),
org_id=auth.org_id,
route=SWEEP_ROUTE,
raw_key=idempotency_key,
request_hash=request_hash,
now=utcnow(),
)
if replay_json is not None:
if await replay_has_retryable_failed_trials(
session, replay_json, org_id=auth.org_id
):
# The stable CLI key normally identifies a transport replay.
# Once its current retry-chain leaf has failed, the same
# command is instead an intentional retry. Reconciliation is
# task-row locked, so bypassing the old reservation remains
# duplicate-safe under concurrent submissions.
idempotency_key = None
else:
return TaskResponse.model_validate(replay_json)
await resolve_submission_identity(session, submission, auth)
apply_github_attribution(submission)
# Unconditional linkage gate: a truthy github_id that resolves to no
# active org user is rejected here, before any rows are written.
connected_user = await require_connected_github_user(session, submission, auth)
# Billing follows the resolved owner (submitted github_id/github_username,
# github_id first), else the API-key owner / submitter. Reuse the
# linkage-gate user so we don't re-query it.
owner_user_id = await resolve_experiment_owner_user_id(
session, submission, auth, connected_user
)
billed_user_id = await resolve_billed_user_id(
session, submission, auth, owner_user_id=owner_user_id
)
try:
task, new_trials, is_append, experiment = await create_task_sweep_core(
session,
submission=submission,
org_id=auth.org_id,
billed_user_id=billed_user_id,
default_environment=get_default_cloud_environment(submission),
allowed_environments=ALLOWED_CLOUD_ENVIRONMENTS,
idempotency_key=idempotency_key,
idempotency_store=SubmissionIdempotencyStore(session),
request_hash=request_hash,
)
except TimeoutError as exc:
# asyncpg raises bare TimeoutError on DB wait timeouts.
logger.error(
"create_task_sweep timed out for task_id=%s org_id=%s",
submission.task_id,
auth.org_id,
exc_info=exc,
)
raise HTTPException(
status_code=503,
detail=(
"Couldn't submit right now (database lock timeout). Please retry."
),
) from exc
except SQLAlchemyError as exc:
logger.error(
"create_task_sweep failed for task_id=%s org_id=%s",
submission.task_id,
auth.org_id,
exc_info=exc,
)
raise HTTPException(
status_code=503,
detail="Couldn't submit right now (database error). Please retry.",
) from exc
except IdempotencyReplay as replay:
# Faithful retry of a completed key: return the stored response and
# skip the owner-stamping / publish side effects below. The image
# build spawn IS retried though -- it is best-effort on the
# original request and the builder is idempotent (checks the
# registry first), so a replay is the natural recovery hook when
# the original spawn failed.
response = TaskResponse.model_validate(replay.response_json)
replay_task_id = getattr(response, "id", None)
if replay_task_id:
await _spawn_gke_image_builds(session, [replay_task_id])
return response
stamp_experiment_owner(experiment, owner_user_id, claim_unowned=not is_append)
if not is_append:
created_by_user_id = await resolve_created_by_user_id(
session, submission, auth, connected_user
)
if created_by_user_id:
task.created_by_user_id = created_by_user_id
task.api_key_id = auth.api_key_id
await maybe_publish_experiment(session, task, submission, auth)
elif experiment and submission.publish_experiment:
require_experiment_publish_scope(auth)
await ensure_experiment_public(session, experiment)
await session.commit()
await _spawn_gke_image_builds(session, [task.id])
return build_task_sweep_response(task, new_trials, is_append, experiment)
@router.post("/tasks/sweep/batch", response_model=TaskSweepBatchResponse)
async def create_task_sweep_batch(
payload: TaskSweepBatchRequest,
auth: Annotated[AuthContext, Depends(require_auth)],
response: Response,
) -> TaskSweepBatchResponse:
"""Submit several task sweeps in one request (best-effort, per-item status).
Each submission is created inside its own savepoint, so one bad item neither
aborts the batch nor rolls back items that already succeeded. ``results`` is
a per-item status array indexed to ``submissions``. Returns HTTP 200 when
every item succeeds and HTTP 207 Multi-Status when at least one item fails --
callers must inspect each item's ``success``/``status_code``.
Per-item idempotency-key replay is intentionally not handled here; request
idempotency is separate in-flight work and will layer on top of this path.
"""
auth.require_scope(APIKeyScope.TASKS)
if not payload.submissions:
raise HTTPException(
status_code=400, detail="Must specify at least one submission"
)
connected_users: dict[int, UserModel | None] = {}
async def _prepare(
session: AsyncSession, submission: TaskSweepSubmission
) -> EnvironmentType | None:
# Per-item, auth-aware setup. Runs in the batch core's read-only
# pre-loop (identity -> attribution -> billed, same order as the single
# route); a failure fails only this item.
await resolve_submission_identity(session, submission, auth)
apply_github_attribution(submission)
# Unconditional linkage gate: a truthy github_id resolving to no active
# org user raises 403 here; the batch core catches it and fails only
# this item (rolling back its savepoint) before any rows are written.
connected_users[id(submission)] = await require_connected_github_user(
session, submission, auth
)
return get_default_cloud_environment(submission)
# Owner resolved once in the pre-loop (inside _resolve_billed) and reused
# by _finalize -- same single-resolution shape as the single route.
owners: dict[int, str | None] = {}
async def _resolve_billed(
session: AsyncSession, submission: TaskSweepSubmission
) -> str | None:
owner_user_id = await resolve_experiment_owner_user_id(
session, submission, auth
)
owners[id(submission)] = owner_user_id
return await resolve_billed_user_id(
session, submission, auth, owner_user_id=owner_user_id
)
async def _finalize(
session: AsyncSession,
submission: TaskSweepSubmission,
task: TaskModel,
is_append: bool,
experiment: ExperimentModel | None,
) -> None:
# Post-create stamping, inside the savepoint (mirrors the single route).
# Owner was resolved once in _resolve_billed; connected_user (linkage
# gate) is reused for created_by resolution below.
connected_user = connected_users.get(id(submission))
owner_user_id = owners.get(id(submission))
stamp_experiment_owner(experiment, owner_user_id, claim_unowned=not is_append)
if not is_append:
created_by_user_id = await resolve_created_by_user_id(
session, submission, auth, connected_user
)
if created_by_user_id:
task.created_by_user_id = created_by_user_id
task.api_key_id = auth.api_key_id
await maybe_publish_experiment(session, task, submission, auth)
elif experiment and submission.publish_experiment:
require_experiment_publish_scope(auth)
await ensure_experiment_public(session, experiment)
async with get_session() as session:
results = await create_task_sweep_batch_core(
session,
submissions=payload.submissions,
org_id=auth.org_id,
allowed_environments=ALLOWED_CLOUD_ENVIRONMENTS,
prepare=_prepare,
finalize=_finalize,
resolve_billed_user_id=_resolve_billed,
)
await session.commit()
await _spawn_gke_image_builds(
session,
[r.task.id for r in results if r.success and r.task is not None],
)
succeeded = sum(1 for r in results if r.success)
failed = len(results) - succeeded
# 207 Multi-Status whenever any item failed; the body carries per-item
# outcomes so the client never has to rely on the top-level status alone.
if failed:
response.status_code = status.HTTP_207_MULTI_STATUS
return TaskSweepBatchResponse(
total=len(results),
succeeded=succeeded,
failed=failed,
results=results,
)
# =============================================================================
# Task Listing and Retrieval
# =============================================================================
@router.get("/tasks", response_model=list[TaskStatusResponse])
async def list_tasks(
request: Request,
auth: Annotated[AuthContext, Depends(require_auth)],
status: str | None = None,
user: str | None = None,
experiment_id: str | None = None,
include_trials: bool = False,
compact_trials: bool = False,
compact_tasks: bool = False,
include_queue_info: bool = True,
include_worker_jobs: bool = True,
limit: int = Query(100, ge=1, le=2000),
offset: int = 0,
) -> list[TaskStatusResponse]:
"""List tasks for the authenticated organization.
``compact_tasks=true`` is a fast-path used by the experiment page
first paint: it implies ``include_trials=false`` and skips the
per-task ``visible_worker_jobs`` and ``effective_version_ids``
lookups. The phase-2 batched fetch (``include_trials=true``) fills
those columns in afterwards.
"""
auth.require_scope(APIKeyScope.READ)
async with get_session() as session:
connect_started_at = now()
await session.connection()
add_server_timing_metric(
request,
"db_connect",
elapsed_ms(connect_started_at),
"Tasks DB connect",
)
tasks = await list_tasks_core(
session,
status=status,
user=user,
experiment_id=experiment_id,
include_trials=include_trials,
compact_trials=compact_trials,
compact_tasks=compact_tasks,
include_queue_info=include_queue_info,
include_worker_jobs=include_worker_jobs,
limit=limit,
offset=offset,
org_id=auth.org_id,
include_empty_rewards=True,
record_timing=_make_timing_recorder(request),
)
return tasks
@router.get(
"/experiments/{experiment_id}/task-shells",
response_model=list[TaskStatusResponse],
)
async def list_experiment_task_shells(
request: Request,
experiment_id: str,
auth: Annotated[AuthContext, Depends(require_auth)],
limit: int = Query(2000, ge=1, le=2000),
offset: int = 0,
) -> list[TaskStatusResponse]:
"""Lightweight task shells for the experiment-details first paint.
A dedicated, trimmed alternative to ``GET /tasks?...&compact_tasks=true``
that additionally drops the per-task ``experiments`` fan-out. The generic
``/tasks`` route (and ``list_tasks_core``) are intentionally left unchanged;
only the experiment-page first paint should call this.
"""
auth.require_scope(APIKeyScope.READ)
async with get_session() as session:
connect_started_at = now()
await session.connection()
add_server_timing_metric(
request,
"db_connect",
elapsed_ms(connect_started_at),
"Task shells DB connect",
)
return await list_experiment_task_shells_core(
session,
experiment_id=experiment_id,
org_id=auth.org_id,
limit=limit,
offset=offset,
include_empty_rewards=True,
record_timing=_make_timing_recorder(request),
)
@router.get(
"/experiments/{experiment_id}/cost-totals",
response_model=ExperimentCostTotals,
)
async def get_experiment_cost_totals_route(
experiment_id: str,
auth: Annotated[AuthContext, Depends(require_auth)],
) -> ExperimentCostTotals:
"""The experiment's spend rollup: member-wide cost + owned "new spend".
``cost_*`` prices every trial the page renders (homed or gathered, the
grid's membership); ``owned_*`` only what the experiment ran itself — the
additive number (``core.endpoints.experiment_cost``). Deliberately wider
than the grid routes above: those page their trials (so the page can't sum
cost client-side without loading all of them) and scope each task to its
current version (so they omit earlier versions, superseded retries and
probes -- all of which were still billed). One grouped query.
"""
auth.require_scope(APIKeyScope.READ)
async with get_session() as session:
return await get_experiment_cost_totals(
session, experiment_id=experiment_id, org_id=auth.org_id
)
@router.get(
"/experiments/{experiment_id}/slim-tasks",
response_model=list[TaskStatusResponse],
)
async def list_experiment_slim_tasks_route(
request: Request,
experiment_id: str,
auth: Annotated[AuthContext, Depends(require_auth)],
limit: int = Query(2000, ge=1, le=2000),
offset: int = 0,
) -> list[TaskStatusResponse]:
"""Phase-2 grid data with SLIM per-trial payloads for the experiment page.
Like the experiment-scoped ``GET /tasks?include_trials=true`` path, but
each trial carries only the fields the grid renders (+ cost). Heavy
per-trial detail is fetched on demand via ``GET /trials/{trial_id}`` when a
cell is clicked. The generic ``/tasks`` route is left unchanged; only the
experiment-page Phase-2 fetch should call this.
"""
auth.require_scope(APIKeyScope.READ)
async with get_session() as session:
connect_started_at = now()
await session.connection()
add_server_timing_metric(
request,
"db_connect",
elapsed_ms(connect_started_at),
"Slim tasks DB connect",
)
return await list_experiment_slim_tasks(
session,
experiment_id=experiment_id,
org_id=auth.org_id,
limit=limit,
offset=offset,
include_empty_rewards=True,
record_timing=_make_timing_recorder(request),
)
@router.get("/tasks/browse", response_model=TaskBrowseResponse)
async def browse_tasks(
request: Request,
auth: Annotated[AuthContext, Depends(require_auth)],
limit: int = Query(25, ge=1, le=100),
offset: int = Query(0, ge=0),
query: str | None = None,
tags: str | None = Query(None),
tags_any: str | None = Query(None),
tags_none: str | None = Query(None),
author: str | None = Query(
None,
description=(
"Author search (the github:/author:/user: qualifier). Comma-separated "
"tokens, each resolved to matching org members + their aliases and "
"ANDed with the free-text and tag filters."
),
),
statuses: str | None = Query(None, description="Task status CSV"),
priorities: str | None = Query(None, description="Task priority CSV"),
verdict_statuses: str | None = Query(None, description="Task verdict status CSV"),
has_link: bool | None = Query(None),
run_analysis: bool | None = Query(None),
run_probe: bool | None = Query(None),
created_after: datetime | None = Query(None),
created_before: datetime | None = Query(None),
trial_finished_after: datetime | None = Query(None),
trial_finished_before: datetime | None = Query(None),
experiment_ids: str | None = Query(None, description="Experiment id CSV"),
agents: str | None = Query(None, description="Trial agent CSV"),
models: str | None = Query(None, description="Trial model CSV"),
agent_models: str | None = Query(
None, description="Agent+model pair CSV, each 'agent:model'"
),
providers: str | None = Query(None, description="Trial provider CSV"),
environments: str | None = Query(None, description="Trial environment CSV"),
trial_statuses: str | None = Query(None, description="Trial status CSV"),
origins: str | None = Query(None, description="Trial origin CSV"),
trial_is_probe: bool | None = Query(None),
harbor_shas: str | None = Query(None, description="Harbor SHA CSV"),
harbor_stages: str | None = Query(None, description="Harbor stage CSV"),
analysis_classifications: str | None = Query(
None, description="Trial analysis classification CSV"
),
has_error: bool | None = Query(None),
has_trajectory: bool | None = Query(None),
min_attempts: int | None = Query(None, ge=1),
min_tokens: int | None = Query(None, ge=0),
max_tokens: int | None = Query(None, ge=0),
min_steps: int | None = Query(None, ge=0),
max_steps: int | None = Query(None, ge=0),
min_duration_seconds: float | None = Query(None, ge=0),
max_duration_seconds: float | None = Query(None, ge=0),
min_tool_calls: int | None = Query(None, ge=0),
max_tool_calls: int | None = Query(None, ge=0),
tool_names: str | None = Query(None, description="Tool function name CSV"),
tool_count_mins: str | None = Query(
None, description="JSON object of tool name to minimum count"
),
trial_metric_match: str = Query("any", pattern="^(any|all)$"),
reward_min: float | None = Query(None, ge=0.0, le=1.0),
reward_max: float | None = Query(None, ge=0.0, le=1.0),
# --- Phase 1.2-lite aggregate filters / sort (computed on the fly) ---
avg_score_min: float | None = Query(
None, ge=0.0, le=100.0, description="Task avg score percent (0-100), min"
),
avg_score_max: float | None = Query(
None, ge=0.0, le=100.0, description="Task avg score percent (0-100), max"
),
total_tokens_min: int | None = Query(None, ge=0),
total_tokens_max: int | None = Query(None, ge=0),
total_trials_min: int | None = Query(None, ge=1),
completed_trials_min: int | None = Query(None, ge=1),
failed_trials_min: int | None = Query(None, ge=1),
pass_count_min: int | None = Query(None, ge=1),
partial_count_min: int | None = Query(None, ge=1),
fail_count_min: int | None = Query(None, ge=1),
harness_count_min: int | None = Query(None, ge=1),
runtime_total_min: float | None = Query(
None, ge=0.0, description="Task total run time (seconds), min"
),
runtime_total_max: float | None = Query(
None, ge=0.0, description="Task total run time (seconds), max"
),
runtime_avg_min: float | None = Query(
None, ge=0.0, description="Task avg run time per trial (seconds), min"
),
runtime_avg_max: float | None = Query(
None, ge=0.0, description="Task avg run time per trial (seconds), max"
),
pass_rate_min: float | None = Query(
None, ge=0.0, le=100.0, description="Task pass rate percent (0-100), min"
),
pass_rate_max: float | None = Query(
None, ge=0.0, le=100.0, description="Task pass rate percent (0-100), max"
),
sort: str | None = Query(
None,
description=(
"Aggregate sort: cost_desc, avg_score_(asc|desc), "
"total_tokens_(asc|desc), runtime_total_(asc|desc), or "
"runtime_avg_(asc|desc). Unknown/absent keeps the default recency "
"order."
),
),
# --- Phase 2.1 agent/model comparison (computed on the fly) ---
compare_by: str | None = Query(
None, description="Compare subject column: 'agent' or 'model'"
),
compare_a: str | None = Query(None, description="Subject A (agent/model name)"),
compare_b: str | None = Query(None, description="Subject B (agent/model name)"),
compare_metric: str | None = Query(
None,
description="Compare metric: reward | runtime | tokens | steps | pass_rate",
),
compare_agg: str | None = Query(
None,
description=(
"Reduce each subject's trials by: best | avg | median (default best; "
"ignored for pass_rate)"
),
),
compare_margin: float | None = Query(
None, ge=0.0, description="A must beat B by more than this (0/absent = any)"
),
compare_margin_unit: str | None = Query(
None, description="Margin unit: 'pct' (percent of B, default) or 'abs'"
),
top_by: str | None = Query(
None, description="Top performer subject column: 'agent' or 'model'"
),
top_value: str | None = Query(
None, description="The subject that must be the task's top performer"
),
top_metric: str | None = Query(
None,
description="Top performer metric: reward | runtime | tokens | steps | pass_rate",
),
or_groups: str | None = Query(
None,
description=(
"Phase 2.2 'Match any of…' OR-groups: URL-encoded JSON list of "
"condition dicts (each dict uses the same field keys as the flat "
"params). A task matches if it satisfies ANY group; the block is "
"ANDed with the flat filters."
),
),
) -> TaskBrowseResponse:
"""Browse latest task versions for the authenticated organization."""
auth.require_scope(APIKeyScope.READ)
async with get_session() as session:
connect_started_at = now()
await session.connection()
add_server_timing_metric(
request,
"db_connect",
elapsed_ms(connect_started_at),
"Browse DB connect",
)
author_tokens = [
token.strip() for token in (author or "").split(",") if token.strip()
]
if author_tokens:
(
author_user_ids,
author_github_usernames,
author_emails,
) = await resolve_search_authors(
session, org_id=auth.org_id, tokens=author_tokens
)
else:
author_user_ids = ()
author_github_usernames = ()
author_emails = ()
# Parse the OR-groups JSON defensively: a bad/deep-linked value must not
# 500 the browse; keep only dict groups, drop the rest.
parsed_or_groups: list[dict] | None = None
if or_groups:
try:
loaded = json.loads(or_groups)
except (ValueError, TypeError):
loaded = None
if isinstance(loaded, list):
parsed_or_groups = [g for g in loaded if isinstance(g, dict)] or None
try:
metric_filter = TrialMetricFilter.from_query(
models=models,
min_steps=min_steps,
max_steps=max_steps,
min_duration_seconds=min_duration_seconds,
max_duration_seconds=max_duration_seconds,
min_tool_calls=min_tool_calls,
max_tool_calls=max_tool_calls,
tool_names=tool_names,
tool_count_mins=tool_count_mins,
match=trial_metric_match,
)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
return await browse_tasks_core(
session,
org_id=auth.org_id,
limit=limit,
offset=offset,
query=query,
tags_all=_split_tag_csv(tags),
tags_any=_split_tag_csv(tags_any),
tags_none=_split_tag_csv(tags_none),
author_user_ids=author_user_ids,
author_github_usernames=author_github_usernames,
author_emails=author_emails,
statuses=_split_tag_csv(statuses),
priorities=_split_tag_csv(priorities),
verdict_statuses=_split_tag_csv(verdict_statuses),
has_link=has_link,
run_analysis=run_analysis,
run_probe=run_probe,
created_after=created_after,
created_before=created_before,
trial_finished_after=trial_finished_after,
trial_finished_before=trial_finished_before,
experiment_ids=_split_tag_csv(experiment_ids),
agents=_split_tag_csv(agents),
models=metric_filter.models,
agent_models=_split_tag_csv(agent_models),
providers=_split_tag_csv(providers),
environments=_split_tag_csv(environments),
trial_statuses=_split_tag_csv(trial_statuses),
origins=_split_tag_csv(origins),
trial_is_probe=trial_is_probe,
harbor_shas=_split_tag_csv(harbor_shas),
harbor_stages=_split_tag_csv(harbor_stages),
analysis_classifications=_split_tag_csv(analysis_classifications),
has_error=has_error,
has_trajectory=has_trajectory,
min_attempts=min_attempts,
min_tokens=min_tokens,
max_tokens=max_tokens,
min_steps=metric_filter.min_steps,
max_steps=metric_filter.max_steps,
min_duration_seconds=metric_filter.min_duration_seconds,
max_duration_seconds=metric_filter.max_duration_seconds,
min_tool_calls=metric_filter.min_tool_calls,
max_tool_calls=metric_filter.max_tool_calls,
tool_names=metric_filter.tool_names,
tool_count_mins=metric_filter.tool_count_mins,
trial_metric_match=metric_filter.match.value,
reward_min=reward_min,
reward_max=reward_max,
avg_score_min=avg_score_min,
avg_score_max=avg_score_max,
total_tokens_min=total_tokens_min,
total_tokens_max=total_tokens_max,
total_trials_min=total_trials_min,
completed_trials_min=completed_trials_min,
failed_trials_min=failed_trials_min,
pass_count_min=pass_count_min,
partial_count_min=partial_count_min,
fail_count_min=fail_count_min,
harness_count_min=harness_count_min,
runtime_total_min=runtime_total_min,
runtime_total_max=runtime_total_max,
runtime_avg_min=runtime_avg_min,
runtime_avg_max=runtime_avg_max,
pass_rate_min=pass_rate_min,
pass_rate_max=pass_rate_max,
sort=sort,
compare_by=compare_by,
compare_a=compare_a,
compare_b=compare_b,
compare_metric=compare_metric,