Skip to content

prefect.server.models.flow_runs

Functions for interacting with flow run ORM objects. Intended for internal use by the Prefect REST API.

cleanup_flow_run_concurrency_slots(session, flow_run) async

Cleanup flow run related resources, such as releasing concurrency slots. All operations should be idempotent and safe to call multiple times. IMPORTANT: This run may no longer exist in the database when this operation occurs.

Source code in src/prefect/server/models/flow_runs.py
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
async def cleanup_flow_run_concurrency_slots(
    session: AsyncSession,
    flow_run: orm_models.FlowRun,
):
    """
    Cleanup flow run related resources, such as releasing concurrency slots.
    All operations should be idempotent and safe to call multiple times.
    IMPORTANT: This run may no longer exist in the database when this operation occurs.
    """

    if (
        flow_run.deployment_id
        and flow_run.state
        and flow_run.state.type
        in (
            schemas.states.StateType.PENDING,
            schemas.states.StateType.RUNNING,
            schemas.states.StateType.CANCELLING,
        )
    ):
        deployment = await models.deployments.read_deployment(
            session, flow_run.deployment_id
        )
        if deployment and deployment.concurrency_limit_id:
            await models.concurrency_limits_v2.bulk_decrement_active_slots(
                session, [deployment.concurrency_limit_id], 1
            )

count_flow_runs(session, flow_filter=None, flow_run_filter=None, task_run_filter=None, deployment_filter=None, work_pool_filter=None, work_queue_filter=None) async

Count flow runs.

Parameters:

Name Type Description Default
session AsyncSession

a database session

required
flow_filter Optional[FlowFilter]

only count flow runs whose flows match these filters

None
flow_run_filter Optional[FlowRunFilter]

only count flow runs that match these filters

None
task_run_filter Optional[TaskRunFilter]

only count flow runs whose task runs match these filters

None
deployment_filter Optional[DeploymentFilter]

only count flow runs whose deployments match these filters

None

Returns:

Name Type Description
int int

count of flow runs

Source code in src/prefect/server/models/flow_runs.py
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
async def count_flow_runs(
    session: AsyncSession,
    flow_filter: Optional[schemas.filters.FlowFilter] = None,
    flow_run_filter: Optional[schemas.filters.FlowRunFilter] = None,
    task_run_filter: Optional[schemas.filters.TaskRunFilter] = None,
    deployment_filter: Optional[schemas.filters.DeploymentFilter] = None,
    work_pool_filter: Optional[schemas.filters.WorkPoolFilter] = None,
    work_queue_filter: Optional[schemas.filters.WorkQueueFilter] = None,
) -> int:
    """
    Count flow runs.

    Args:
        session: a database session
        flow_filter: only count flow runs whose flows match these filters
        flow_run_filter: only count flow runs that match these filters
        task_run_filter: only count flow runs whose task runs match these filters
        deployment_filter: only count flow runs whose deployments match these filters

    Returns:
        int: count of flow runs
    """

    query = select(sa.func.count(sa.text("*"))).select_from(orm_models.FlowRun)

    query = await _apply_flow_run_filters(
        query,
        flow_filter=flow_filter,
        flow_run_filter=flow_run_filter,
        task_run_filter=task_run_filter,
        deployment_filter=deployment_filter,
        work_pool_filter=work_pool_filter,
        work_queue_filter=work_queue_filter,
    )

    result = await session.execute(query)
    return result.scalar_one()

create_flow_run(db, session, flow_run, orchestration_parameters=None) async

Creates a new flow run.

If the provided flow run has a state attached, it will also be created.

Parameters:

Name Type Description Default
session AsyncSession

a database session

required
flow_run FlowRun

a flow run model

required

Returns:

Type Description
FlowRun

orm_models.FlowRun: the newly-created flow run

Source code in src/prefect/server/models/flow_runs.py
 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
@db_injector
async def create_flow_run(
    db: PrefectDBInterface,
    session: AsyncSession,
    flow_run: schemas.core.FlowRun,
    orchestration_parameters: Optional[dict] = None,
) -> orm_models.FlowRun:
    """Creates a new flow run.

    If the provided flow run has a state attached, it will also be created.

    Args:
        session: a database session
        flow_run: a flow run model

    Returns:
        orm_models.FlowRun: the newly-created flow run
    """
    now = pendulum.now("UTC")
    # model: Union[orm_models.FlowRun, None] = None

    flow_run_dict = dict(
        **flow_run.model_dump_for_orm(
            exclude={
                "created",
                "state",
                "estimated_run_time",
                "estimated_start_time_delta",
            },
            exclude_unset=True,
        ),
        created=now,
    )

    # if no idempotency key was provided, create the run directly
    if not flow_run.idempotency_key:
        model = orm_models.FlowRun(**flow_run_dict)
        session.add(model)
        await session.flush()

    # otherwise let the database take care of enforcing idempotency
    else:
        insert_stmt = (
            db.insert(orm_models.FlowRun)
            .values(**flow_run_dict)
            .on_conflict_do_nothing(
                index_elements=db.flow_run_unique_upsert_columns,
            )
        )
        await session.execute(insert_stmt)

        # read the run to see if idempotency was applied or not
        query = (
            sa.select(orm_models.FlowRun)
            .where(
                sa.and_(
                    orm_models.FlowRun.flow_id == flow_run.flow_id,
                    orm_models.FlowRun.idempotency_key == flow_run.idempotency_key,
                )
            )
            .limit(1)
            .execution_options(populate_existing=True)
            .options(
                selectinload(orm_models.FlowRun.work_queue).selectinload(
                    orm_models.WorkQueue.work_pool
                )
            )
        )
        result = await session.execute(query)
        model = result.scalar_one()

    # if the flow run was created in this function call then we need to set the
    # state. If it was created idempotently, the created time won't match.
    if model.created == now and flow_run.state:
        await models.flow_runs.set_flow_run_state(
            session=session,
            flow_run_id=model.id,
            state=flow_run.state,
            force=True,
            orchestration_parameters=orchestration_parameters,
        )
    return model

delete_flow_run(session, flow_run_id) async

Delete a flow run by flow_run_id, handling concurrency limits if applicable.

Parameters:

Name Type Description Default
session AsyncSession

A database session

required
flow_run_id UUID

a flow run id

required

Returns:

Name Type Description
bool bool

whether or not the flow run was deleted

Source code in src/prefect/server/models/flow_runs.py
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
async def delete_flow_run(session: AsyncSession, flow_run_id: UUID) -> bool:
    """
    Delete a flow run by flow_run_id, handling concurrency limits if applicable.

    Args:
        session: A database session
        flow_run_id: a flow run id

    Returns:
        bool: whether or not the flow run was deleted
    """
    flow_run = await read_flow_run(session, flow_run_id)
    if not flow_run:
        return False

    deployment_id = flow_run.deployment_id

    if deployment_id:
        await cleanup_flow_run_concurrency_slots(session=session, flow_run=flow_run)

    # Delete the flow run
    result = await session.execute(
        delete(orm_models.FlowRun).where(orm_models.FlowRun.id == flow_run_id)
    )

    return result.rowcount > 0

read_flow_run(session, flow_run_id, for_update=False) async

Reads a flow run by id.

Parameters:

Name Type Description Default
session AsyncSession

A database session

required
flow_run_id UUID

a flow run id

required

Returns:

Type Description
Optional[FlowRun]

orm_models.FlowRun: the flow run

Source code in src/prefect/server/models/flow_runs.py
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
async def read_flow_run(
    session: AsyncSession,
    flow_run_id: UUID,
    for_update: bool = False,
) -> Optional[orm_models.FlowRun]:
    """
    Reads a flow run by id.

    Args:
        session: A database session
        flow_run_id: a flow run id

    Returns:
        orm_models.FlowRun: the flow run
    """
    select = (
        sa.select(orm_models.FlowRun)
        .where(orm_models.FlowRun.id == flow_run_id)
        .options(
            selectinload(orm_models.FlowRun.work_queue).selectinload(
                orm_models.WorkQueue.work_pool
            )
        )
    )

    if for_update:
        select = select.with_for_update()

    result = await session.execute(select)
    return result.scalar()

read_flow_run_graph(db, session, flow_run_id, since=datetime.datetime.min) async

Given a flow run, return the graph of it's task and subflow runs. If a since datetime is provided, only return items that may have changed since that time.

Source code in src/prefect/server/models/flow_runs.py
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
@db_injector
async def read_flow_run_graph(
    db: PrefectDBInterface,
    session: AsyncSession,
    flow_run_id: UUID,
    since: datetime.datetime = datetime.datetime.min,
) -> Graph:
    """Given a flow run, return the graph of it's task and subflow runs. If a `since`
    datetime is provided, only return items that may have changed since that time."""
    return await db.queries.flow_run_graph_v2(
        session=session,
        flow_run_id=flow_run_id,
        since=since,
        max_nodes=PREFECT_API_MAX_FLOW_RUN_GRAPH_NODES.value(),
        max_artifacts=PREFECT_API_MAX_FLOW_RUN_GRAPH_ARTIFACTS.value(),
    )

read_flow_runs(session, columns=None, flow_filter=None, flow_run_filter=None, task_run_filter=None, deployment_filter=None, work_pool_filter=None, work_queue_filter=None, offset=None, limit=None, sort=schemas.sorting.FlowRunSort.ID_DESC) async

Read flow runs.

Parameters:

Name Type Description Default
session AsyncSession

a database session

required
columns Optional[List]

a list of the flow run ORM columns to load, for performance

None
flow_filter Optional[FlowFilter]

only select flow runs whose flows match these filters

None
flow_run_filter Optional[FlowRunFilter]

only select flow runs match these filters

None
task_run_filter Optional[TaskRunFilter]

only select flow runs whose task runs match these filters

None
deployment_filter Optional[DeploymentFilter]

only select flow runs whose deployments match these filters

None
offset Optional[int]

Query offset

None
limit Optional[int]

Query limit

None
sort FlowRunSort

Query sort

ID_DESC

Returns:

Type Description
Sequence[FlowRun]

List[orm_models.FlowRun]: flow runs

Source code in src/prefect/server/models/flow_runs.py
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
async def read_flow_runs(
    session: AsyncSession,
    columns: Optional[List] = None,
    flow_filter: Optional[schemas.filters.FlowFilter] = None,
    flow_run_filter: Optional[schemas.filters.FlowRunFilter] = None,
    task_run_filter: Optional[schemas.filters.TaskRunFilter] = None,
    deployment_filter: Optional[schemas.filters.DeploymentFilter] = None,
    work_pool_filter: Optional[schemas.filters.WorkPoolFilter] = None,
    work_queue_filter: Optional[schemas.filters.WorkQueueFilter] = None,
    offset: Optional[int] = None,
    limit: Optional[int] = None,
    sort: schemas.sorting.FlowRunSort = schemas.sorting.FlowRunSort.ID_DESC,
) -> Sequence[orm_models.FlowRun]:
    """
    Read flow runs.

    Args:
        session: a database session
        columns: a list of the flow run ORM columns to load, for performance
        flow_filter: only select flow runs whose flows match these filters
        flow_run_filter: only select flow runs match these filters
        task_run_filter: only select flow runs whose task runs match these filters
        deployment_filter: only select flow runs whose deployments match these filters
        offset: Query offset
        limit: Query limit
        sort: Query sort

    Returns:
        List[orm_models.FlowRun]: flow runs
    """
    query = (
        select(orm_models.FlowRun)
        .order_by(sort.as_sql_sort())
        .options(
            selectinload(orm_models.FlowRun.work_queue).selectinload(
                orm_models.WorkQueue.work_pool
            )
        )
    )

    if columns:
        query = query.options(load_only(*columns))

    query = await _apply_flow_run_filters(
        query,
        flow_filter=flow_filter,
        flow_run_filter=flow_run_filter,
        task_run_filter=task_run_filter,
        deployment_filter=deployment_filter,
        work_pool_filter=work_pool_filter,
        work_queue_filter=work_queue_filter,
    )

    if offset is not None:
        query = query.offset(offset)

    if limit is not None:
        query = query.limit(limit)

    result = await session.execute(query)
    return result.scalars().unique().all()

read_task_run_dependencies(session, flow_run_id) async

Get a task run dependency map for a given flow run.

Source code in src/prefect/server/models/flow_runs.py
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
async def read_task_run_dependencies(
    session: AsyncSession,
    flow_run_id: UUID,
) -> List[DependencyResult]:
    """
    Get a task run dependency map for a given flow run.
    """
    flow_run = await models.flow_runs.read_flow_run(
        session=session, flow_run_id=flow_run_id
    )
    if not flow_run:
        raise ObjectNotFoundError(f"Flow run with id {flow_run_id} not found")

    task_runs = await models.task_runs.read_task_runs(
        session=session,
        flow_run_filter=schemas.filters.FlowRunFilter(
            id=schemas.filters.FlowRunFilterId(any_=[flow_run_id])
        ),
    )

    dependency_graph = []

    for task_run in task_runs:
        inputs = list(set(chain(*task_run.task_inputs.values())))
        untrackable_result_status = (
            False
            if task_run.state is None
            else task_run.state.state_details.untrackable_result
        )
        dependency_graph.append(
            DependencyResult(
                id=task_run.id,
                upstream_dependencies=inputs,
                state=task_run.state,
                expected_start_time=task_run.expected_start_time,
                name=task_run.name,
                start_time=task_run.start_time,
                end_time=task_run.end_time,
                total_run_time=task_run.total_run_time,
                estimated_run_time=task_run.estimated_run_time,
                untrackable_result=untrackable_result_status,
            )
        )

    return dependency_graph

set_flow_run_state(session, flow_run_id, state, force=False, flow_policy=None, orchestration_parameters=None) async

Creates a new orchestrated flow run state.

Setting a new state on a run is the one of the principal actions that is governed by Prefect's orchestration logic. Setting a new run state will not guarantee creation, but instead trigger orchestration rules to govern the proposed state input. If the state is considered valid, it will be written to the database. Otherwise, a it's possible a different state, or no state, will be created. A force flag is supplied to bypass a subset of orchestration logic.

Parameters:

Name Type Description Default
session AsyncSession

a database session

required
flow_run_id UUID

the flow run id

required
state State

a flow run state model

required
force bool

if False, orchestration rules will be applied that may alter or prevent the state transition. If True, orchestration rules are not applied.

False

Returns:

Type Description
OrchestrationResult

OrchestrationResult object

Source code in src/prefect/server/models/flow_runs.py
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
async def set_flow_run_state(
    session: AsyncSession,
    flow_run_id: UUID,
    state: schemas.states.State,
    force: bool = False,
    flow_policy: Optional[Type[BaseOrchestrationPolicy]] = None,
    orchestration_parameters: Optional[Dict[str, Any]] = None,
) -> OrchestrationResult:
    """
    Creates a new orchestrated flow run state.

    Setting a new state on a run is the one of the principal actions that is governed by
    Prefect's orchestration logic. Setting a new run state will not guarantee creation,
    but instead trigger orchestration rules to govern the proposed `state` input. If
    the state is considered valid, it will be written to the database. Otherwise, a
    it's possible a different state, or no state, will be created. A `force` flag is
    supplied to bypass a subset of orchestration logic.

    Args:
        session: a database session
        flow_run_id: the flow run id
        state: a flow run state model
        force: if False, orchestration rules will be applied that may alter or prevent
            the state transition. If True, orchestration rules are not applied.

    Returns:
        OrchestrationResult object
    """

    # load the flow run
    run = await models.flow_runs.read_flow_run(
        session=session,
        flow_run_id=flow_run_id,
        # Lock the row to prevent orchestration race conditions
        for_update=True,
    )

    if not run:
        raise ObjectNotFoundError(f"Flow run with id {flow_run_id} not found")

    initial_state = run.state.as_state() if run.state else None
    initial_state_type = initial_state.type if initial_state else None
    proposed_state_type = state.type if state else None
    intended_transition = (initial_state_type, proposed_state_type)

    if force or flow_policy is None:
        flow_policy = MinimalFlowPolicy

    orchestration_rules = flow_policy.compile_transition_rules(*intended_transition)  # type: ignore
    global_rules = GlobalFlowPolicy.compile_transition_rules(*intended_transition)

    context = FlowOrchestrationContext(
        session=session,
        run=run,
        initial_state=initial_state,
        proposed_state=state,
    )

    if orchestration_parameters is not None:
        context.parameters = orchestration_parameters

    # apply orchestration rules and create the new flow run state
    async with contextlib.AsyncExitStack() as stack:
        for rule in orchestration_rules:
            context = await stack.enter_async_context(
                rule(context, *intended_transition)
            )

        for rule in global_rules:
            context = await stack.enter_async_context(
                rule(context, *intended_transition)
            )

        await context.validate_proposed_state()

    if context.orchestration_error is not None:
        raise context.orchestration_error

    result = OrchestrationResult(
        state=context.validated_state,
        status=context.response_status,
        details=context.response_details,
    )

    # if a new state is being set (either ACCEPTED from user or REJECTED
    # and set by the server), check for any notification policies
    if result.status in (SetStateStatus.ACCEPT, SetStateStatus.REJECT):
        await models.flow_run_notification_policies.queue_flow_run_notifications(
            session=session, flow_run=run
        )

    return result

update_flow_run(session, flow_run_id, flow_run) async

Updates a flow run.

Parameters:

Name Type Description Default
session AsyncSession

a database session

required
flow_run_id UUID

the flow run id to update

required
flow_run FlowRunUpdate

a flow run model

required

Returns:

Name Type Description
bool bool

whether or not matching rows were found to update

Source code in src/prefect/server/models/flow_runs.py
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
async def update_flow_run(
    session: AsyncSession,
    flow_run_id: UUID,
    flow_run: schemas.actions.FlowRunUpdate,
) -> bool:
    """
    Updates a flow run.

    Args:
        session: a database session
        flow_run_id: the flow run id to update
        flow_run: a flow run model

    Returns:
        bool: whether or not matching rows were found to update
    """
    update_stmt = (
        sa.update(orm_models.FlowRun)
        .where(orm_models.FlowRun.id == flow_run_id)
        # exclude_unset=True allows us to only update values provided by
        # the user, ignoring any defaults on the model
        .values(**flow_run.model_dump_for_orm(exclude_unset=True))
    )
    result = await session.execute(update_stmt)
    return result.rowcount > 0