feat: filter run history by how runs started and group nested runs

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-10-26 10:29:39 -07:00
co-authored by Claude Opus 5.5
parent a1c39233d5
commit d28619e39b
15 changed files with 1946 additions and 364 deletions
+1 -1
View File
@@ -1 +1 @@
dd0c7087f9b2453260f3d73b0d589042b4393a1d
1a47ebf405774527e3b79c0591897ace3e22a739
@@ -1,7 +1,7 @@
-- Serves get_input_history with include_non_root in windmill-api-inputs: a runnable's runs as a
-- flow step. Every other runnable_path index on v2_job is partial on parent_job IS NULL.
-- runnable_path IS NOT NULL keeps inline flow steps, which no path lookup can match, from
-- paying an index write on every insert.
-- Serves get_input_history in windmill-api-inputs when it lists a runnable's runs inside other
-- runs. Every other runnable_path index on v2_job is partial on parent_job IS NULL. That listing
-- reads only script and flow runs, so the kind predicate spares inline steps, loop and branch
-- containers and agent steps, most of the child jobs, an index write on every insert.
-- Dropped before it is built because the OVERRIDDEN_MIGRATIONS rewrite in
-- windmill-api/src/db.rs runs both CONCURRENTLY: an interrupted concurrent build leaves an
-- invalid index that IF NOT EXISTS would skip rebuilding.
@@ -9,4 +9,4 @@ DROP INDEX IF EXISTS ix_v2_job_child_by_path;
CREATE INDEX IF NOT EXISTS ix_v2_job_child_by_path
ON v2_job (workspace_id, runnable_path, created_at DESC)
WHERE parent_job IS NOT NULL AND runnable_path IS NOT NULL;
WHERE parent_job IS NOT NULL AND kind IN ('script', 'flow');
+756
View File
@@ -0,0 +1,756 @@
/*
* Author: Ruben Fiszel
* Copyright: Windmill Labs, Inc 2022
* This file and its contents are licensed under the AGPLv3 License.
* Please see the included NOTICE for copyright information and
* LICENSE-AGPL for a copy of the license.
*/
//! A runnable's run history listed by how each run started. Its runs inside other runs are
//! grouped by the top-level run that contains them.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::{types::Uuid, FromRow, Postgres, Transaction};
use windmill_common::{
error::{Error, Result},
jobs::JobKind,
};
use crate::{singlestepflow_filter, Input, RunnableType};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RunStartedBy {
Manual,
Api,
Schedule,
App,
Trigger,
Preview,
FlowStep,
AgentTool,
ScriptCall,
Handler,
}
impl RunStartedBy {
const ALL: [RunStartedBy; 10] = [
Self::Manual,
Self::Api,
Self::Schedule,
Self::App,
Self::Trigger,
Self::Preview,
Self::FlowStep,
Self::AgentTool,
Self::ScriptCall,
Self::Handler,
];
fn as_str(self) -> &'static str {
match self {
Self::Manual => "manual",
Self::Api => "api",
Self::Schedule => "schedule",
Self::App => "app",
Self::Trigger => "trigger",
Self::Preview => "preview",
Self::FlowStep => "flow_step",
Self::AgentTool => "agent_tool",
Self::ScriptCall => "script_call",
Self::Handler => "handler",
}
}
fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|c| c.as_str() == s)
}
fn is_inside(self) -> bool {
matches!(
self,
Self::FlowStep | Self::AgentTool | Self::ScriptCall | Self::Handler
)
}
}
pub(crate) fn parse_started_by(list: &str) -> Result<Vec<RunStartedBy>> {
list.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(|s| {
RunStartedBy::parse(s)
.ok_or_else(|| Error::BadRequest(format!("unknown started_by value: {s}")))
})
.collect()
}
/// The history fields of a run, flattened into [`Input`].
#[derive(Debug, Serialize, Deserialize)]
pub struct RunDetails {
#[serde(skip_serializing_if = "Option::is_none")]
started_by: Option<RunStartedBy>,
#[serde(skip_serializing_if = "Option::is_none")]
trigger_kind: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
trigger: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
running: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
suspended: bool,
#[serde(skip_serializing_if = "Option::is_none")]
flow_step_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
retry: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
parent_path: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
top_run: Option<TopRun>,
#[serde(skip_serializing_if = "Option::is_none")]
group: Option<RunGroup>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct TopRun {
id: Uuid,
#[serde(skip_serializing_if = "Option::is_none")]
kind: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
path: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
success: Option<bool>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
running: bool,
#[serde(skip_serializing_if = "Option::is_none")]
trigger_kind: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
trigger: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RunGroup {
runs: i64,
failed: i64,
running: i64,
retries: i64,
handlers: i64,
complete: bool,
}
pub(crate) struct HistoryQuery<'a> {
pub w_id: &'a str,
pub path: &'a str,
pub runnable_type: &'a RunnableType,
pub started_by: &'a [RunStartedBy],
pub args: Option<serde_json::Value>,
}
/// Runs examined per side (top-level, inside) when a category of that side is unticked, and the
/// most the inside window grows to.
const CAP: i64 = 5000;
const MIN_INSIDE_WINDOW: i64 = 200;
const INSIDE_RUNS_LIMIT: i64 = 500;
const HANDLER_CREATED_BY: &str = "('error_handler', 'schedule_error_handler', \
'schedule_recovery_handler', 'success_handler', 'global')";
/// Category of a run with no parent, from its own columns. `prefix` is the table alias with its
/// dot, or empty.
fn top_level_category(prefix: &str) -> String {
format!(
"CASE WHEN {prefix}kind IN ('preview', 'flowpreview') THEN 'preview' \
WHEN {prefix}trigger_kind IS NULL OR {prefix}trigger_kind = 'ui' THEN 'manual' \
WHEN {prefix}trigger_kind = 'webhook' THEN 'api' \
WHEN {prefix}trigger_kind = 'schedule' THEN 'schedule' \
WHEN {prefix}trigger_kind = 'app' THEN 'app' \
ELSE 'trigger' END"
)
}
/// A handler job has the job it handles as both parent and innermost root. The steps of a
/// handler flow and the runs a handler starts through the SDK inherit its `created_by`, but
/// not that shape.
fn is_handler(prefix: &str) -> String {
format!(
"({prefix}flow_step_id IS NULL AND {prefix}created_by IN {HANDLER_CREATED_BY} \
AND {prefix}parent_job = {prefix}flow_innermost_root_job)"
)
}
/// Category of a run with a parent as far as its own columns tell: NULL means it needs its
/// parent row (agent tool, script call, or a retry, which takes its first attempt's category).
fn own_category(prefix: &str) -> String {
format!(
"CASE WHEN {prefix}flow_step_id IS NOT NULL THEN 'flow_step' \
WHEN {handler} THEN 'handler' END",
handler = is_handler(prefix)
)
}
/// Lateral subquery `x` over the run `s` (with `s.own_category`): its full category, retry
/// attempt, parent path, whether its first attempt is top-level, and whether it is hidden.
/// A run whose parent shares its path is a workflow-as-code task or the inner run of a
/// single-step-flow wrapper, both already listed through that parent. A parent that row-level
/// security hides from the viewer reads as NULL, and the run must stay listed.
fn classify_inside() -> String {
format!(
"CROSS JOIN LATERAL (\
SELECT ra.attempt AS retry, p.runnable_path AS parent_path, \
p.id IS NOT NULL AND p.parent_job IS NULL AS parent_is_top, \
CASE WHEN s.own_category IS NOT NULL THEN s.own_category \
WHEN ra.attempt IS NOT NULL AND p.id IS NOT NULL AND p.parent_job IS NULL \
THEN {parent_top_level} \
WHEN ra.attempt IS NOT NULL AND p.id IS NOT NULL THEN \
CASE WHEN {parent_handler} THEN 'handler' \
WHEN (SELECT pp.kind FROM v2_job pp \
WHERE pp.id = p.parent_job AND pp.workspace_id = $2) = 'aiagent' \
THEN 'agent_tool' \
ELSE 'script_call' END \
WHEN p.kind = 'aiagent' THEN 'agent_tool' \
ELSE 'script_call' END AS started_by, \
ra.attempt IS NULL AND p.runnable_path IS NOT DISTINCT FROM $1 \
AND s.own_category IS DISTINCT FROM 'handler' AS hidden \
FROM (SELECT 1) one \
LEFT JOIN v2_job p ON p.id = s.parent_job AND p.workspace_id = $2 \
LEFT JOIN native_retry_attempt ra ON ra.job_id = s.id AND s.own_category IS NULL \
LIMIT 1\
) x",
parent_top_level = top_level_category("p."),
parent_handler = is_handler("p."),
)
}
/// Lateral subquery `st` over the run `{alias}`: completion or, while it runs, queue state.
/// The LIMIT keeps it a per-row lookup, so the scan above it keeps its index order.
fn run_state(alias: &str) -> String {
format!(
"CROSS JOIN LATERAL (\
SELECT c.status, c.completed_at, q.running IS TRUE AS running, \
COALESCE(q.suspend, 0) > 0 AS suspended, q.started_at \
FROM (SELECT 1) one \
LEFT JOIN v2_job_completed c ON c.id = {alias}.id \
LEFT JOIN v2_job_queue q ON q.id = {alias}.id \
LIMIT 1\
) st"
)
}
/// Runs that completed (except skipped ones) or that a worker has started.
const STARTED: &str =
"CASE WHEN st.status IS NOT NULL THEN st.status <> 'skipped' ELSE st.running END";
fn inside_kind(runnable_type: &RunnableType) -> &'static str {
match runnable_type {
RunnableType::FlowPath => "'flow'",
_ => "'script'",
}
}
/// A page entry, or the one row with no entry that carries the bounds of an empty page.
#[derive(FromRow)]
struct EntryRow {
run_id: Option<Uuid>,
top: Option<Uuid>,
latest_created: Option<DateTime<Utc>>,
created_by: Option<String>,
started_by: Option<String>,
is_preview: Option<bool>,
trigger_kind: Option<String>,
trigger: Option<String>,
flow_step_id: Option<String>,
retry: Option<i32>,
parent_path: Option<String>,
status: Option<String>,
running: Option<bool>,
suspended: Option<bool>,
time: Option<DateTime<Utc>>,
runs: Option<i64>,
failed: Option<i64>,
running_runs: Option<i64>,
retries: Option<i64>,
handlers: Option<i64>,
top_created_at: Option<DateTime<Utc>>,
root_retries: Option<i64>,
root_retries_failed: Option<i64>,
root_retries_running: Option<i64>,
top_kind: Option<String>,
top_path: Option<String>,
top_trigger_kind: Option<String>,
top_trigger: Option<String>,
top_status: Option<String>,
top_running: Option<bool>,
window_bound: Option<DateTime<Utc>>,
count_bound: Option<DateTime<Utc>>,
above: i64,
}
/// One page of history entries, newest activity first. An entry is a top-level run of the
/// runnable (with a count of its own retries and of the runs of the runnable inside it), or the
/// runs of the runnable inside one other top-level run.
///
/// Runs come from two windows over `created_at`: the latest top-level runs, and the latest runs
/// inside other runs. A run inside another starts after it, so a group's count is exact when its
/// top-level run started after the oldest run the inside window examined.
pub(crate) async fn list(
tx: &mut Transaction<'static, Postgres>,
q: &HistoryQuery<'_>,
per_page: usize,
offset: usize,
) -> Result<Vec<Input>> {
let needed = (offset + per_page) as i64;
let mut inside_window = (10 * needed).clamp(MIN_INSIDE_WINDOW, CAP);
let mut rows = list_page(tx, q, per_page, offset, inside_window).await?;
// The page may hold entries older than the full inside window, where an older inner run
// could still belong before them: grow the window once, in proportion to the shortfall.
if let Some(first) = rows.first() {
if first.window_bound.is_some() && first.above < needed && inside_window < CAP {
inside_window = (inside_window * needed * 3 / (2 * first.above.max(1)))
.max(2 * inside_window)
.min(CAP);
rows = list_page(tx, q, per_page, offset, inside_window).await?;
}
}
Ok(rows
.into_iter()
.filter(|row| row.run_id.is_some() || row.top.is_some())
.map(entry_to_input)
.collect())
}
async fn list_page(
tx: &mut Transaction<'static, Postgres>,
q: &HistoryQuery<'_>,
per_page: usize,
offset: usize,
inside_window: i64,
) -> Result<Vec<EntryRow>> {
let needed = (offset + per_page) as i64;
let root_categories: Vec<&str> = q
.started_by
.iter()
.filter(|c| !c.is_inside())
.map(|c| c.as_str())
.collect();
let inside_categories: Vec<&str> = q
.started_by
.iter()
.filter(|c| c.is_inside())
.map(|c| c.as_str())
.collect();
let include_preview = q.started_by.contains(&RunStartedBy::Preview);
let root_kinds = match q.runnable_type {
RunnableType::FlowPath if include_preview => {
vec![JobKind::Flow, JobKind::SingleStepFlow, JobKind::FlowPreview]
}
RunnableType::FlowPath => vec![JobKind::Flow, JobKind::SingleStepFlow],
_ if include_preview => vec![JobKind::Script, JobKind::SingleStepFlow, JobKind::Preview],
_ => vec![JobKind::Script, JobKind::SingleStepFlow],
};
// Previews are left out through the kinds; any other unticked top-level category filters
// rows, so the scan is capped like the inside one.
let root_filtered = [
RunStartedBy::Manual,
RunStartedBy::Api,
RunStartedBy::Schedule,
RunStartedBy::App,
RunStartedBy::Trigger,
]
.iter()
.any(|c| !q.started_by.contains(c));
let (root_cap, root_filter) = if root_filtered {
("LIMIT $8", "AND j.started_by = ANY($4)")
} else {
("", "")
};
// Only a failed script run can have native retries (windmill-queue
// maybe_enqueue_native_script_retry), so every other run skips the walk over its children.
let retry_gate = match q.runnable_type {
RunnableType::FlowPath => "AND false",
_ => "AND r.status = 'failure'",
};
// `kind = 'script'` (or 'flow') stays a literal: the planner can only use the partial index
// ix_v2_job_child_by_path when it proves the index predicate from the query text.
// root_runs adds the runs in progress that the window passed over, however old: a flow
// suspended at an approval step or a hung run must stay in sight.
let sql = format!(
"WITH root_window AS (\
SELECT j.id, j.created_at, j.created_by, j.kind, j.trigger_kind::text AS trigger_kind, \
j.trigger, j.started_by, st.status, st.completed_at, st.running, st.suspended, \
st.started_at \
FROM (\
SELECT id, created_at, created_by, kind, trigger_kind, trigger, \
{root_category} AS started_by \
FROM v2_job \
WHERE workspace_id = $2 AND runnable_path = $1 AND parent_job IS NULL \
AND kind = ANY($3) AND script_entrypoint_override IS NULL \
AND cardinality($4) > 0 {singlestepflow_filter} \
AND ($11::jsonb IS NULL OR args @> $11::jsonb) \
ORDER BY created_at DESC {root_cap}\
) j \
{root_state} \
WHERE {STARTED} {root_filter} \
ORDER BY j.created_at DESC \
LIMIT $6\
), \
root_runs AS (\
SELECT id, created_at, created_by, kind, trigger_kind, trigger, started_by, status, \
completed_at, running, suspended, started_at \
FROM root_window \
UNION ALL \
(SELECT j.id, j.created_at, j.created_by, j.kind, j.trigger_kind::text AS trigger_kind, \
j.trigger, j.started_by, st.status, st.completed_at, st.running, st.suspended, \
st.started_at \
FROM (\
SELECT q.id FROM v2_job_queue q \
WHERE q.workspace_id = $2 AND q.running AND cardinality($4) > 0\
) running \
CROSS JOIN LATERAL (\
SELECT id, created_at, created_by, kind, trigger_kind, trigger, \
{root_category} AS started_by \
FROM v2_job \
WHERE id = running.id AND workspace_id = $2 AND runnable_path = $1 \
AND parent_job IS NULL AND kind = ANY($3) \
AND script_entrypoint_override IS NULL {singlestepflow_filter} \
AND ($11::jsonb IS NULL OR args @> $11::jsonb) \
LIMIT 1\
) j \
{root_state} \
WHERE st.running {root_filter} \
AND NOT EXISTS (SELECT 1 FROM root_window w WHERE w.id = j.id) \
ORDER BY j.created_at DESC LIMIT 100)\
), \
inside_runs AS (\
SELECT s.id, s.created_at, s.created_by, s.trigger_kind, s.trigger, s.parent_job, \
s.root_job, s.flow_innermost_root_job, s.flow_step_id, st.status, \
st.completed_at, st.running, st.suspended, st.started_at, x.retry, \
x.parent_path, x.started_by \
FROM (\
SELECT id, created_at, created_by, trigger_kind, trigger, parent_job, root_job, \
flow_innermost_root_job, flow_step_id, script_entrypoint_override, args, \
{own_category} AS own_category \
FROM v2_job \
WHERE workspace_id = $2 AND runnable_path = $1 AND parent_job IS NOT NULL \
AND kind = {inside_kind} AND cardinality($5) > 0 \
ORDER BY created_at DESC LIMIT $8\
) s \
{classify} \
{inside_state} \
WHERE s.script_entrypoint_override IS NULL \
AND ($11::jsonb IS NULL OR s.args @> $11::jsonb) \
AND (s.own_category = ANY($5) \
OR (s.own_category IS NULL AND $5 && '{{agent_tool,script_call,handler}}')) \
AND NOT x.hidden AND NOT (x.retry IS NOT NULL AND x.parent_is_top) \
AND x.started_by = ANY($5) AND {STARTED} \
ORDER BY s.created_at DESC \
LIMIT $7\
), \
firsts AS (\
SELECT DISTINCT COALESCE(root_job, flow_innermost_root_job, parent_job) AS first \
FROM inside_runs\
), \
tops AS (\
SELECT f.first, COALESCE(a4.id, a3.id, a2.id, a1.id, f.first) AS top, \
COALESCE(a4.created_at, a3.created_at, a2.created_at, a1.created_at) AS top_created_at \
FROM firsts f \
LEFT JOIN LATERAL (SELECT id, created_at, COALESCE(root_job, flow_innermost_root_job, parent_job) AS nxt \
FROM v2_job WHERE id = f.first AND workspace_id = $2) a1 ON true \
LEFT JOIN LATERAL (SELECT id, created_at, COALESCE(root_job, flow_innermost_root_job, parent_job) AS nxt \
FROM v2_job WHERE id = a1.nxt AND workspace_id = $2) a2 ON true \
LEFT JOIN LATERAL (SELECT id, created_at, COALESCE(root_job, flow_innermost_root_job, parent_job) AS nxt \
FROM v2_job WHERE id = a2.nxt AND workspace_id = $2) a3 ON true \
LEFT JOIN LATERAL (SELECT id, created_at FROM v2_job WHERE id = a3.nxt AND workspace_id = $2) a4 ON true\
), \
inside_keyed AS (\
SELECT r.*, t.top, t.top_created_at \
FROM inside_runs r \
JOIN tops t ON t.first = COALESCE(r.root_job, r.flow_innermost_root_job, r.parent_job)\
), \
groups AS (\
SELECT top, min(top_created_at) AS top_created_at, count(*) AS runs, \
count(*) FILTER (WHERE status IN ('failure', 'canceled')) AS failed, \
count(*) FILTER (WHERE running) AS running, \
count(*) FILTER (WHERE retry IS NOT NULL) AS retries, \
count(*) FILTER (WHERE started_by = 'handler') AS handlers, \
max(COALESCE(completed_at, 'infinity')) AS latest, \
max(created_at) AS latest_created, \
(array_agg(id ORDER BY created_at DESC))[1] AS last_id \
FROM inside_keyed GROUP BY top\
), \
bounds AS (\
SELECT window_bound, \
CASE WHEN window_bound IS NOT NULL THEN window_bound \
ELSE (SELECT created_at FROM v2_job \
WHERE workspace_id = $2 AND runnable_path = $1 AND parent_job IS NOT NULL \
AND kind IN ('script', 'flow') AND cardinality($5) > 0 \
ORDER BY created_at DESC OFFSET $8 - 1 LIMIT 1) END AS count_bound \
FROM (SELECT CASE WHEN count(*) >= $7 THEN min(created_at) END AS window_bound \
FROM inside_runs) w\
), \
entries AS (\
SELECT r.id AS run_id, NULL::uuid AS top, \
GREATEST(COALESCE(r.completed_at, 'infinity'), g.latest) AS latest, \
GREATEST(r.created_at, g.latest_created) AS latest_created \
FROM root_runs r LEFT JOIN groups g ON g.top = r.id \
UNION ALL \
SELECT g.last_id, g.top, g.latest, g.latest_created \
FROM groups g WHERE NOT EXISTS (SELECT 1 FROM root_runs r WHERE r.id = g.top)\
), \
page AS (\
SELECT run_id, top, latest, latest_created FROM entries \
ORDER BY latest DESC, latest_created DESC, COALESCE(top, run_id) \
LIMIT $10 OFFSET $9\
) \
SELECT e.run_id, e.top, e.latest_created, \
(SELECT count(*) FROM entries a \
WHERE b.window_bound IS NULL OR a.latest_created >= b.window_bound) AS above, \
COALESCE(r.created_by, i.created_by) AS created_by, \
COALESCE(r.started_by, i.started_by) AS started_by, \
r.kind IN ('preview', 'flowpreview') AS is_preview, \
COALESCE(r.trigger_kind, i.trigger_kind::text) AS trigger_kind, \
COALESCE(r.trigger, i.trigger) AS trigger, i.flow_step_id, i.retry, \
CASE WHEN i.started_by = 'script_call' THEN i.parent_path END AS parent_path, \
COALESCE(r.status, i.status)::text AS status, \
COALESCE(r.running, i.running) AS running, \
COALESCE(r.suspended, i.suspended) AS suspended, \
COALESCE(r.completed_at, i.completed_at, r.started_at, i.started_at, \
r.created_at, i.created_at) AS time, \
g.runs, g.failed, g.running AS running_runs, g.retries, g.handlers, \
COALESCE(g.top_created_at, r.created_at) AS top_created_at, \
rt.n AS root_retries, rt.failed AS root_retries_failed, \
rt.running AS root_retries_running, \
t.kind::text AS top_kind, t.runnable_path AS top_path, \
t.trigger_kind::text AS top_trigger_kind, t.trigger AS top_trigger, \
tc.status::text AS top_status, tq.running IS TRUE AS top_running, \
b.window_bound, b.count_bound \
FROM bounds b \
LEFT JOIN page e ON true \
LEFT JOIN root_runs r ON e.top IS NULL AND r.id = e.run_id \
LEFT JOIN inside_keyed i ON e.top IS NOT NULL AND i.id = e.run_id \
LEFT JOIN groups g ON g.top = COALESCE(e.top, e.run_id) \
LEFT JOIN v2_job t ON t.id = e.top AND t.workspace_id = $2 \
LEFT JOIN v2_job_completed tc ON tc.id = t.id \
LEFT JOIN v2_job_queue tq ON tq.id = t.id \
LEFT JOIN LATERAL (\
SELECT count(*) AS n, \
count(*) FILTER (WHERE xc.status IN ('failure', 'canceled')) AS failed, \
count(*) FILTER (WHERE xq.running) AS running \
FROM v2_job x \
JOIN native_retry_attempt n ON n.job_id = x.id \
LEFT JOIN v2_job_completed xc ON xc.id = x.id \
LEFT JOIN v2_job_queue xq ON xq.id = x.id \
WHERE x.parent_job = e.run_id AND x.workspace_id = $2 {retry_gate} \
AND CASE WHEN xc.status IS NOT NULL THEN xc.status <> 'skipped' \
ELSE xq.running IS TRUE END\
) rt ON e.top IS NULL \
ORDER BY e.latest DESC, e.latest_created DESC, COALESCE(e.top, e.run_id)",
root_category = top_level_category(""),
singlestepflow_filter = singlestepflow_filter(q.runnable_type),
root_state = run_state("j"),
own_category = own_category(""),
inside_kind = inside_kind(q.runnable_type),
classify = classify_inside(),
inside_state = run_state("s"),
);
let rows = sqlx::query_as::<_, EntryRow>(&sql)
.bind(q.path)
.bind(q.w_id)
.bind(root_kinds)
.bind(root_categories.as_slice())
.bind(inside_categories.as_slice())
.bind(needed)
.bind(inside_window)
.bind(CAP)
.bind(offset as i64)
.bind(per_page as i64)
.bind(q.args.as_ref())
.fetch_all(&mut **tx)
.await?;
Ok(rows)
}
fn entry_to_input(row: EntryRow) -> Input {
let complete = match row.count_bound {
None => true,
Some(bound) => row.top_created_at.is_some_and(|t| t > bound),
};
let time = row.time.or(row.latest_created).unwrap_or_default();
let created_by = row.created_by.unwrap_or_default();
let success = row.status.as_deref() == Some("success");
let run = |run_id: Uuid, top_run: Option<TopRun>, group: Option<RunGroup>| {
Input::history_entry(
run_id,
time,
created_by.clone(),
success,
row.is_preview.unwrap_or(false),
RunDetails {
started_by: row.started_by.as_deref().and_then(RunStartedBy::parse),
trigger_kind: row.trigger_kind.clone(),
trigger: row.trigger.clone(),
running: row.running.unwrap_or(false),
suspended: row.suspended.unwrap_or(false),
flow_step_id: row.flow_step_id.clone(),
retry: row.retry,
parent_path: row.parent_path.clone(),
top_run,
group,
},
)
};
let Some(top) = row.top else {
let retries = row.root_retries.unwrap_or(0);
let inner = row.runs.unwrap_or(0) + retries;
let group = (inner > 0).then(|| RunGroup {
runs: inner,
failed: row.failed.unwrap_or(0) + row.root_retries_failed.unwrap_or(0),
running: row.running_runs.unwrap_or(0) + row.root_retries_running.unwrap_or(0),
retries: row.retries.unwrap_or(0) + retries,
handlers: row.handlers.unwrap_or(0),
complete,
});
return run(row.run_id.unwrap_or_default(), None, group);
};
let top_run = TopRun {
id: top,
kind: row.top_kind.clone(),
path: row.top_path.clone(),
success: row.top_status.as_deref().map(|s| s == "success"),
running: row.top_running.unwrap_or(false),
trigger_kind: row.top_trigger_kind.clone(),
trigger: row.top_trigger.clone(),
};
let runs = row.runs.unwrap_or(0);
match row.run_id {
Some(run_id) if runs == 1 && complete => run(run_id, Some(top_run), None),
_ => {
let group = RunGroup {
runs,
failed: row.failed.unwrap_or(0),
running: row.running_runs.unwrap_or(0),
retries: row.retries.unwrap_or(0),
handlers: row.handlers.unwrap_or(0),
complete,
};
Input::history_entry(
top,
time,
created_by,
group.failed == 0,
false,
RunDetails {
started_by: None,
trigger_kind: None,
trigger: None,
running: group.running > 0,
suspended: false,
flow_step_id: None,
retry: None,
parent_path: None,
top_run: Some(top_run),
group: Some(group),
},
)
}
}
}
#[derive(FromRow)]
struct InsideRow {
id: Uuid,
created_by: String,
trigger_kind: Option<String>,
trigger: Option<String>,
flow_step_id: Option<String>,
retry: Option<i32>,
parent_path: Option<String>,
started_by: String,
status: Option<String>,
running: bool,
suspended: bool,
time: DateTime<Utc>,
args: sqlx::types::Json<Box<serde_json::value::RawValue>>,
}
/// The runs of the runnable inside the top-level run `top_run`, in execution order, with their
/// args (or `"WINDMILL_TOO_BIG"`), since an opened group shows them all at once.
pub(crate) async fn list_inside(
tx: &mut Transaction<'static, Postgres>,
q: &HistoryQuery<'_>,
top_run: Uuid,
) -> Result<Vec<Input>> {
let categories: Vec<&str> = q.started_by.iter().map(|c| c.as_str()).collect();
let sql = format!(
"WITH RECURSIVE inside(id, depth) AS (\
SELECT id, 1 FROM v2_job WHERE parent_job = $4 AND workspace_id = $2 \
UNION ALL \
SELECT j.id, i.depth + 1 FROM v2_job j JOIN inside i ON j.parent_job = i.id \
WHERE i.depth < 10 AND j.workspace_id = $2\
) \
SELECT s.id, s.created_by, s.trigger_kind::text AS trigger_kind, s.trigger, \
s.flow_step_id, x.retry, \
CASE WHEN x.started_by = 'script_call' THEN x.parent_path END AS parent_path, \
x.started_by, st.status::text AS status, st.running, st.suspended, \
COALESCE(st.completed_at, st.started_at, s.created_at) AS time, \
CASE WHEN pg_column_size(s.args) < 40000 THEN COALESCE(s.args, '{{}}'::jsonb) \
ELSE '\"WINDMILL_TOO_BIG\"'::jsonb END AS args \
FROM inside i \
JOIN (\
SELECT id, created_at, created_by, kind, runnable_path, trigger_kind, trigger, \
parent_job, flow_innermost_root_job, flow_step_id, script_entrypoint_override, \
args, {own_category} AS own_category \
FROM v2_job\
) s ON s.id = i.id \
{classify} \
{state} \
WHERE s.runnable_path = $1 AND s.kind = {inside_kind} \
AND s.script_entrypoint_override IS NULL \
AND ($6::jsonb IS NULL OR s.args @> $6::jsonb) \
AND NOT x.hidden AND x.started_by = ANY($3) AND {STARTED} \
ORDER BY s.created_at \
LIMIT $5",
own_category = own_category(""),
classify = classify_inside(),
state = run_state("s"),
inside_kind = inside_kind(q.runnable_type),
);
let rows = sqlx::query_as::<_, InsideRow>(&sql)
.bind(q.path)
.bind(q.w_id)
.bind(categories.as_slice())
.bind(top_run)
.bind(INSIDE_RUNS_LIMIT)
.bind(q.args.as_ref())
.fetch_all(&mut **tx)
.await?;
Ok(rows
.into_iter()
.map(|row| {
let mut input = Input::history_entry(
row.id,
row.time,
row.created_by,
row.status.as_deref() == Some("success"),
false,
RunDetails {
started_by: RunStartedBy::parse(&row.started_by),
trigger_kind: row.trigger_kind,
trigger: row.trigger,
running: row.running,
suspended: row.suspended,
flow_step_id: row.flow_step_id,
retry: row.retry,
parent_path: row.parent_path,
top_run: None,
group: None,
},
);
input.args = row.args;
input
})
.collect())
}
+106 -51
View File
@@ -28,6 +28,9 @@ use windmill_common::{
utils::{not_found_if_none, paginate, Pagination},
worker::CLOUD_HOSTED,
};
mod history;
pub fn workspaced_service() -> Router {
Router::new()
.route("/history", get(get_input_history))
@@ -99,8 +102,34 @@ pub struct Input {
success: bool,
#[serde(skip_serializing_if = "std::ops::Not::not")]
is_preview: bool,
#[serde(skip_serializing_if = "Option::is_none")]
parent_job: Option<Uuid>,
#[serde(flatten)]
#[sqlx(skip)]
run: Option<history::RunDetails>,
}
impl Input {
fn history_entry(
id: Uuid,
time: DateTime<Utc>,
created_by: String,
success: bool,
is_preview: bool,
run: history::RunDetails,
) -> Self {
Self {
id,
name: format!("{} {}", time.format("%H:%M %-d/%-m"), created_by),
created_at: time,
args: sqlx::types::Json(
serde_json::value::RawValue::from_string("null".to_string()).unwrap(),
),
created_by,
is_public: true,
success,
is_preview,
run: Some(run),
}
}
}
#[derive(Debug, Serialize, Deserialize, FromRow)]
@@ -111,7 +140,6 @@ pub struct CompletedJobMini {
created_by: String,
success: bool,
is_preview: bool,
parent_job: Option<Uuid>,
}
#[derive(Deserialize)]
@@ -119,6 +147,32 @@ struct GetInputHistory {
include_preview: Option<bool>,
args: Option<String>,
include_non_root: Option<bool>,
started_by: Option<String>,
top_run: Option<Uuid>,
}
/// A scheduled runnable with a dynamic-skip handler is wrapped in a synthetic
/// `singlestepflow`, so its runs land under that kind rather than `flow`/`script` (see
/// windmill-queue schedule.rs). Such a wrapper holds either a script or a flow, and the two may
/// share a runnable_path, so match only the wrapped kind that belongs to the queried runnable.
/// The wrapped type lives in raw_flow.modules[id in ('a','main')].value.type (mirrors the
/// projection in windmill-api jobs.rs). runnable_id is NULL on these rows, so ScriptHash never
/// matches.
fn singlestepflow_filter(runnable_type: &RunnableType) -> &'static str {
match runnable_type {
RunnableType::FlowPath => {
"AND (kind <> 'singlestepflow' OR EXISTS (\
SELECT 1 FROM jsonb_array_elements(v2_job.raw_flow->'modules') m \
WHERE m->>'id' IN ('a', 'main') AND m->'value'->>'type' = 'flow'))"
}
RunnableType::ScriptPath => {
"AND (kind <> 'singlestepflow' OR EXISTS (\
SELECT 1 FROM jsonb_array_elements(v2_job.raw_flow->'modules') m \
WHERE m->>'id' IN ('a', 'main') \
AND COALESCE(m->'value'->>'type', 'script') <> 'flow'))"
}
RunnableType::ScriptHash => "",
}
}
async fn get_input_history(
@@ -136,6 +190,40 @@ async fn get_input_history(
per_page
};
// An archived script version's history is read by hash, which no index on runs inside
// other runs covers: it keeps the plain list below.
let started_by = g
.started_by
.as_deref()
.filter(|_| !matches!(r.runnable_type, RunnableType::ScriptHash));
if let Some(started_by) = started_by {
let started_by = history::parse_started_by(started_by)?;
let args = match &g.args {
Some(args) => match serde_json::from_str::<serde_json::Value>(args) {
Ok(v) => Some(v),
Err(_) => return Ok(Json(vec![])),
},
None => None,
};
let q = history::HistoryQuery {
w_id: &w_id,
path: &r.runnable_id,
runnable_type: &r.runnable_type,
started_by: &started_by,
args,
};
let mut tx = user_db.begin(&authed).await?;
// Row estimates for the windows and the walk down a run's children sit far above the
// rows actually read, and JIT-compiling the plan costs more than running it.
sqlx::query("SET LOCAL jit = off").execute(&mut *tx).await?;
let inputs = match g.top_run {
Some(top_run) => history::list_inside(&mut tx, &q, top_run).await?,
None => history::list(&mut tx, &q, per_page, offset).await?,
};
tx.commit().await?;
return Ok(Json(inputs));
}
let mut tx = user_db.begin(&authed).await?;
let args_query = if let Some(args) = &g.args {
@@ -148,65 +236,32 @@ async fn get_input_history(
"".to_string()
};
// A scheduled runnable with a dynamic-skip handler (or a scheduled script with
// native retry) is wrapped in a synthetic `singlestepflow`, so its runs land under
// that kind rather than `flow`/`script` (see windmill-queue schedule.rs). Such a
// wrapper holds either a script or a flow, and the two may share a runnable_path, so
// match only the wrapped kind that belongs to the queried runnable. The wrapped type
// lives in raw_flow.modules[id in ('a','main')].value.type (mirrors the projection in
// windmill-api jobs.rs). runnable_id is NULL on these rows, so ScriptHash never matches.
let singlestepflow_filter = match r.runnable_type {
RunnableType::FlowPath => {
"AND (kind <> 'singlestepflow' OR EXISTS (\
SELECT 1 FROM jsonb_array_elements(v2_job.raw_flow->'modules') m \
WHERE m->>'id' IN ('a', 'main') AND m->'value'->>'type' = 'flow'))"
}
RunnableType::ScriptPath => {
"AND (kind <> 'singlestepflow' OR EXISTS (\
SELECT 1 FROM jsonb_array_elements(v2_job.raw_flow->'modules') m \
WHERE m->>'id' IN ('a', 'main') \
AND COALESCE(m->'value'->>'type', 'script') <> 'flow'))"
}
RunnableType::ScriptHash => "",
let include_non_root = if g.include_non_root.unwrap_or(false) {
""
} else {
"AND parent_job IS NULL"
};
let singlestepflow_filter = singlestepflow_filter(&r.runnable_type);
// Two-step approach: first fetch 2*(per_page+offset) rows using created_at ordering
// (which leverages the ix_job_root_job_index_by_path_2 index on v2_job), then sort
// the small result set by completed_at. This works because created_at and completed_at
// are highly correlated.
let inner_limit = 2 * (per_page + offset);
let recent = |parent_filter: &str| {
format!(
"(SELECT id, v2_job_completed.completed_at, created_by, 'null'::jsonb as args, \
let sql = &format!(
"SELECT id, completed_at, created_by, args, success, is_preview FROM (\
SELECT id, v2_job_completed.completed_at, created_by, 'null'::jsonb as args, \
status = 'success' as success, \
kind IN ('preview', 'flowpreview') as is_preview, parent_job \
kind IN ('preview', 'flowpreview') as is_preview \
FROM v2_job JOIN v2_job_completed USING (id) \
WHERE v2_job.workspace_id = $3 AND {} = $1 AND kind = any($2) \
AND v2_job.script_entrypoint_override IS NULL {singlestepflow_filter} \
{args_query} AND v2_job_completed.status != 'skipped' {parent_filter} \
ORDER BY v2_job.created_at DESC LIMIT $4)",
r.runnable_type.column_name(),
)
};
// Root and child runs are read separately: the runnable_path indexes on v2_job are each
// partial on one side of parent_job, so a single scan over both cannot walk created_at
// in index order and would sort every run of the path.
let inner = if g.include_non_root.unwrap_or(false) {
format!(
"{} UNION ALL {}",
recent("AND parent_job IS NULL"),
recent("AND parent_job IS NOT NULL")
)
} else {
recent("AND parent_job IS NULL")
};
let sql = &format!(
"SELECT id, completed_at, created_by, args, success, is_preview, parent_job FROM (\
{inner}\
{args_query} AND v2_job_completed.status != 'skipped' {include_non_root} \
ORDER BY v2_job.created_at DESC LIMIT $4\
) t ORDER BY completed_at DESC LIMIT $5 OFFSET $6",
r.runnable_type.column_name(),
);
let query = sqlx::query_as::<_, CompletedJobMini>(sql);
@@ -273,7 +328,7 @@ async fn get_input_history(
is_public: true,
success: row.success,
is_preview: row.is_preview,
parent_job: row.parent_job,
run: None,
});
}
@@ -374,7 +429,7 @@ async fn list_saved_inputs(
is_public: row.is_public,
success: true,
is_preview: false,
parent_job: None,
run: None,
})
}
@@ -75,8 +75,8 @@ async fn test_inputs_endpoints(db: Pool<Postgres>) -> anyhow::Result<()> {
Ok(())
}
// A scheduled runnable with a dynamic-skip handler (or a scheduled script with native
// retry) runs as a `singlestepflow`, not `flow`/`script` (see windmill-queue schedule.rs).
// A scheduled runnable with a dynamic-skip handler runs as a `singlestepflow`, not
// `flow`/`script` (see windmill-queue schedule.rs).
// Both a flow's and a script's history must surface their own singlestepflow runs, but a
// script and flow may share a path, so each side must match only the wrapped kind that
// belongs to it — the other must not leak in.
@@ -166,75 +166,310 @@ async fn insert_singlestepflow(
Ok(id)
}
// Each way a run of f/test/step can start, as the history lists it with `started_by`: top-level
// runs by origin, and runs inside other runs grouped under the top-level run containing them.
#[sqlx::test(migrations = "../migrations", fixtures("base"))]
async fn test_input_history_include_non_root(db: Pool<Postgres>) -> anyhow::Result<()> {
async fn test_input_history_started_by(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
const STEP: &str = "f/test/step";
let parent = uuid::Uuid::new_v4();
let root_run = insert_script_run(&db, None).await?;
let step_run = insert_script_run(&db, Some(parent)).await?;
let manual = insert_run(&db, Run { path: STEP, at: 1, ..Run::default() }).await?;
let scheduled = insert_run(
&db,
Run { path: STEP, trigger_kind: Some("schedule"), failed: true, at: 2, ..Run::default() },
)
.await?;
let retry = insert_run(
&db,
Run {
path: STEP,
parent_job: Some(scheduled),
trigger_kind: Some("schedule"),
at: 3,
..Run::default()
},
)
.await?;
sqlx::query("INSERT INTO native_retry_attempt (job_id, attempt) VALUES ($1, 1)")
.bind(retry)
.execute(&db)
.await?;
// A workflow-as-code task carries its script's path under a run of that script: hidden.
let wac_task = insert_run(
&db,
Run { path: STEP, parent_job: Some(manual), at: 4, ..Run::default() },
)
.await?;
let flow = insert_run(
&db,
Run { kind: "flow", path: "f/test/flow", at: 5, ..Run::default() },
)
.await?;
let step = insert_run(
&db,
Run {
path: STEP,
parent_job: Some(flow),
root_job: Some(flow),
innermost_root: Some(flow),
flow_step_id: Some("a"),
at: 6,
..Run::default()
},
)
.await?;
let agent = insert_run(
&db,
Run {
kind: "aiagent",
path: "f/test/flow/b",
parent_job: Some(flow),
root_job: Some(flow),
innermost_root: Some(flow),
flow_step_id: Some("b"),
at: 7,
..Run::default()
},
)
.await?;
let tool = insert_run(
&db,
Run {
path: STEP,
parent_job: Some(agent),
root_job: Some(agent),
innermost_root: Some(flow),
at: 8,
..Run::default()
},
)
.await?;
let caller = insert_run(&db, Run { path: "f/test/caller", at: 9, ..Run::default() }).await?;
let call = insert_run(
&db,
Run {
path: STEP,
parent_job: Some(caller),
innermost_root: Some(caller),
trigger_kind: Some("webhook"),
at: 10,
..Run::default()
},
)
.await?;
let failing = insert_run(
&db,
Run { path: "f/test/failing", failed: true, at: 11, ..Run::default() },
)
.await?;
let handler = insert_run(
&db,
Run {
path: STEP,
parent_job: Some(failing),
innermost_root: Some(failing),
created_by: "error_handler",
at: 12,
..Run::default()
},
)
.await?;
// A run still in progress, older than the one page entry a newer run would fill.
let long_running = insert_run(
&db,
Run { path: "f/test/long", running: true, at: 13, ..Run::default() },
)
.await?;
insert_run(&db, Run { path: "f/test/long", at: 14, ..Run::default() }).await?;
// test-user-2 can read the runs of its own script, not the flow run they are steps of.
let private_flow = insert_run(
&db,
Run { kind: "flow", path: "u/test-user/private_flow", at: 15, ..Run::default() },
)
.await?;
let own_step = insert_run(
&db,
Run {
path: "u/test-user-2/helper",
permissioned_as: "u/test-user-2",
parent_job: Some(private_flow),
root_job: Some(private_flow),
innermost_root: Some(private_flow),
flow_step_id: Some("a"),
at: 16,
..Run::default()
},
)
.await?;
let server = ApiServer::start(db.clone()).await?;
let port = server.addr.port();
let base = format!(
"http://localhost:{port}/api/w/test-workspace/inputs/history\
?runnable_id=f/test/step&runnable_type=ScriptPath"
);
let history = |query: &'static str| {
let url = format!("{base}{query}");
let fetch = |token: &'static str, query: String| {
let url = format!(
"http://localhost:{port}/api/w/test-workspace/inputs/history\
?runnable_type=ScriptPath{query}"
);
async move {
let resp = authed(client().get(url)).send().await?;
let resp = client()
.get(url)
.header("Authorization", format!("Bearer {token}"))
.send()
.await?;
let status = resp.status().as_u16();
let body = resp.text().await?;
assert_2xx(status, &body, "GET /inputs/history");
anyhow::Ok(serde_json::from_str::<Vec<serde_json::Value>>(&body)?)
}
};
let ids = |inputs: &[serde_json::Value]| {
inputs
let history = |query: String| fetch("SECRET_TOKEN", format!("&runnable_id={STEP}{query}"));
let ids = |entries: &[serde_json::Value]| {
entries
.iter()
.filter_map(|i| i["id"].as_str().map(String::from))
.collect::<std::collections::HashSet<_>>()
.map(|e| e["id"].as_str().unwrap_or_default().to_string())
.collect::<Vec<_>>()
};
let top_level = "manual,api,schedule,app,trigger,preview";
let everything = format!("{top_level},flow_step,agent_tool,script_call,handler");
let default = history("").await?;
assert_eq!(ids(&default), [root_run.to_string()].into());
let default = history(format!("&started_by={top_level}")).await?;
assert_eq!(ids(&default), [scheduled.to_string(), manual.to_string()]);
assert_eq!(default[0]["group"]["retries"], 1);
assert!(
default[1].get("group").is_none(),
"the hidden task counts: {default:?}"
);
let all = history("&include_non_root=true").await?;
let all = history(format!("&started_by={everything}")).await?;
assert_eq!(
ids(&all),
[root_run.to_string(), step_run.to_string()].into()
[handler, call, flow, scheduled, manual].map(|id| id.to_string())
);
for input in &all {
let expected = (input["id"] == step_run.to_string()).then(|| parent.to_string());
assert_eq!(input["parent_job"].as_str().map(String::from), expected);
}
assert!(!ids(&all).contains(&wac_task.to_string()));
assert_eq!(all[0]["started_by"], "handler");
assert_eq!(all[0]["top_run"]["id"], failing.to_string());
assert_eq!(all[1]["started_by"], "script_call");
assert_eq!(all[1]["parent_path"], "f/test/caller");
assert_eq!(all[2]["group"]["runs"], 2);
assert_eq!(all[2]["top_run"]["path"], "f/test/flow");
let tools = history("&started_by=agent_tool".to_string()).await?;
assert_eq!(ids(&tools), [tool.to_string()]);
assert_eq!(tools[0]["top_run"]["id"], flow.to_string());
let in_flow = history(format!("&started_by={everything}&top_run={flow}")).await?;
assert_eq!(ids(&in_flow), [step.to_string(), tool.to_string()]);
assert_eq!(in_flow[0]["flow_step_id"], "a");
assert_eq!(in_flow[1]["started_by"], "agent_tool");
let retries = history(format!("&started_by={everything}&top_run={scheduled}")).await?;
assert_eq!(ids(&retries), [retry.to_string()]);
assert_eq!(retries[0]["retry"], 1);
assert_eq!(retries[0]["started_by"], "schedule");
let first = fetch(
"SECRET_TOKEN",
format!("&runnable_id=f/test/long&started_by={top_level}&per_page=1"),
)
.await?;
assert_eq!(ids(&first), [long_running.to_string()]);
assert_eq!(first[0]["running"], true);
let steps = fetch(
"SECRET_TOKEN_2",
"&runnable_id=u/test-user-2/helper&started_by=flow_step".to_string(),
)
.await?;
assert_eq!(ids(&steps), [own_step.to_string()]);
assert_eq!(steps[0]["top_run"]["id"], private_flow.to_string());
assert!(steps[0]["top_run"].get("path").is_none());
Ok(())
}
// Insert a completed script run at path f/test/step, as a flow step when `parent_job` is set.
async fn insert_script_run(
db: &Pool<Postgres>,
struct Run {
kind: &'static str,
path: &'static str,
parent_job: Option<uuid::Uuid>,
) -> anyhow::Result<uuid::Uuid> {
root_job: Option<uuid::Uuid>,
innermost_root: Option<uuid::Uuid>,
flow_step_id: Option<&'static str>,
trigger_kind: Option<&'static str>,
created_by: &'static str,
permissioned_as: &'static str,
failed: bool,
/// Started and not finished: a queue row instead of a completed one.
running: bool,
/// Seconds after a fixed start, so runs are ordered by insertion.
at: i32,
}
impl Default for Run {
fn default() -> Self {
Run {
kind: "script",
path: "",
parent_job: None,
root_job: None,
innermost_root: None,
flow_step_id: None,
trigger_kind: None,
created_by: "test-user",
permissioned_as: "u/test-user",
failed: false,
running: false,
at: 0,
}
}
}
async fn insert_run(db: &Pool<Postgres>, run: Run) -> anyhow::Result<uuid::Uuid> {
let id = uuid::Uuid::new_v4();
sqlx::query(
"INSERT INTO v2_job (id, workspace_id, tag, created_by, permissioned_as, \
permissioned_as_email, kind, runnable_path, parent_job, same_worker, visible_to_owner) \
VALUES ($1, 'test-workspace', 'deno', 'test-user', 'u/test-user', \
'test@windmill.dev', 'script', 'f/test/step', $2, false, true)",
permissioned_as_email, kind, runnable_path, parent_job, root_job, \
flow_innermost_root_job, flow_step_id, trigger_kind, created_at, args, same_worker, \
visible_to_owner) \
VALUES ($1, 'test-workspace', 'deno', $2, $11, 'test@windmill.dev', \
$3::job_kind, $4, $5, $6, $7, $8, $9::job_trigger_kind, \
now() - interval '1 hour' + make_interval(secs => $10), '{}'::jsonb, false, true)",
)
.bind(id)
.bind(parent_job)
.bind(run.created_by)
.bind(run.kind)
.bind(run.path)
.bind(run.parent_job)
.bind(run.root_job)
.bind(run.innermost_root)
.bind(run.flow_step_id)
.bind(run.trigger_kind)
.bind(run.at as f64)
.bind(run.permissioned_as)
.execute(db)
.await?;
if run.running {
sqlx::query(
"INSERT INTO v2_job_queue (id, workspace_id, created_at, started_at, scheduled_for, \
running, tag) \
SELECT id, workspace_id, created_at, created_at, created_at, true, 'deno' \
FROM v2_job WHERE id = $1",
)
.bind(id)
.execute(db)
.await?;
return Ok(id);
}
sqlx::query(
"INSERT INTO v2_job_completed (id, workspace_id, duration_ms, deleted, status) \
VALUES ($1, 'test-workspace', 1, false, 'success')",
"INSERT INTO v2_job_completed (id, workspace_id, duration_ms, deleted, status, \
started_at, completed_at) \
SELECT id, workspace_id, 1, false, $2::job_status, created_at, created_at \
FROM v2_job WHERE id = $1",
)
.bind(id)
.bind(if run.failed { "failure" } else { "success" })
.execute(db)
.await?;
Ok(id)
+103 -6
View File
@@ -25094,11 +25094,22 @@ paths:
in: query
schema:
type: boolean
- name: include_non_root
- name: started_by
in: query
description: also include runs of the runnable as a step of a flow
description: >-
comma-separated RunStartedBy values to list. Runs inside other runs are grouped by
the top-level run that contains them, and runs in progress are included. Ignored
for ScriptHash.
schema:
type: boolean
type: string
- name: top_run
in: query
description: >-
with started_by, list instead the runs of the runnable inside this top-level run,
in execution order, with their args
schema:
type: string
format: uuid
responses:
"200":
description: Input history for completed jobs
@@ -31236,10 +31247,29 @@ components:
type: boolean
success:
type: boolean
parent_job:
started_by:
$ref: "#/components/schemas/RunStartedBy"
trigger_kind:
$ref: "#/components/schemas/JobTriggerKind"
trigger:
type: string
format: uuid
description: set when the run was a step of a flow
description: path of the schedule, app or trigger that started the run
running:
type: boolean
suspended:
type: boolean
flow_step_id:
type: string
retry:
type: integer
description: attempt number, when the run is a retry of an earlier attempt
parent_path:
type: string
description: path of the runnable that called this one, for a script call
top_run:
$ref: "#/components/schemas/InputTopRun"
group:
$ref: "#/components/schemas/InputRunGroup"
required:
- id
- name
@@ -31248,6 +31278,73 @@ components:
- created_at
- is_public
RunStartedBy:
type: string
description: >-
how a run started: manual through trigger and preview for runs with no parent,
flow_step through handler for runs inside another run. A retry takes the category of
its first attempt.
enum:
- manual
- api
- schedule
- app
- trigger
- preview
- flow_step
- agent_tool
- script_call
- handler
InputTopRun:
type: object
description: the top-level run that a history entry's runs sit in
properties:
id:
type: string
format: uuid
kind:
type: string
path:
type: string
success:
type: boolean
running:
type: boolean
trigger_kind:
$ref: "#/components/schemas/JobTriggerKind"
trigger:
type: string
required:
- id
InputRunGroup:
type: object
description: >-
the runs a history entry stands for: the runs of the runnable inside its top_run, or
the retries and other runs of the runnable inside a top-level run listed as the entry
properties:
runs:
type: integer
failed:
type: integer
running:
type: integer
retries:
type: integer
handlers:
type: integer
complete:
type: boolean
description: false when more runs of the group may be older than the runs examined
required:
- runs
- failed
- running
- retries
- handlers
- complete
CreateInput:
type: object
properties:
@@ -1,12 +1,9 @@
<script lang="ts">
import { type RunnableType } from '$lib/gen/index.js'
import { type RunnableType, type RunStartedBy } from '$lib/gen/index.js'
import { sendUserToast } from '$lib/utils.js'
import RunningJobSchemaPicker from '$lib/components/schema/RunningJobSchemaPicker.svelte'
import { createEventDispatcher, onDestroy } from 'svelte'
import { useJobsLoader, type UseJobLoaderArgs } from './runs/useJobsLoader.svelte'
import { DataTable } from '$lib/components/table'
import HistoricList from './HistoricList.svelte'
import { Loader2 } from 'lucide-svelte'
import { TOP_LEVEL_CATEGORIES } from './runHistory'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
const operatingWorkspace = useOperatingWorkspace()
@@ -21,7 +18,8 @@
searchArgs?: Record<string, any> | undefined
/** Workspace to read run history from; defaults to the nav workspace. */
workspace?: string
includeFlowSteps?: boolean
/** Kinds of runs to list; top-level runs by default. */
startedBy?: RunStartedBy[]
}
let {
@@ -33,7 +31,7 @@
limitPayloadSize = false,
searchArgs = undefined,
workspace = undefined,
includeFlowSteps = false
startedBy = TOP_LEVEL_CATEGORIES
}: Props = $props()
let ws = $derived(workspace ?? $operatingWorkspace)
@@ -41,9 +39,6 @@
let historicList: HistoricList | undefined = $state(undefined)
const dispatch = createEventDispatcher()
let hasMoreCurrentRuns = false
let page = $state(1)
async function handleSelected(data: any) {
if (selected === data.id) {
resetSelected(true)
@@ -62,7 +57,7 @@
}
export function loading(): boolean {
return jobsLoader?.loading ?? false
return historicList?.loading() ?? false
}
onDestroy(() => {
@@ -83,8 +78,6 @@
}
}
let jobHovered: string | undefined = undefined
export function refresh(clearCurrentRuns: boolean = false) {
historicList?.refresh(clearCurrentRuns)
}
@@ -95,78 +88,11 @@
dispatch('select', undefined)
}
}
function getJobKinds(runnableType: RunnableType | undefined) {
if (runnableType === 'FlowPath') {
return 'flow,flowpreview'
} else if (runnableType === 'ScriptPath') {
return 'script,preview'
} else if (runnableType === 'ScriptHash') {
return 'script,preview'
}
return ''
}
let jobsLoader = useJobsLoader(
() =>
({
filters: {
show_skipped: false,
path: runnableId,
status: 'running',
arg: searchArgs ? JSON.stringify(searchArgs) : ''
},
perPage: 5,
jobKinds: getJobKinds(runnableType),
syncQueuedRunsCount: false,
refreshRate: 10000,
currentWorkspace: ws ?? '',
skip: !runnableId,
excludesEntrypointOverride: true,
includeFlowSteps
}) satisfies UseJobLoaderArgs
)
let jobs = $derived(jobsLoader?.jobs ?? [])
</script>
<svelte:window onkeydown={handleKeydown} />
<div class="h-full max-h-full min-h-0 w-full flex flex-col gap-2 relative">
<div class="grow-0" data-schema-picker>
<DataTable size="xs" bind:currentPage={page} hasMore={hasMoreCurrentRuns} tableFixed={true}>
{#if jobsLoader?.loading}
<div class="text-primary absolute top-2 right-2">
<Loader2 class="animate-spin" size={14} />
</div>
{/if}
{#if jobs.length > 0}
<colgroup>
<col class="w-8" />
<col class="w-16" />
<col />
</colgroup>
<tbody class="w-full overflow-y-auto">
{#each jobs as job (job.id)}
<RunningJobSchemaPicker
{job}
selected={selected === job.id}
hovering={jobHovered === job.id}
on:select={(e) => handleSelected(e.detail)}
/>
{/each}
{#if jobs.length == 5}
<tr class="text-left text-primary text-xs w-full">
<td class="w-full px-2" colspan="3">limited to 5 runs</td>
</tr>
{/if}
</tbody>
{:else}
<div class="text-center text-primary text-xs py-2">No job currently running</div>
{/if}
</DataTable>
</div>
<div class="min-h-0 grow" data-schema-picker>
<HistoricList
bind:this={historicList}
@@ -179,7 +105,8 @@
{placement}
{limitPayloadSize}
{searchArgs}
{includeFlowSteps}
{startedBy}
workspace={ws}
/>
</div>
</div>
+320 -53
View File
@@ -1,11 +1,30 @@
<script lang="ts">
import { InputService, type RunnableType } from '$lib/gen'
import { onDestroy, untrack } from 'svelte'
import { InputService, type Job, type RunnableType, type RunStartedBy } from '$lib/gen'
import { createEventDispatcher, onDestroy, untrack } from 'svelte'
import { ChevronDown, ChevronRight, ExternalLink, Loader2 } from 'lucide-svelte'
import { twMerge } from 'tailwind-merge'
import InfiniteList from './InfiniteList.svelte'
import JobSchemaPicker from './schema/JobSchemaPicker.svelte'
import { Cell, Row } from './table'
import { Button } from './common'
import { formatDate, formatDateShort, getJobKindIcon } from '$lib/utils'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
import {
innerRunLabel,
innerRunsLabel,
isDefaultSelection,
isGroupEntry,
lastSegment,
logRunHistoryGroupExpand,
shortId,
shortPath,
startedByIcon,
topRunIcon,
type HistoryEntry
} from './runHistory'
const operatingWorkspace = useOperatingWorkspace()
const dispatch = createEventDispatcher()
interface Props {
runnableId: string | undefined
@@ -15,7 +34,11 @@
placement?: 'bottom-start' | 'top-start' | 'bottom-end' | 'top-end'
limitPayloadSize?: boolean
searchArgs?: Record<string, any> | undefined
includeFlowSteps?: boolean
/** Kinds of runs to list, runs inside other runs grouped by the top-level run that holds
* them. Undefined lists only completed top-level runs. */
startedBy?: RunStartedBy[] | undefined
/** Workspace to read run history from; defaults to the operating workspace. */
workspace?: string
}
let {
@@ -26,17 +49,32 @@
placement = 'bottom-start',
limitPayloadSize = false,
searchArgs = undefined,
includeFlowSteps = false
startedBy = undefined,
workspace = undefined
}: Props = $props()
let ws = $derived(workspace ?? $operatingWorkspace)
// An archived script version is read by hash, which the categorized history does not cover.
let categorized = $derived(startedBy != undefined && runnableType !== 'ScriptHash')
let infiniteList: InfiniteList | undefined = $state(undefined)
let loadInputsPageFn: ((page: number, perPage: number) => Promise<any>) | undefined = undefined
let viewerOpen = $state(false)
let openStates: Record<string, boolean> = {} // Track open state for each item
let listLoading = $state(false)
type OpenGroup = { loading: boolean; runs: any[]; summary: string }
let openGroups: Record<string, OpenGroup> = $state({})
let hoveredInner: string | undefined = $state(undefined)
export function loading(): boolean {
return listLoading
}
export async function refresh(clearCurrentRuns: boolean = false) {
if (clearCurrentRuns) {
infiniteList?.reset()
openGroups = {}
}
if (infiniteList) {
await infiniteList.loadData('refresh')
@@ -52,49 +90,121 @@
refreshInterval()
}, 10000)
}
/** What a refresh compares to tell that an entry changed, a running run finishing included. */
function summary(entry: HistoryEntry): string {
const g = entry.group
const top = entry.top_run
return [
entry.created_at,
entry.running,
entry.suspended,
entry.success,
top?.running,
top?.success,
g?.runs,
g?.failed,
g?.running
].join()
}
async function withPayload(input: HistoryEntry) {
if (isGroupEntry(input)) {
return input
}
const isPreview = !!input.is_preview
if (cachedArgs[input.id]) {
return { ...input, payloadData: cachedArgs[input.id] }
}
const payloadData = await loadArgsFromHistory(input.id, undefined, false, isPreview)
if (payloadData === 'WINDMILL_TOO_BIG') {
return {
...input,
payloadData: 'WINDMILL_TOO_BIG',
getFullPayload: () => loadArgsFromHistory(input.id, undefined, true, isPreview)
}
}
cachedArgs[input.id] = payloadData
return { ...input, payloadData }
}
function initLoadInputs() {
refreshInterval()
loadInputsPageFn = async (page: number, perPage: number) => {
const inputs = await InputService.getInputHistory({
workspace: $operatingWorkspace!,
if (categorized && startedBy?.length === 0) {
return []
}
const inputs = (await InputService.getInputHistory({
workspace: ws!,
runnableId,
runnableType,
page,
perPage,
includePreview: true,
includeNonRoot: includeFlowSteps,
startedBy: categorized ? startedBy?.join(',') : undefined,
args: searchArgs ? JSON.stringify(searchArgs) : undefined
})
})) as HistoryEntry[]
const inputsWithPayload = await Promise.all(
inputs.map(async (input) => {
const isPreview = !!(input as any).is_preview
if (cachedArgs[input.id]) {
return {
...input,
payloadData: cachedArgs[input.id]
}
}
const payloadData = await loadArgsFromHistory(input.id, undefined, false, isPreview)
if (payloadData === 'WINDMILL_TOO_BIG') {
return {
...input,
payloadData: 'WINDMILL_TOO_BIG',
getFullPayload: () => loadArgsFromHistory(input.id, undefined, true, isPreview)
}
}
cachedArgs[input.id] = payloadData
return {
...input,
payloadData
}
})
)
const inputsWithPayload = await Promise.all(inputs.map(withPayload))
for (const entry of inputs) {
const open = openGroups[entry.id]
if (open && !open.loading && open.summary !== summary(entry)) {
loadGroup(entry)
}
}
return inputsWithPayload
}
infiniteList?.setLoader(loadInputsPageFn)
}
async function loadGroup(entry: HistoryEntry) {
openGroups[entry.id] = {
loading: true,
runs: openGroups[entry.id]?.runs ?? [],
summary: summary(entry)
}
try {
const runs = (await InputService.getInputHistory({
workspace: ws!,
runnableId,
runnableType,
startedBy: startedBy?.join(','),
topRun: entry.top_run?.id ?? entry.id,
args: searchArgs ? JSON.stringify(searchArgs) : undefined
})) as HistoryEntry[]
if (!openGroups[entry.id]) {
return
}
openGroups[entry.id] = {
loading: false,
summary: summary(entry),
runs: runs.map((run) => {
if (run.args === 'WINDMILL_TOO_BIG') {
return {
...run,
payloadData: 'WINDMILL_TOO_BIG',
getFullPayload: () => loadArgsFromHistory(run.id, undefined, true)
}
}
cachedArgs[run.id] = run.args
return { ...run, payloadData: run.args }
})
}
} catch (err) {
delete openGroups[entry.id]
dispatch('error', { type: 'load', error: err })
}
}
function toggleGroup(entry: HistoryEntry) {
if (openGroups[entry.id]) {
delete openGroups[entry.id]
} else {
loadGroup(entry)
logRunHistoryGroupExpand(isGroupEntry(entry) ? 'group' : 'run')
}
}
onDestroy(() => {
timeout && clearTimeout(timeout)
})
@@ -114,7 +224,7 @@
if (!id) return
const payloadData = await InputService.getArgsFromHistoryOrSavedInput({
jobOrInputId: id,
workspace: $operatingWorkspace!,
workspace: ws!,
input,
allowLarge
})
@@ -126,16 +236,27 @@
viewerOpen = Object.values(openStates).some((state) => state)
}
function onSelect(item: any) {
if (isGroupEntry(item)) {
toggleGroup(item)
} else {
dispatch('select', item)
}
}
$effect(() => {
$operatingWorkspace &&
runnableId &&
runnableType &&
infiniteList &&
untrack(() => initLoadInputs())
ws && runnableId && runnableType && infiniteList && untrack(() => initLoadInputs())
})
</script>
<InfiniteList bind:this={infiniteList} selectedItemId={selected} on:error on:select>
<InfiniteList
bind:this={infiniteList}
bind:loading={listLoading}
selectedItemId={selected}
itemKey={(item) => `${item.id}:${summary(item)}`}
on:error
on:select={(e) => onSelect(e.detail)}
>
{#snippet columns()}
<colgroup>
<col class="w-8" />
@@ -144,23 +265,169 @@
</colgroup>
{/snippet}
{#snippet children({ item, hover })}
<JobSchemaPicker
job={item}
hovering={hover}
payloadData={item.payloadData}
isPreview={!!item.is_preview}
{showAuthor}
{placement}
{viewerOpen}
on:openChange={({ detail }) => {
updateViewerOpenState(item.id, detail)
}}
{limitPayloadSize}
/>
{#if isGroupEntry(item)}
{@const top = item.top_run}
{@const KindIcon = getJobKindIcon(top.kind as Job['job_kind'])}
{@const origin = topRunIcon(top)}
<Cell>
<div class="center-center text-tertiary">
{#if openGroups[item.id]}
<ChevronDown size={14} />
{:else}
<ChevronRight size={14} />
{/if}
</div>
</Cell>
<Cell wrap class="text-2xs font-normal text-left py-2" title={formatDate(item.created_at)}>
{formatDateShort(item.created_at)}
</Cell>
<Cell class="items-center flex flex-row gap-2">
<div class="flex items-center gap-1.5 grow min-w-0 text-xs">
{#if top.running}
<div class="rounded-full w-2 h-2 shrink-0 animate-pulse bg-orange-400" title="Running"
></div>
{:else if top.success != undefined}
<div
class="rounded-full w-2 h-2 shrink-0 {top.success ? 'bg-green-400' : 'bg-red-400'}"
title={top.success ? 'Success' : 'Failed'}
></div>
{/if}
{#if KindIcon}
<KindIcon size={14} class="shrink-0 text-tertiary" />
{/if}
<span class="truncate text-primary" title={top.path ?? top.id}>
{top.path ? shortPath(top.path) : 'Run'}
</span>
<span class="shrink-0 text-tertiary" title={top.id}>·{shortId(top.id)}</span>
{#if origin}
<span class="center-center shrink-0 text-tertiary" title={origin.title}>
<origin.icon size={14} />
</span>
{/if}
</div>
<span class="shrink-0 text-2xs text-secondary whitespace-nowrap">
{item.group.runs}{item.group.complete ? '' : '+'}
{item.group.runs === 1 ? 'run' : 'runs'}
{#if item.group.failed > 0}
· <span class="text-red-500">{item.group.failed} failed</span>
{/if}
{#if item.group.running > 0}
· {item.group.running} running
{/if}
</span>
<a
target="_blank"
href="/run/{top.id}?workspace={ws}"
class="text-secondary px-2"
title="See the top-level run in a new tab"
onclick={(e) => e.stopPropagation()}
>
<ExternalLink size={16} />
</a>
</Cell>
{:else}
{@const inner = innerRunsLabel(item)}
{#snippet innerRunsButton()}
<Button
variant="subtle"
unifiedSize="xs"
endIcon={{ icon: openGroups[item.id] ? ChevronDown : ChevronRight }}
onClick={() => toggleGroup(item)}
>
{inner}
</Button>
{/snippet}
{#snippet insideRun()}
<span
class="flex min-w-0 flex-col px-2 leading-tight"
title="Inside {item.top_run.path ?? 'a run'} ({item.top_run.id})"
>
<span class="truncate text-secondary">
{item.top_run.path ? lastSegment(item.top_run.path) : 'Run'}
</span>
<span class="text-2xs text-tertiary">·{shortId(item.top_run.id)}</span>
</span>
{/snippet}
<JobSchemaPicker
job={item}
hovering={hover}
payloadData={item.payloadData}
isPreview={!!item.is_preview}
{showAuthor}
{placement}
{viewerOpen}
icon={startedByIcon(item)}
aside={inner ? innerRunsButton : item.top_run ? insideRun : undefined}
on:openChange={({ detail }) => {
updateViewerOpenState(item.id, detail)
}}
{limitPayloadSize}
/>
{/if}
{/snippet}
{#snippet afterRow({ item })}
{@const group = openGroups[item.id]}
{#if group}
{#each group.runs as run (run.id)}
<Row
on:click={() => dispatch('select', run)}
on:hover={(e) => (hoveredInner = e.detail ? run.id : undefined)}
class={twMerge(
selected === run.id ? 'bg-surface-selected' : 'hover:bg-surface-hover',
'cursor-pointer rounded-md'
)}
>
<JobSchemaPicker
job={run}
hovering={hoveredInner === run.id}
payloadData={run.payloadData}
{placement}
{viewerOpen}
nested
label={innerRunLabel(run)}
on:openChange={({ detail }) => {
updateViewerOpenState(run.id, detail)
}}
{limitPayloadSize}
/>
</Row>
{/each}
{#if group.loading && group.runs.length === 0}
<tr>
<td colspan="3" class="py-1.5">
<div class="flex justify-center text-tertiary">
<Loader2 size={14} class="animate-spin" />
</div>
</td>
</tr>
{:else if !group.loading && group.runs.length === 0}
<tr>
<td colspan="3" class="py-1.5 pl-10 text-2xs text-secondary">
No runs of the selected kinds in this run
</td>
</tr>
{:else if group.runs.length >= 500}
<tr>
<td colspan="3" class="py-1.5 pl-10 text-2xs text-secondary">
Showing the first 500 runs.
<a target="_blank" href="/run/{item.top_run?.id ?? item.id}?workspace={ws}">
Open the run
</a>
to see the rest.
</td>
</tr>
{/if}
{/if}
{/snippet}
{#snippet empty()}
<div class="text-center text-primary text-xs py-2">
{runnableId ? 'No previous inputs' : 'Save draft to see previous runs'}
{#if !runnableId}
Save draft to see previous runs
{:else if categorized && startedBy && !isDefaultSelection(startedBy)}
No runs of the selected kinds in the latest 5,000 runs
{:else}
No previous inputs
{/if}
</div>
{/snippet}
</InfiniteList>
@@ -18,6 +18,10 @@
neverShowLoader?: boolean
preventXOverflow?: boolean
customRow?: import('svelte').Snippet<[any]>
/** Rows rendered right after an item's row. */
afterRow?: import('svelte').Snippet<[any]>
/** What a refresh compares to tell whether an item changed; its id by default. */
itemKey?: (item: any) => string
columns?: import('svelte').Snippet
extra_row?: import('svelte').Snippet<[any]>
children?: import('svelte').Snippet<[any]>
@@ -40,6 +44,8 @@
neverShowLoader = false,
preventXOverflow = false,
customRow,
afterRow,
itemKey = (item) => item.id,
columns,
extra_row,
children,
@@ -90,7 +96,7 @@
items &&
items?.length > 0 &&
newItems.length === items?.length &&
newItems.every((i, index) => i.id === items?.[index]?.id)
newItems.every((i, index) => items?.[index] && itemKey(i) === itemKey(items[index]))
) {
return
}
@@ -206,6 +212,7 @@
{@render children?.({ item, hover })}
</Row>
{/if}
{@render afterRow?.({ item })}
{/each}
</tbody>
@@ -0,0 +1,103 @@
<script lang="ts">
import type { RunStartedBy, RunnableType } from '$lib/gen'
import { ChevronDown } from 'lucide-svelte'
import { Button } from './common'
import Checkbox from './common/checkbox/Checkbox.svelte'
import { Popover } from './meltComponents'
import {
availableCategories,
CATEGORY_LABELS,
INSIDE_CATEGORIES,
isDefaultSelection,
logRunHistoryFilter,
selectionLabel,
TOP_LEVEL_CATEGORIES
} from './runHistory'
interface Props {
selected: RunStartedBy[]
runnableType: RunnableType | undefined
onChange: (selected: RunStartedBy[]) => void
}
let { selected, runnableType, onChange }: Props = $props()
let available = $derived(availableCategories(runnableType))
let isDefault = $derived(isDefaultSelection(available.filter((c) => selected.includes(c))))
const sections = [
{ title: 'Started on their own', categories: TOP_LEVEL_CATEGORIES },
{ title: 'Started inside another run', categories: INSIDE_CATEGORIES }
]
function toggle(category: RunStartedBy, on: boolean) {
const others = selected.filter((c) => c !== category)
onChange(on ? [...others, category] : others)
logRunHistoryFilter(`${category}:${on ? 'on' : 'off'}`)
}
</script>
<Popover
class="w-fit"
usePointerDownOutside
closeOnOtherPopoverOpen
on:click={(e) => {
e.stopPropagation()
}}
floatingConfig={{ placement: 'bottom-end' }}
>
{#snippet trigger()}
<Button
unifiedSize="sm"
variant="default"
selected={!isDefault}
endIcon={{ icon: ChevronDown }}
nonCaptureEvent
title="Kinds of runs listed"
>
{selectionLabel(selected, available)}
</Button>
{/snippet}
{#snippet content()}
<div class="p-3 w-[440px] max-w-[90vw] flex flex-col gap-2">
<div class="grid grid-cols-2 gap-x-6">
{#each sections as section (section.title)}
<div class="flex flex-col gap-1">
<div class="text-2xs font-semibold text-secondary pb-0.5">{section.title}</div>
{#each section.categories.filter((c) => available.includes(c)) as category (category)}
<label class="flex items-start gap-2 text-xs text-primary cursor-pointer py-0.5">
<!-- Toggled on click: the popover cancels the click's default, so no
change event would follow. -->
<Checkbox
class="mt-0.5"
checked={selected.includes(category)}
onClick={() => toggle(category, !selected.includes(category))}
/>
<span class="flex flex-col">
{CATEGORY_LABELS[category].label}
{#if CATEGORY_LABELS[category].hint}
<span class="text-2xs text-tertiary">{CATEGORY_LABELS[category].hint}</span>
{/if}
</span>
</label>
{/each}
</div>
{/each}
</div>
<div class="flex items-center justify-between gap-2 border-t border-border-light pt-2">
<span class="text-2xs text-tertiary">Retries are listed under their first attempt.</span>
<Button
variant="subtle"
unifiedSize="xs"
disabled={isDefault}
onClick={() => {
onChange([...TOP_LEVEL_CATEGORIES])
logRunHistoryFilter('reset')
}}
>
Reset to default
</Button>
</div>
</div>
{/snippet}
</Popover>
@@ -12,7 +12,9 @@
import SchemaForm from './SchemaForm.svelte'
import MultiSelect from './select/MultiSelect.svelte'
import { safeSelectItems } from './select/utils.svelte'
import Toggle from './Toggle.svelte'
import RunHistoryFilter from './RunHistoryFilter.svelte'
import { availableCategories, parseCategories, TOP_LEVEL_CATEGORIES } from './runHistory'
import { useLocalStorageValue } from '$lib/svelte5Utils.svelte'
const dispatch = createEventDispatcher()
interface Props {
@@ -71,10 +73,19 @@
let searchArgsFields = $state([] as string[])
let includeFlowSteps = $state(false)
let emptySearchArgs = $derived(Object.keys(appliedSearchArgs).length === 0)
// One choice for every script and flow page in this browser.
const storedStartedBy = useLocalStorageValue(
'run_history_started_by',
TOP_LEVEL_CATEGORIES.join(','),
'string'
)
let storedSelection = $derived(parseCategories(storedStartedBy.val))
let startedBy = $derived(
storedSelection.filter((c) => availableCategories(runnableType).includes(c))
)
let filteredSchema = $derived({
properties: Object.fromEntries(
Object.entries(schema?.properties ?? {}).filter(([key]) => searchArgsFields.includes(key))
@@ -88,18 +99,19 @@
<Section label="History" wrapperClass="h-full" small={true}>
{#snippet action()}
<div class="flex items-center space-x-2">
<Toggle
size="xs"
bind:checked={includeFlowSteps}
options={{
right: 'Flow steps',
rightTooltip: 'Also list runs where this was a step of another flow'
}}
on:change={async () => {
await tick()
historicInputs?.refresh(true)
}}
/>
{#if runnableType !== 'ScriptHash'}
<!-- The whole stored choice: a flow page hides AI agent tools but must
not drop them from the choice script pages share. -->
<RunHistoryFilter
selected={storedSelection}
{runnableType}
onChange={async (selected) => {
storedStartedBy.val = selected.join(',')
await tick()
historicInputs?.refresh(true)
}}
/>
{/if}
<Popover
class="w-fit"
usePointerDownOutside
@@ -190,7 +202,7 @@
selectArgs(e.detail?.args, e.detail ? 'history' : undefined)
}}
searchArgs={emptySearchArgs ? undefined : appliedSearchArgs}
{includeFlowSteps}
{startedBy}
showAuthor
placement="top-end"
/>
+191
View File
@@ -0,0 +1,191 @@
import type { Input, InputTopRun, RunStartedBy, RunnableType } from '$lib/gen'
import { Bot, Code, LayoutDashboard, ShieldAlert } from 'lucide-svelte'
import BarsStaggered from './icons/BarsStaggered.svelte'
import { triggerDisplayNamesMap, triggerIconMapMono } from './triggers/utils'
import { logFeatureUsage } from '$lib/utils/featureUsage'
export type HistoryEntry = Input & { args?: unknown; is_preview?: boolean }
export const TOP_LEVEL_CATEGORIES: RunStartedBy[] = [
'manual',
'api',
'schedule',
'app',
'trigger',
'preview'
]
export const INSIDE_CATEGORIES: RunStartedBy[] = [
'flow_step',
'agent_tool',
'script_call',
'handler'
]
export const CATEGORY_LABELS: Record<RunStartedBy, { label: string; hint?: string }> = {
manual: { label: 'Manual runs', hint: 'Run from the UI' },
api: { label: 'API and webhooks', hint: 'CLI, tokens, MCP' },
schedule: { label: 'Schedules' },
app: { label: 'Apps' },
trigger: { label: 'Triggers', hint: 'HTTP, Kafka, email…' },
preview: { label: 'Editor previews' },
flow_step: { label: 'Flow steps', hint: 'Loops, branches and subflows included' },
agent_tool: { label: 'AI agent tools' },
script_call: { label: 'Script calls', hint: 'SDK, workflow-as-code tasks' },
handler: { label: 'Error and success handlers' }
}
/** Flows cannot be AI agent tools: the agent rejects them. */
export function availableCategories(runnableType: RunnableType | undefined): RunStartedBy[] {
const all = [...TOP_LEVEL_CATEGORIES, ...INSIDE_CATEGORIES]
return runnableType === 'FlowPath' ? all.filter((c) => c !== 'agent_tool') : all
}
/** Selected categories, stored as a comma-separated list; unknown values are dropped. */
export function parseCategories(stored: string): RunStartedBy[] {
const known = new Set<string>(availableCategories(undefined))
return stored.split(',').filter((c): c is RunStartedBy => known.has(c))
}
export function isDefaultSelection(selected: RunStartedBy[]): boolean {
return (
selected.length === TOP_LEVEL_CATEGORIES.length &&
TOP_LEVEL_CATEGORIES.every((c) => selected.includes(c))
)
}
/** What the list holds, for the filter button. */
export function selectionLabel(selected: RunStartedBy[], available: RunStartedBy[]): string {
const shown = available.filter((c) => selected.includes(c))
if (isDefaultSelection(shown)) return 'Top-level runs'
if (shown.length === available.length) return 'Everything'
if (shown.length === 0) return 'No runs'
if (shown.length === 1) return CATEGORY_LABELS[shown[0]].label
return `${shown.length} kinds`
}
const HANDLER_LABELS: Record<string, string> = {
error_handler: 'Error handler',
schedule_error_handler: 'Schedule error handler',
schedule_recovery_handler: 'Recovery handler',
success_handler: 'Success handler',
global: 'Instance error handler'
}
/** Icon and tooltip for how a run started. Manual runs and previews have none: the first is
* the common case and the second keeps its "P" badge. */
export function startedByIcon(run: HistoryEntry): { icon: any; title: string } | undefined {
switch (run.started_by) {
case 'api':
return { icon: triggerIconMapMono.webhook, title: 'Started through the API' }
case 'schedule':
return {
icon: triggerIconMapMono.schedule,
title: run.trigger ? `Schedule ${run.trigger}` : 'Schedule'
}
case 'app':
return { icon: LayoutDashboard, title: run.trigger ? `App ${run.trigger}` : 'App' }
case 'trigger': {
const kind = run.trigger_kind ?? ''
const name = (triggerDisplayNamesMap as Record<string, string>)[kind] ?? 'Trigger'
const icon = (triggerIconMapMono as Record<string, any>)[kind]
return icon ? { icon, title: run.trigger ? `${name} ${run.trigger}` : name } : undefined
}
case 'flow_step':
return { icon: BarsStaggered, title: 'Flow step' }
case 'agent_tool':
return { icon: Bot, title: 'AI agent tool' }
case 'script_call':
return { icon: Code, title: 'Script call' }
case 'handler':
return { icon: ShieldAlert, title: HANDLER_LABELS[run.created_by] ?? 'Handler' }
}
return undefined
}
/** Icon and tooltip for what started a group's top-level run. */
export function topRunIcon(top: InputTopRun): { icon: any; title: string } | undefined {
const kind = top.trigger_kind
if (!kind || kind === 'ui') return undefined
if (kind === 'webhook')
return { icon: triggerIconMapMono.webhook, title: 'Started through the API' }
const name = (triggerDisplayNamesMap as Record<string, string>)[kind] ?? kind
const icon = (triggerIconMapMono as Record<string, any>)[kind]
return icon ? { icon, title: top.trigger ? `${name} ${top.trigger}` : name } : undefined
}
/** What an inner row shows where a top-level run shows its author. */
export function innerRunLabel(run: HistoryEntry): string {
if (run.retry != undefined) return `Retry ${run.retry}`
switch (run.started_by) {
case 'flow_step':
return run.flow_step_id ? `Step ${run.flow_step_id}` : 'Flow step'
case 'agent_tool':
return 'Tool call'
case 'script_call':
return run.parent_path ? `Called by ${shortPath(run.parent_path)}` : 'Script call'
case 'handler':
return HANDLER_LABELS[run.created_by] ?? 'Handler'
}
return run.created_by
}
/** A path cut from the left, keeping its last segment: u/admin/etl/load becomes …/load. */
export function shortPath(path: string | undefined): string {
if (!path) return ''
const i = path.lastIndexOf('/')
return i > 0 ? `…/${path.slice(i + 1)}` : path
}
export function lastSegment(path: string): string {
return path.slice(path.lastIndexOf('/') + 1)
}
export function shortId(id: string): string {
return id.slice(-6)
}
/** Text for the runs an entry holds besides itself: "+2 retries", "+1 handler", "+3 runs". */
export function innerRunsLabel(entry: HistoryEntry): string | undefined {
const group = entry.group
if (!group || group.runs === 0) return undefined
const plus = group.complete ? '' : '+'
const noun =
group.retries === group.runs
? group.runs === 1
? 'retry'
: 'retries'
: group.handlers === group.runs
? group.runs === 1
? 'handler'
: 'handlers'
: group.runs === 1
? 'run'
: 'runs'
return `+${group.runs}${plus} ${noun}`
}
/** A history entry standing for several runs inside another top-level run, opened rather
* than selected. */
export function isGroupEntry(entry: HistoryEntry): boolean {
return !!entry.group && !!entry.top_run
}
// Anonymous counters for the History panel. Same rules as every other `logFeatureUsage`
// caller: the keys below are the whole vocabulary, and no path or run id ever reaches here.
/** A category ticked or unticked in the filter, or the filter reset to its default. */
export type RunHistoryFilterEvent = `${RunStartedBy}:${'on' | 'off'}` | 'reset'
export type RunHistoryGroupEvent =
/** A group row: this runnable's runs inside another top-level run. */
| 'group'
/** A run's "+N" button: its retries, handlers or the runs inside it. */
| 'run'
export function logRunHistoryFilter(event: RunHistoryFilterEvent): void {
logFeatureUsage('run_history', 'filter', { key: event })
}
export function logRunHistoryGroupExpand(event: RunHistoryGroupEvent): void {
logFeatureUsage('run_history', 'group_expand', { key: event })
}
@@ -74,8 +74,6 @@ export interface UseJobLoaderArgs {
lookback?: number
perPage?: number
excludesEntrypointOverride?: boolean
/** Also list runs that are steps of a flow, without widening the job kinds. */
includeFlowSteps?: boolean
}
export function useJobsLoader(args: () => UseJobLoaderArgs) {
@@ -93,7 +91,6 @@ export function useJobsLoader(args: () => UseJobLoaderArgs) {
let timeframe = $derived(_args?.timeframe)
let perPage = $derived(_args?.perPage ?? 1000)
let excludesEntrypointOverride = $derived(_args.excludesEntrypointOverride ?? false)
let includeFlowSteps = $derived(_args.includeFlowSteps ?? false)
let label = $derived(filters?.label ?? null)
let worker = $derived(filters?.worker ?? null)
@@ -489,7 +486,7 @@ export function useJobsLoader(args: () => UseJobLoaderArgs) {
? false
: undefined,
// isFlowStep: jobKindsCat != 'all' ? false : undefined,
hasNullParent: jobKindsCat != 'all' && !includeFlowSteps ? true : undefined,
hasNullParent: jobKindsCat != 'all' ? true : undefined,
label: label == null || label === '' ? undefined : label,
tag: tag == null || tag === '' ? undefined : tag,
worker: worker == null || worker === '' ? undefined : worker,
@@ -942,7 +939,6 @@ export function useJobsLoader(args: () => UseJobLoaderArgs) {
perPage
showSchedules
showFutureJobs
includeFlowSteps
clearTimeout(paramChangeTimeout)
paramChangePromise?.cancel()
paramChangeTimeout = setTimeout(() => {
@@ -1,7 +1,7 @@
<script lang="ts">
import SchemaPickerRow from './SchemaPickerRow.svelte'
import { ExternalLink, Workflow } from 'lucide-svelte'
import { Button } from '$lib/components/common'
import { ExternalLink } from 'lucide-svelte'
import { twMerge } from 'tailwind-merge'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
const operatingWorkspace = useOperatingWorkspace()
@@ -15,6 +15,14 @@
placement?: 'bottom-start' | 'top-start' | 'bottom-end' | 'top-end'
viewerOpen?: boolean
limitPayloadSize?: boolean
/** How the run started, shown before the author. */
icon?: { icon: any; title: string } | undefined
/** Shown instead of the author. */
label?: string | undefined
/** A run listed inside the one above it. */
nested?: boolean
/** Shown instead of the author or label. */
aside?: import('svelte').Snippet
}
let {
@@ -25,7 +33,11 @@
isPreview = false,
placement = 'bottom-start',
viewerOpen = false,
limitPayloadSize = false
limitPayloadSize = false,
icon = undefined,
label = undefined,
nested = false,
aside
}: Props = $props()
</script>
@@ -39,11 +51,21 @@
{limitPayloadSize}
>
{#snippet start()}
<div class="center-center relative">
<div
class="rounded-full w-2 h-2 {job.success ? 'bg-green-400' : 'bg-red-400'}"
title={job.success ? 'Success' : 'Failed'}
></div>
<div class={twMerge('center-center relative', nested && 'pl-3')}>
{#if job.running}
<div
class={twMerge(
'rounded-full w-2 h-2 animate-pulse',
job.suspended ? 'bg-violet-400' : 'bg-orange-400'
)}
title={job.suspended ? 'Suspended' : 'Running'}
></div>
{:else}
<div
class="rounded-full w-2 h-2 {job.success ? 'bg-green-400' : 'bg-red-400'}"
title={job.success ? 'Success' : 'Failed'}
></div>
{/if}
{#if isPreview}
<span
class="absolute -top-1.5 right-0.5 text-[8px] font-bold leading-none text-tertiary"
@@ -53,25 +75,25 @@
</div>
{/snippet}
{#snippet extra()}
<div class="flex flex-row gap-2">
{#if showAuthor}
<div class="flex flex-row items-center gap-2">
{#if icon}
<span class="center-center text-tertiary" title={icon.title}>
<icon.icon size={14} />
</span>
{/if}
{#if aside}
<div class="flex w-28">
{@render aside()}
</div>
{:else if label != undefined}
<span class="text-secondary px-2 w-28 truncate" title={label}>
{label}
</span>
{:else if showAuthor}
<span class="text-secondary px-2 w-28 truncate" title={job.created_by}>
{job.created_by}
</span>
{/if}
{#if job.parent_job}
<div class="center-center">
<Button
variant="subtle"
unifiedSize="xs"
iconOnly
startIcon={{ icon: Workflow }}
target="_blank"
href="/run/{job.parent_job}?workspace={$operatingWorkspace}"
title="Ran as a flow step: see the parent flow run in a new tab"
/>
</div>
{/if}
<div class="center-center">
<a
target="_blank"
@@ -1,86 +0,0 @@
<script lang="ts">
import SchemaPickerRow from './SchemaPickerRow.svelte'
import Skeleton from '$lib/components/common/skeleton/Skeleton.svelte'
import { JobService } from '$lib/gen/index.js'
import { createEventDispatcher, untrack } from 'svelte'
import { ExternalLink } from 'lucide-svelte'
import { Cell, Row } from '$lib/components/table'
import { twMerge } from 'tailwind-merge'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
const operatingWorkspace = useOperatingWorkspace()
const dispatch = createEventDispatcher()
interface Props {
job: any
selected?: boolean
payloadData?: any | undefined
hovering?: boolean
}
let {
job,
selected = false,
payloadData = $bindable(undefined),
hovering = $bindable(false)
}: Props = $props()
let loadingArgs = $state(true)
loadArgsFromRunningJob(untrack(() => job).id)
async function loadArgsFromRunningJob(id: string | undefined) {
if (!id) return
payloadData = await JobService.getJobArgs({
workspace: $operatingWorkspace!,
id
})
loadingArgs = false
}
</script>
{#if loadingArgs}
<Cell>
<Skeleton layout={[[1]]} />
</Cell>
<Cell>
<Skeleton layout={[[1]]} />
</Cell>
<Cell>
<Skeleton layout={[[1]]} />
</Cell>
{:else}
<Row
on:click={() => dispatch('select', { id: job.id, payloadData })}
class={twMerge(
selected === job.id ? 'bg-surface-selected' : 'hover:bg-surface-hover',
'cursor-pointer rounded-md'
)}
on:hover={(e) => (hovering = e.detail ? true : false)}
>
<SchemaPickerRow {payloadData} date={job.started_at} {hovering}>
{#snippet start()}
<div class="center-center">
<div
class={twMerge(
'rounded-full w-2 h-2 animate-pulse',
job.suspend ? 'bg-violet-400' : 'bg-orange-400'
)}
title="Running"
></div>
</div>
{/snippet}
{#snippet extra()}
<div class="center-center {hovering ? '' : '!hidden'}">
<a
target="_blank"
href="/run/{job.id}?workspace={$operatingWorkspace}"
class="text-right float-right text-secondary"
title="See run detail in a new tab"
>
<ExternalLink size={16} />
</a>
</div>
{/snippet}
</SchemaPickerRow>
</Row>
{/if}