forge
Explore
Log in

Don't you dare go Hollow

A job's top-level log groups are now steps: the server saves each one's name, start and end times and place in the log as chunks arrive, reading the masked text so a step name cannot hold a secret

Browse files at this commit

c4b949a4c918981629033945f2148834358e1a57Ahmet Kaan GümüşParent: b1c4695
All checks have passed
Show checks
  • feat
    • a job's top-level log groups are now steps: the server saves each one's name, start and end times and place in the log as chunks arrive, reading the masked text so a step name cannot hold a secret
    • a step left open takes the job's result, a requeued job starts with none, and each step gets a duration estimate by the same rule as a job
    • forge's own job prints Unit tests, Release build, E2E tests and Package as steps
    • the run page shows them: the selected job lists its steps with state and time, each job's row has a thin bar split by step, a step opens the log at its first line with its name held at the top and the failure box out of the way, and the timeline gives the selected job a lane per step
    • a job's preview no longer reads ::endgroup::
  • fix
    • a run page on a phone shows its jobs and log, which a long title had squeezed to nothing
  • style
    • Ctrl K sits by the search hint and no longer reads as the key for Explore
Show full message
✨ feat(ci): a job's top-level log groups are now steps: the server saves each one's name, start and end times and place in the log as chunks arrive, reading the masked text so a step name cannot hold a secret; a step left open takes the job's result, a requeued job starts with none, and each step gets a duration estimate by the same rule as a job; forge's own job prints Unit tests, Release build, E2E tests and Package as steps; the run page shows them: the selected job lists its steps with state and time, each job's row has a thin bar split by step, a step opens the log at its first line with its name held at the top and the failure box out of the way, and the timeline gives the selected job a lane per step; a job's preview no longer reads ::endgroup::; 🐛 fix: a run page on a phone shows its jobs and log, which a long title had squeezed to nothing; 💄 style: Ctrl K sits by the search hint and no longer reads as the key for Explore
.forge/ci.tomlmodified+11 -0
@@ -26,14 +26,25 @@ image = "docker.io/library/rust:1"
26 env = { CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_HOME = "/workspace/.cargo-home", SOURCE_DATE_EPOCH = "0" }26 env = { CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_HOME = "/workspace/.cargo-home", SOURCE_DATE_EPOCH = "0" }
27 # Unit tests run first, so a failure shows before the release build. The e2e tests then run against27 # Unit tests run first, so a failure shows before the release build. The e2e tests then run against
28 # the binary this job ships, so forge is not compiled a third time just for them.28 # the binary this job ships, so forge is not compiled a third time just for them.
29+# The groups are the job's steps on the run page, and `exec 2>&1` keeps a marker in order with cargo's
30+# stderr, which the runner reads from a separate pipe.
29 run = """31 run = """
32+exec 2>&1
33+echo "::group::Unit tests"
30 cargo test --workspace --exclude forge-e2e34 cargo test --workspace --exclude forge-e2e
35+echo "::endgroup::"
36+echo "::group::Release build"
31 cargo build --profile dist -p forge-web -p forge-runner37 cargo build --profile dist -p forge-web -p forge-runner
38+echo "::endgroup::"
39+echo "::group::E2E tests"
32 FORGE_BIN="$PWD/target/dist/forge" cargo test -p forge-e2e40 FORGE_BIN="$PWD/target/dist/forge" cargo test -p forge-e2e
41+echo "::endgroup::"
42+echo "::group::Package"
33 ARCH=$(uname -m)43 ARCH=$(uname -m)
34 cp target/dist/forge forge-$ARCH-linux44 cp target/dist/forge forge-$ARCH-linux
35 cp target/dist/forge-runner forge-runner-$ARCH-linux45 cp target/dist/forge-runner forge-runner-$ARCH-linux
36 sha256sum forge-$ARCH-linux forge-runner-$ARCH-linux > SHA256SUMS46 sha256sum forge-$ARCH-linux forge-runner-$ARCH-linux > SHA256SUMS
47+echo "::endgroup::"
37 """48 """
38 artifacts = ["forge-*-linux", "SHA256SUMS"]49 artifacts = ["forge-*-linux", "SHA256SUMS"]
39 cache = ["target", ".cargo-home"]50 cache = ["target", ".cargo-home"]
crates/forge-ci/src/lib.rsmodified+1 -0
@@ -8,5 +8,6 @@ pub mod error;
8 pub mod mask;8 pub mod mask;
9 pub mod proto;9 pub mod proto;
10 pub mod size;10 pub mod size;
11+pub mod steps;
11 12
12 pub use error::ConfigError;13 pub use error::ConfigError;
crates/forge-ci/src/steps.rsadded+129 -0
@@ -0,0 +1,129 @@
1+//! Job steps from the log: `::group::Name` opens a step and `::endgroup::` closes it, the way the
2+//! browser's log viewer reads them. Only top-level groups are steps; nested groups add no marks.
3+
4+/// The most steps kept per job. Later top-level groups are not stored.
5+pub const MAX_STEPS: usize = 32;
6+/// The longest step name, in characters. Longer names are cut.
7+pub const MAX_STEP_NAME_CHARS: usize = 80;
8+
9+/// A change of step state found in a log line.
10+#[derive(Debug, Clone, PartialEq, Eq)]
11+pub enum StepMark {
12+ /// A top-level group opened. `offset` is the byte position of its line in the log.
13+ Start { name: String, offset: u64 },
14+ /// The open top-level group closed.
15+ End,
16+}
17+
18+/// The marks found in the complete lines of a chunk, and how many bytes of it they used.
19+#[derive(Debug, Clone, PartialEq, Eq)]
20+pub struct Scan {
21+ pub marks: Vec<StepMark>,
22+ /// Bytes through the last newline. A partial last line is left for the next scan.
23+ pub consumed: usize,
24+}
25+
26+/// Reads the complete lines of `bytes`, which start at log byte `base_offset`. `depth` is the
27+/// number of open groups and carries over between scans.
28+pub fn scan(bytes: &[u8], base_offset: u64, depth: &mut u32) -> Scan {
29+ let mut marks = Vec::new();
30+ let mut start = 0;
31+ for (i, &byte) in bytes.iter().enumerate() {
32+ if byte != b'\n' {
33+ continue;
34+ }
35+ let raw = String::from_utf8_lossy(&bytes[start..i]);
36+ let stripped = strip_ansi(&raw);
37+ let line = stripped.strip_suffix('\r').unwrap_or(&stripped);
38+ if let Some(rest) = line.strip_prefix("::group::") {
39+ if *depth == 0 {
40+ let trimmed = rest.trim();
41+ let name = if trimmed.is_empty() { "group" } else { trimmed };
42+ marks.push(StepMark::Start {
43+ name: name.chars().take(MAX_STEP_NAME_CHARS).collect(),
44+ offset: base_offset + start as u64,
45+ });
46+ }
47+ *depth = depth.saturating_add(1);
48+ } else if line.trim_end() == "::endgroup::" {
49+ if *depth == 1 {
50+ marks.push(StepMark::End);
51+ }
52+ *depth = depth.saturating_sub(1);
53+ }
54+ start = i + 1;
55+ }
56+ Scan {
57+ marks,
58+ consumed: start,
59+ }
60+}
61+
62+/// Removes ANSI CSI sequences: `ESC [`, any parameter bytes, then one final byte.
63+fn strip_ansi(line: &str) -> String {
64+ let mut out = String::with_capacity(line.len());
65+ let mut chars = line.chars().peekable();
66+ while let Some(c) = chars.next() {
67+ if c == '\u{1b}' && chars.peek() == Some(&'[') {
68+ chars.next();
69+ for f in chars.by_ref() {
70+ if ('\u{40}'..='\u{7e}').contains(&f) {
71+ break;
72+ }
73+ }
74+ } else {
75+ out.push(c);
76+ }
77+ }
78+ out
79+}
80+
81+#[cfg(test)]
82+mod tests {
83+ use super::*;
84+
85+ #[test]
86+ fn top_level_groups_become_marks_with_offsets() {
87+ let log = b"hi\n::group::Build\nx\n::endgroup::\npartial";
88+ let mut depth = 0;
89+ let found = scan(log, 100, &mut depth);
90+ assert_eq!(found.consumed, log.len() - "partial".len());
91+ assert_eq!(
92+ found.marks,
93+ vec![
94+ StepMark::Start {
95+ name: "Build".into(),
96+ offset: 103
97+ },
98+ StepMark::End,
99+ ]
100+ );
101+ assert_eq!(depth, 0);
102+ }
103+
104+ #[test]
105+ fn nested_groups_add_no_marks() {
106+ let mut depth = 0;
107+ let found = scan(
108+ b"::group::A\n::group::B\n::endgroup::\n::endgroup::\n",
109+ 0,
110+ &mut depth,
111+ );
112+ assert_eq!(found.marks.len(), 2);
113+ assert_eq!(found.marks[1], StepMark::End);
114+ assert_eq!(depth, 0);
115+ }
116+
117+ #[test]
118+ fn ansi_codes_are_stripped_and_empty_names_default() {
119+ let mut depth = 0;
120+ let found = scan(b"\x1b[1;32m::group::\x1b[0m \r\n", 0, &mut depth);
121+ assert_eq!(
122+ found.marks,
123+ vec![StepMark::Start {
124+ name: "group".into(),
125+ offset: 0
126+ }]
127+ );
128+ }
129+}
crates/forge-core/migrations/0071_ci_job_steps.sqladded+16 -0
@@ -0,0 +1,16 @@
1+-- Steps of a CI job: the top-level `::group::` sections of its log, in order. `log_offset` is where the
2+-- group line starts in the log. `step_scanned` and `step_depth` are how far the log was read and how
3+-- many groups are open, so the next scan resumes there. Rows go with the job (ON DELETE CASCADE).
4+-- Applied by store/migrate.rs.
5+
6+CREATE TABLE ci_job_steps (
7+ job_id TEXT NOT NULL REFERENCES ci_jobs(id) ON DELETE CASCADE,
8+ seq INTEGER NOT NULL,
9+ name TEXT NOT NULL,
10+ started_at TEXT NOT NULL,
11+ finished_at TEXT NULL,
12+ log_offset INTEGER NOT NULL,
13+ PRIMARY KEY (job_id, seq)
14+);
15+ALTER TABLE ci_jobs ADD COLUMN step_scanned INTEGER NOT NULL DEFAULT 0;
16+ALTER TABLE ci_jobs ADD COLUMN step_depth INTEGER NOT NULL DEFAULT 0;
crates/forge-core/src/ci.rsmodified+53 -0
@@ -571,6 +571,59 @@ pub struct JobSample {
571 pub secs: i64,571 pub secs: i64,
572 }572 }
573 573
574+/// A step of a job: a top-level `::group::` section of its log (migration 0071).
575+#[derive(Debug, Clone, PartialEq, Eq)]
576+pub struct JobStep {
577+ pub job_id: String,
578+ /// The step's place in its job, from 0.
579+ pub seq: i64,
580+ pub name: String,
581+ pub started_at: String,
582+ /// Set when the group closed. Unset while it is open.
583+ pub finished_at: Option<String>,
584+ /// Byte position of the group's line in the job's log.
585+ pub log_offset: i64,
586+}
587+
588+/// What a step shows: its own state, or the job's once the job ended without closing it.
589+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
590+pub enum StepState {
591+ Running,
592+ Passed,
593+ Failed,
594+ Cancelled,
595+}
596+
597+impl JobStep {
598+ /// A closed step passed. An open one follows its job: a job that succeeded passed it too.
599+ pub fn state(&self, job: JobState) -> StepState {
600+ if self.finished_at.is_some() {
601+ return StepState::Passed;
602+ }
603+ match job {
604+ JobState::Success => StepState::Passed,
605+ JobState::Cancelled => StepState::Cancelled,
606+ JobState::Failure | JobState::Error => StepState::Failed,
607+ _ => StepState::Running,
608+ }
609+ }
610+}
611+
612+/// One step's duration in a recent successful run of a repo, for the CI time estimate. Sampled like
613+/// `JobSample`.
614+#[derive(Debug, Clone, PartialEq, Eq)]
615+pub struct StepSample {
616+ pub git_ref: String,
617+ /// The run's place among the repo's successful runs on its branch, newest first.
618+ pub branch_rank: i64,
619+ /// The run's place among the repo's successful runs on any branch, newest first.
620+ pub repo_rank: i64,
621+ pub job: String,
622+ pub step: String,
623+ /// The step's duration in seconds.
624+ pub secs: i64,
625+}
626+
574 /// A job of one runner, with the run and repo it belongs to, for the runner's admin page. The627 /// A job of one runner, with the run and repo it belongs to, for the runner's admin page. The
575 /// run's page is `/{owner}/{repo}/ci/runs/{run_number}`.628 /// run's page is `/{owner}/{repo}/ci/runs/{run_number}`.
576 #[derive(Debug, Clone, PartialEq, Eq)]629 #[derive(Debug, Clone, PartialEq, Eq)]
crates/forge-core/src/store/ci.rsmodified+175 -4
@@ -14,14 +14,16 @@ use super::{
14 finish, insert_err, missing_row, new_id,14 finish, insert_err, missing_row, new_id,
15 };15 };
16 use crate::ci::{16 use crate::ci::{
17- CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobSample, JobState, MAX_RUNNER_CONCURRENCY,17+ CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobSample, JobState, JobStep,
18- MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, QueueSkips, RestartMode, RunState, RunnerJob,18+ MAX_RUNNER_CONCURRENCY, MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, QueueSkips, RestartMode,
19- RunnerReport, RunnerRestart, STARVE_AFTER_SECS, pick_by_memory, validate_runner_field,19+ RunState, RunnerJob, RunnerReport, RunnerRestart, STARVE_AFTER_SECS, StepSample,
20+ pick_by_memory, validate_runner_field,
20 };21 };
21 use crate::error::{Error, Result};22 use crate::error::{Error, Result};
22 use crate::secret;23 use crate::secret;
23 use crate::time::{now_stamp, stamp_after, stamp_to_unix};24 use crate::time::{now_stamp, stamp_after, stamp_to_unix};
24 use crate::token::{generate_token, hash_token};25 use crate::token::{generate_token, hash_token};
26+use forge_ci::steps::{MAX_STEPS, StepMark};
25 27
26 const JOB_COLS: &str = "id, run_id, name, spec, state, runner_id, exit_code, message, queued_at, \28 const JOB_COLS: &str = "id, run_id, name, spec, state, runner_id, exit_code, message, queued_at, \
27 started_at, finished_at, heartbeat_at, cancel_requested, log_bytes, oom_kills";29 started_at, finished_at, heartbeat_at, cancel_requested, log_bytes, oom_kills";
@@ -1339,7 +1341,8 @@ impl Store {
1339 .execute(1341 .execute(
1340 "UPDATE ci_jobs SET state = 'queued', runner_id = NULL, job_token_hash = NULL, \1342 "UPDATE ci_jobs SET state = 'queued', runner_id = NULL, job_token_hash = NULL, \
1341 started_at = NULL, heartbeat_at = NULL, finished_at = NULL, exit_code = NULL, \1343 started_at = NULL, heartbeat_at = NULL, finished_at = NULL, exit_code = NULL, \
1342- message = NULL, cancel_requested = 0, log_bytes = 0, oom_kills = NULL \1344+ message = NULL, cancel_requested = 0, log_bytes = 0, oom_kills = NULL, \
1345+ step_scanned = 0, step_depth = 0 \
1343 WHERE id = ?1 AND state = 'running'",1346 WHERE id = ?1 AND state = 'running'",
1344 (job_id.to_string(),),1347 (job_id.to_string(),),
1345 )1348 )
@@ -1348,6 +1351,12 @@ impl Store {
1348 if changed != 1 {1351 if changed != 1 {
1349 return Ok(false);1352 return Ok(false);
1350 }1353 }
1354+ tx.execute(
1355+ "DELETE FROM ci_job_steps WHERE job_id = ?1",
1356+ (job_id.to_string(),),
1357+ )
1358+ .await
1359+ .map_err(db_err)?;
1351 recompute_run(&tx, &job.run_id, &now).await?;1360 recompute_run(&tx, &job.run_id, &now).await?;
1352 Ok(true)1361 Ok(true)
1353 }1362 }
@@ -1730,6 +1739,168 @@ impl Store {
1730 Ok(rows.into_iter().flatten().collect())1739 Ok(rows.into_iter().flatten().collect())
1731 }1740 }
1732 1741
1742+ /// How far a job's log has been scanned for steps, and how many groups are open there.
1743+ /// `NotFound` if the job does not exist.
1744+ pub async fn step_scan(&self, job_id: &str) -> Result<(u64, u32)> {
1745+ let conn = self.read_conn().await;
1746+ let row = fetch_opt(
1747+ &conn,
1748+ "SELECT step_scanned, step_depth FROM ci_jobs WHERE id = ?1",
1749+ (job_id.to_string(),),
1750+ |row| Ok((col_int(row, 0)?, col_int(row, 1)?)),
1751+ )
1752+ .await?
1753+ .ok_or(Error::NotFound)?;
1754+ Ok((
1755+ u64::try_from(row.0).unwrap_or(0),
1756+ u32::try_from(row.1).unwrap_or(0),
1757+ ))
1758+ }
1759+
1760+ /// Stores the marks of one log scan and the new scan position. A start is kept while the job
1761+ /// has fewer than `MAX_STEPS` steps. An end closes the newest open step, if any.
1762+ pub async fn apply_step_scan(
1763+ &self,
1764+ job_id: &str,
1765+ scanned: u64,
1766+ depth: u32,
1767+ marks: &[StepMark],
1768+ ) -> Result<()> {
1769+ let now = now_stamp();
1770+ let conn = self.inner.conn.lock().await;
1771+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
1772+ let outcome: Result<()> = async {
1773+ let mut count = fetch_opt(
1774+ &tx,
1775+ "SELECT COUNT(*) FROM ci_job_steps WHERE job_id = ?1",
1776+ (job_id.to_string(),),
1777+ |row| col_int(row, 0),
1778+ )
1779+ .await?
1780+ .unwrap_or(0);
1781+ for mark in marks {
1782+ match mark {
1783+ StepMark::Start { name, offset } => {
1784+ if count >= MAX_STEPS as i64 {
1785+ continue;
1786+ }
1787+ tx.execute(
1788+ "INSERT INTO ci_job_steps \
1789+ (job_id, seq, name, started_at, finished_at, log_offset) \
1790+ VALUES (?1, ?2, ?3, ?4, NULL, ?5)",
1791+ (
1792+ job_id.to_string(),
1793+ count,
1794+ name.clone(),
1795+ now.clone(),
1796+ *offset as i64,
1797+ ),
1798+ )
1799+ .await
1800+ .map_err(db_err)?;
1801+ count += 1;
1802+ }
1803+ StepMark::End => {
1804+ tx.execute(
1805+ "UPDATE ci_job_steps SET finished_at = ?2 \
1806+ WHERE job_id = ?1 AND finished_at IS NULL AND seq = ( \
1807+ SELECT MAX(seq) FROM ci_job_steps \
1808+ WHERE job_id = ?1 AND finished_at IS NULL)",
1809+ (job_id.to_string(), now.clone()),
1810+ )
1811+ .await
1812+ .map_err(db_err)?;
1813+ }
1814+ }
1815+ }
1816+ tx.execute(
1817+ "UPDATE ci_jobs SET step_scanned = ?2, step_depth = ?3 WHERE id = ?1",
1818+ (job_id.to_string(), scanned as i64, i64::from(depth)),
1819+ )
1820+ .await
1821+ .map_err(db_err)?;
1822+ Ok(())
1823+ }
1824+ .await;
1825+ finish(tx, outcome).await
1826+ }
1827+
1828+ /// Every step of a run's jobs, ordered by job, then by step.
1829+ pub async fn steps_for_run(&self, run_id: &str) -> Result<Vec<JobStep>> {
1830+ let conn = self.read_conn().await;
1831+ fetch_all(
1832+ &conn,
1833+ "SELECT s.job_id, s.seq, s.name, s.started_at, s.finished_at, s.log_offset \
1834+ FROM ci_job_steps s JOIN ci_jobs j ON j.id = s.job_id \
1835+ WHERE j.run_id = ?1 ORDER BY s.job_id, s.seq",
1836+ (run_id.to_string(),),
1837+ |row| {
1838+ Ok(JobStep {
1839+ job_id: col_text(row, 0)?,
1840+ seq: col_int(row, 1)?,
1841+ name: col_text(row, 2)?,
1842+ started_at: col_text(row, 3)?,
1843+ finished_at: col_opt_text(row, 4)?,
1844+ log_offset: col_int(row, 5)?,
1845+ })
1846+ },
1847+ )
1848+ .await
1849+ }
1850+
1851+ /// One step's duration in the recent successful runs of a repo, sampled as `recent_job_samples`
1852+ /// samples jobs. Only finished steps of successful jobs count.
1853+ pub async fn recent_step_samples(
1854+ &self,
1855+ repo_id: &str,
1856+ git_refs: &[String],
1857+ ) -> Result<Vec<StepSample>> {
1858+ let mut params: Vec<Value> = Vec::with_capacity(git_refs.len() + 1);
1859+ params.push(Value::Text(repo_id.to_string()));
1860+ params.extend(git_refs.iter().map(|git_ref| Value::Text(git_ref.clone())));
1861+ let scope = if git_refs.is_empty() {
1862+ "done.repo_rank <= 5".to_owned()
1863+ } else {
1864+ let marks: Vec<String> = (2..=git_refs.len() + 1).map(|i| format!("?{i}")).collect();
1865+ format!(
1866+ "(done.branch_rank <= 5 AND done.git_ref IN ({})) OR done.repo_rank <= 5",
1867+ marks.join(", ")
1868+ )
1869+ };
1870+ let sql = format!(
1871+ "WITH done AS ( \
1872+ SELECT id, git_ref, \
1873+ ROW_NUMBER() OVER (PARTITION BY git_ref ORDER BY number DESC) AS branch_rank, \
1874+ ROW_NUMBER() OVER (ORDER BY number DESC) AS repo_rank \
1875+ FROM ci_runs WHERE repo_id = ?1 AND state = 'success' \
1876+ ) \
1877+ SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, s.name, \
1878+ s.started_at, s.finished_at \
1879+ FROM done JOIN ci_jobs j ON j.run_id = done.id \
1880+ JOIN ci_job_steps s ON s.job_id = j.id \
1881+ WHERE ({scope}) \
1882+ AND j.state = 'success' AND s.finished_at IS NOT NULL"
1883+ );
1884+ let conn = self.read_conn().await;
1885+ let rows = fetch_all(&conn, &sql, params, |row| {
1886+ let started = col_opt_text(row, 5)?.as_deref().and_then(stamp_to_unix);
1887+ let finished = col_opt_text(row, 6)?.as_deref().and_then(stamp_to_unix);
1888+ Ok(match (started, finished) {
1889+ (Some(start), Some(end)) => Some(StepSample {
1890+ git_ref: col_text(row, 0)?,
1891+ branch_rank: col_int(row, 1)?,
1892+ repo_rank: col_int(row, 2)?,
1893+ job: col_text(row, 3)?,
1894+ step: col_text(row, 4)?,
1895+ secs: (end - start).max(0),
1896+ }),
1897+ _ => None,
1898+ })
1899+ })
1900+ .await?;
1901+ Ok(rows.into_iter().flatten().collect())
1902+ }
1903+
1733 /// The jobs a runner holds or held: every running one, then its `recent` newest finished jobs1904 /// The jobs a runner holds or held: every running one, then its `recent` newest finished jobs
1734 /// (by start time). Each carries its run's number and its repo's owner and name.1905 /// (by start time). Each carries its run's number and its repo's owner and name.
1735 pub async fn runner_jobs(&self, runner_id: &str, recent: usize) -> Result<Vec<RunnerJob>> {1906 pub async fn runner_jobs(&self, runner_id: &str, recent: usize) -> Result<Vec<RunnerJob>> {
crates/forge-core/src/store/migrate.rsmodified+1 -0
@@ -116,6 +116,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
116 70,116 70,
117 include_str!("../../migrations/0070_pull_viewed_files.sql"),117 include_str!("../../migrations/0070_pull_viewed_files.sql"),
118 ),118 ),
119+ (71, include_str!("../../migrations/0071_ci_job_steps.sql")),
119 ];120 ];
120 121
121 /// The highest migration version this binary knows about.122 /// The highest migration version this binary knows about.
crates/forge-e2e/tests/e2e/ci_e2e.rsmodified+54 -0
@@ -547,6 +547,60 @@ async fn push_run_masks_secrets_keeps_artifacts_and_skips_dependants() {
547 );547 );
548 }548 }
549 549
550+#[tokio::test]
551+async fn run_page_lists_a_jobs_steps_and_a_step_opens_its_part_of_the_log() {
552+ let b = boot().await;
553+ let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
554+ let token = create_token(&b.http, &tahinli, "ci-token").await;
555+ create_repo(&b.http, &tahinli, "r").await;
556+ let worker = register_runner(&b, &tahinli, "runner-a").await;
557+
558+ // Each `::group::` line the job prints is one of its steps.
559+ let work = clone(
560+ &remote(b.port, "tahinli", &token, "tahinli", "r"),
561+ &b.dir.join("tahinli-work"),
562+ );
563+ let sha = push_ci_config(
564+ &work,
565+ "[on]\npush = [\"main\"]\n\n[jobs.build]\nimage = \"docker.io/library/alpine:3\"\nrun = \"echo ::group::Compile; echo built; echo ::endgroup::; echo ::group::Test; echo tested\"\n",
566+ );
567+ let found = wait_statuses(&b.http, &token, &sha, &["ci/build"]).await;
568+ let job_id = job_id_of(&found["ci/build"]);
569+ assert_eq!(worker.drain().await, 1, "the build job runs");
570+
571+ let page = b
572+ .http
573+ .get(
574+ &format!("{REPO_PATH}/ci/runs/1?job={job_id}"),
575+ Some(&tahinli),
576+ )
577+ .await;
578+ assert_eq!(page.status, 200, "GET run page");
579+ assert!(
580+ page.body.contains("ci-tl-stepname") && page.body.contains("Compile"),
581+ "the rail lists the step names: {}",
582+ page.body
583+ );
584+ assert!(
585+ page.body.contains("step=0"),
586+ "a step links to its part of the log"
587+ );
588+
589+ let step = b
590+ .http
591+ .get(
592+ &format!("{REPO_PATH}/ci/runs/1?job={job_id}&step=1"),
593+ Some(&tahinli),
594+ )
595+ .await;
596+ assert_eq!(step.status, 200, "GET the step's run page");
597+ assert!(
598+ step.body.contains(r#"data-log-start="true""#),
599+ "the log opens at the step: {}",
600+ step.body
601+ );
602+}
603+
550 #[tokio::test]604 #[tokio::test]
551 async fn fork_pull_waits_for_approval_and_runs_without_secrets() {605 async fn fork_pull_waits_for_approval_and_runs_without_secrets() {
552 let b = boot().await;606 let b = boot().await;
crates/forge-web/assets/nav.jsmodified+5 -3
@@ -219,9 +219,11 @@
219 }219 }
220 220
221 // The log tail is a terminal: it opens at its end. A reader who scrolls up keeps their place.221 // The log tail is a terminal: it opens at its end. A reader who scrolls up keeps their place.
222+ // A step's part of the log (data-log-start) opens at its top: the reader came for its first line.
222 function followTail() {223 function followTail() {
223 var pre = document.querySelector('[data-live-log]');224 var pre = document.querySelector('[data-live-log]');
224- if (pre && !pre.querySelector('.ll-sel')) { pre.scrollTop = pre.scrollHeight; }225+ if (!pre || pre.querySelector('.ll-sel')) { return; }
226+ pre.scrollTop = pre.hasAttribute('data-log-start') ? 0 : pre.scrollHeight;
225 }227 }
226 228
227 // The run page's job rows each have a last-line preview and a tail that opens under the row229 // The run page's job rows each have a last-line preview and a tail that opens under the row
@@ -326,7 +328,7 @@
326 var saved = history.state;328 var saved = history.state;
327 // A live swap keeps the log tail where the reader had it: at the end it stays at the end.329 // A live swap keeps the log tail where the reader had it: at the end it stays at the end.
328 var tail = how === 'live' ? document.querySelector('[data-live-log]') : null;330 var tail = how === 'live' ? document.querySelector('[data-live-log]') : null;
329- var tailAt = tail ? { top: tail.scrollTop, end: tail.scrollTop + tail.clientHeight >= tail.scrollHeight - 24 } : null;331+ var tailAt = tail ? { top: tail.scrollTop, end: tail.scrollTop + tail.clientHeight >= tail.scrollHeight - 24, start: tail.hasAttribute('data-log-start') } : null;
330 // A live change must not shut a menu the reader has open (a run's branch picker, say).332 // A live change must not shut a menu the reader has open (a run's branch picker, say).
331 var dd = how === 'live' ? captureDropdowns() : null;333 var dd = how === 'live' ? captureDropdowns() : null;
332 var at = how === 'live' ? captureAnchor() : null;334 var at = how === 'live' ? captureAnchor() : null;
@@ -342,7 +344,7 @@
342 if (paneTops) { setPaneScrolls(paneTops); }344 if (paneTops) { setPaneScrolls(paneTops); }
343 if (tailAt) {345 if (tailAt) {
344 var nextTail = document.querySelector('[data-live-log]');346 var nextTail = document.querySelector('[data-live-log]');
345- if (nextTail) { nextTail.scrollTop = tailAt.end ? nextTail.scrollHeight : tailAt.top; }347+ if (nextTail) { nextTail.scrollTop = tailAt.end && !tailAt.start ? nextTail.scrollHeight : tailAt.top; }
346 }348 }
347 if (how === 'nav') { history.pushState(null, '', dest.href); }349 if (how === 'nav') { history.pushState(null, '', dest.href); }
348 else if (how === 'post' || how === 'query') { history.replaceState(null, '', dest.href); }350 else if (how === 'post' || how === 'query') { history.replaceState(null, '', dest.href); }
crates/forge-web/src/ci/api.rsmodified+40 -0
@@ -43,6 +43,9 @@ const LOG_OFFSET_HEADER: &str = "x-forge-log-offset";
43 const LOG_SIZE_HEADER: &str = "x-forge-log-size";43 const LOG_SIZE_HEADER: &str = "x-forge-log-size";
44 /// Largest log chunk, in bytes.44 /// Largest log chunk, in bytes.
45 const MAX_LOG_CHUNK: usize = 1024 * 1024;45 const MAX_LOG_CHUNK: usize = 1024 * 1024;
46+/// Longest line the step scan waits for. A longer line with no newline is passed over, so a log
47+/// with no newlines is not read again and again.
48+const MAX_STEP_LINE: usize = 1024 * 1024;
46 /// Largest JSON body on the runner routes, in bytes.49 /// Largest JSON body on the runner routes, in bytes.
47 const MAX_JSON_BODY: usize = 64 * 1024;50 const MAX_JSON_BODY: usize = 64 * 1024;
48 /// Largest runner log batch, in bytes. A batch holds at most 1000 lines of up to 4 KiB each.51 /// Largest runner log batch, in bytes. A batch holds at most 1000 lines of up to 4 KiB each.
@@ -907,6 +910,10 @@ async fn write_log(
907 .add_log_bytes(&job.id, len as i64)910 .add_log_bytes(&job.id, len as i64)
908 .await911 .await
909 .map_err(api::internal)?;912 .map_err(api::internal)?;
913+ // A failure here must not fail the append: the runner would retry it and read a duplicate.
914+ if let Err(e) = record_steps(state, &job.id, &path).await {
915+ tracing::warn!(error = %e, job = %job.id, "ci: could not record job steps");
916+ }
910 state.ci_live.bump_job(&job.id);917 state.ci_live.bump_job(&job.id);
911 // The run page shows the last log lines, so its streams wake too. The page debounces.918 // The run page shows the last log lines, so its streams wake too. The page debounces.
912 state.ci_live.bump_run(&job.run_id);919 state.ci_live.bump_run(&job.run_id);
@@ -916,6 +923,39 @@ async fn write_log(
916 Ok(LogWrite::Stored(size + len))923 Ok(LogWrite::Stored(size + len))
917 }924 }
918 925
926+/// Scans the file's log from the last scanned byte for step marks and stores them. The file is read,
927+/// not the chunk: it holds the masked text, and its offsets are the ones the job page seeks to.
928+async fn record_steps(
929+ state: &AppState,
930+ job_id: &str,
931+ path: &std::path::Path,
932+) -> Result<(), CoreError> {
933+ use tokio::io::{AsyncReadExt, AsyncSeekExt};
934+
935+ let (scanned, mut depth) = state.store.step_scan(job_id).await?;
936+ let mut file = match tokio::fs::File::open(path).await {
937+ Ok(file) => file,
938+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
939+ Err(e) => return Err(e.into()),
940+ };
941+ file.seek(std::io::SeekFrom::Start(scanned)).await?;
942+ let mut bytes = Vec::new();
943+ file.read_to_end(&mut bytes).await?;
944+ let found = forge_ci::steps::scan(&bytes, scanned, &mut depth);
945+ let used = if found.consumed == 0 && bytes.len() >= MAX_STEP_LINE {
946+ bytes.len()
947+ } else {
948+ found.consumed
949+ };
950+ if used == 0 {
951+ return Ok(());
952+ }
953+ state
954+ .store
955+ .apply_step_scan(job_id, scanned + used as u64, depth, &found.marks)
956+ .await
957+}
958+
919 /// Masks a chunk with the values of the job's secrets. The chunk is masked on its own, so a959 /// Masks a chunk with the values of the job's secrets. The chunk is masked on its own, so a
920 /// secret split across two requests is masked by the runner, which holds back the boundary.960 /// secret split across two requests is masked by the runner, which holds back the boundary.
921 async fn mask_for_job(state: &AppState, job: &CiJob, chunk: &[u8]) -> Result<Vec<u8>, Refusal> {961 async fn mask_for_job(state: &AppState, job: &CiJob, chunk: &[u8]) -> Result<Vec<u8>, Refusal> {
crates/forge-web/src/ci/api_tests.rsmodified+28 -0
@@ -398,6 +398,34 @@ async fn logs_append_retry_mismatch_and_mask() {
398 assert_eq!(sent.status, 400);398 assert_eq!(sent.status, 400);
399 }399 }
400 400
401+#[tokio::test]
402+async fn a_group_split_across_chunks_is_a_step_and_an_unclosed_one_stays_open() {
403+ let env = bare(|_| {}).await;
404+ let (_, secret) = runner(&env, &[]).await;
405+ let run = make_run(&env, "push", None, COMMIT, &[job("test", spec(&[], &[]))]).await;
406+ let assignment = claim_job(&env.router, &secret).await;
407+ let job_id = assignment["job_id"].as_str().unwrap().to_owned();
408+ let token = assignment["job_token"].as_str().unwrap().to_owned();
409+
410+ // The `::group::Build` line is split between two chunks. Its offset is the start of its line.
411+ let first = b"setup\n::gro";
412+ let (uri, headers, body) = log_post(&job_id, &token, 0, first);
413+ let sent = send(&env.router, "POST", &uri, &headers, body).await;
414+ assert_eq!(sent.status, 200, "{}", sent.json());
415+ let rest = b"up::Build\nbuild\n::endgroup::\n::group::Test\nrunning\n";
416+ let (uri, headers, body) = log_post(&job_id, &token, first.len() as u64, rest);
417+ let sent = send(&env.router, "POST", &uri, &headers, body).await;
418+ assert_eq!(sent.status, 200, "{}", sent.json());
419+
420+ let steps = env.store.steps_for_run(&run.id).await.unwrap();
421+ assert_eq!(steps.len(), 2);
422+ assert_eq!(steps[0].name, "Build");
423+ assert!(steps[0].finished_at.is_some(), "Build is closed");
424+ assert_eq!(steps[0].log_offset, 6, "the group line starts after setup");
425+ assert_eq!(steps[1].name, "Test");
426+ assert!(steps[1].finished_at.is_none(), "Test is still open");
427+}
428+
401 #[test]429 #[test]
402 fn log_cap_keeps_what_fits_then_one_marker() {430 fn log_cap_keeps_what_fits_then_one_marker() {
403 // 100 byte cap. The marker is 17 bytes, so 83 bytes of data fit.431 // 100 byte cap. The marker is 17 bytes, so 83 bytes of data fit.
crates/forge-web/src/pages/ci_estimate.rsmodified+46 -6
@@ -2,11 +2,11 @@
2 //! store hands in the samples, the run's jobs go in as steps, and the answers are unix seconds,2 //! store hands in the samples, the run's jobs go in as steps, and the answers are unix seconds,
3 //! seconds or the page's words. The estimate of a job is the median of its last five successful runs3 //! seconds or the page's words. The estimate of a job is the median of its last five successful runs
4 //! on the branch, or on any branch when the branch has fewer than `MIN_SAMPLES`. Failed and cancelled4 //! on the branch, or on any branch when the branch has fewer than `MIN_SAMPLES`. Failed and cancelled
5-//! runs are never sampled.5+//! runs are never sampled. A step's estimate follows the same rule, from its own durations.
6 6
7 use std::collections::{HashMap, HashSet};7 use std::collections::{HashMap, HashSet};
8 8
9-use forge_core::ci::{JobSample, JobState};9+use forge_core::ci::{JobSample, JobState, StepSample};
10 use serde::Deserialize;10 use serde::Deserialize;
11 11
12 use crate::i18n::Lang;12 use crate::i18n::Lang;
@@ -40,17 +40,57 @@ pub fn needs_of(spec_json: &str) -> Vec<String> {
40 /// five successful runs on that branch, or in the newest five on any branch when the branch has fewer40 /// five successful runs on that branch, or in the newest five on any branch when the branch has fewer
41 /// than `MIN_SAMPLES`. None when neither has enough.41 /// than `MIN_SAMPLES`. None when neither has enough.
42 pub fn job_expected(samples: &[JobSample], git_ref: &str, job: &str) -> Option<i64> {42 pub fn job_expected(samples: &[JobSample], git_ref: &str, job: &str) -> Option<i64> {
43- let on_branch: Vec<i64> = samples43+ let rows: Vec<Sample> = samples
44 .iter()44 .iter()
45- .filter(|s| s.job == job && s.git_ref == git_ref && s.branch_rank <= 5)45+ .filter(|s| s.job == job)
46+ .map(|s| Sample {
47+ git_ref: &s.git_ref,
48+ branch_rank: s.branch_rank,
49+ repo_rank: s.repo_rank,
50+ secs: s.secs,
51+ })
52+ .collect();
53+ expected_of(&rows, git_ref)
54+}
55+
56+/// The expected duration of `step` of `job` on `git_ref`, in seconds, by the same rule as
57+/// `job_expected`. None when neither the branch nor the repo has enough samples.
58+pub fn step_expected(samples: &[StepSample], git_ref: &str, job: &str, step: &str) -> Option<i64> {
59+ let rows: Vec<Sample> = samples
60+ .iter()
61+ .filter(|s| s.job == job && s.step == step)
62+ .map(|s| Sample {
63+ git_ref: &s.git_ref,
64+ branch_rank: s.branch_rank,
65+ repo_rank: s.repo_rank,
66+ secs: s.secs,
67+ })
68+ .collect();
69+ expected_of(&rows, git_ref)
70+}
71+
72+/// One duration sample of a job or step, with the ranks that place it.
73+struct Sample<'a> {
74+ git_ref: &'a str,
75+ branch_rank: i64,
76+ repo_rank: i64,
77+ secs: i64,
78+}
79+
80+/// The rule both estimates share: the median of the newest five on `git_ref` when that has
81+/// `MIN_SAMPLES`, else of the newest five on any branch when that has them. None otherwise.
82+fn expected_of(rows: &[Sample], git_ref: &str) -> Option<i64> {
83+ let on_branch: Vec<i64> = rows
84+ .iter()
85+ .filter(|s| s.git_ref == git_ref && s.branch_rank <= 5)
46 .map(|s| s.secs)86 .map(|s| s.secs)
47 .collect();87 .collect();
48 if on_branch.len() >= MIN_SAMPLES {88 if on_branch.len() >= MIN_SAMPLES {
49 return Some(median(on_branch));89 return Some(median(on_branch));
50 }90 }
51- let any: Vec<i64> = samples91+ let any: Vec<i64> = rows
52 .iter()92 .iter()
53- .filter(|s| s.job == job && s.repo_rank <= 5)93+ .filter(|s| s.repo_rank <= 5)
54 .map(|s| s.secs)94 .map(|s| s.secs)
55 .collect();95 .collect();
56 (any.len() >= MIN_SAMPLES).then(|| median(any))96 (any.len() >= MIN_SAMPLES).then(|| median(any))
crates/forge-web/src/pages/ci_job.rsmodified+48 -0
@@ -196,6 +196,54 @@ pub(crate) async fn log_tail_of(path: &Path, max: u64) -> Result<Tail> {
196 })196 })
197 }197 }
198 198
199+/// The log from byte `offset`, at most `max` bytes. `offset` should be the start of a line, such as a
200+/// step's. When the file goes on past the bytes read, the text is cut back to its last newline. A log
201+/// that does not exist yet is empty. `truncated` is never set: nothing is cut at the start.
202+pub(crate) async fn log_from(path: &Path, offset: u64, max: u64) -> Result<Tail> {
203+ let mut file = match tokio::fs::File::open(path).await {
204+ Ok(file) => file,
205+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
206+ return Ok(Tail {
207+ text: String::new(),
208+ truncated: false,
209+ offset: 0,
210+ first_line: 1,
211+ });
212+ }
213+ Err(e) => return Err(forge_core::Error::Io(e).into()),
214+ };
215+ let len = file.metadata().await.map_err(forge_core::Error::Io)?.len();
216+ let start = offset.min(len);
217+ file.seek(SeekFrom::Start(start))
218+ .await
219+ .map_err(forge_core::Error::Io)?;
220+ let mut buf = Vec::new();
221+ (&mut file)
222+ .take(max)
223+ .read_to_end(&mut buf)
224+ .await
225+ .map_err(forge_core::Error::Io)?;
226+ if start + (buf.len() as u64) < len {
227+ // A single line longer than `max` stays as it is: an empty page would hide it.
228+ if let Some(end) = buf.iter().rposition(|byte| *byte == b'\n') {
229+ buf.truncate(end + 1);
230+ }
231+ }
232+ buf.truncate(whole_utf8_len(&buf));
233+ let offset = start + buf.len() as u64;
234+ let first_line = if start > 0 {
235+ newlines_before(path, start).await? + 1
236+ } else {
237+ 1
238+ };
239+ Ok(Tail {
240+ text: String::from_utf8_lossy(&buf).into_owned(),
241+ truncated: false,
242+ offset,
243+ first_line,
244+ })
245+}
246+
199 /// Follows a log: yields what the file holds, then sends new bytes each time the job changes (its247 /// Follows a log: yields what the file holds, then sends new bytes each time the job changes (its
200 /// log grew or its state did). The stream ends when the job is terminal and a read after seeing248 /// log grew or its state did). The stream ends when the job is terminal and a read after seeing
201 /// that returns nothing, so every byte the runner wrote is sent. A job that is gone, a read249 /// that returns nothing, so every byte the runner wrote is sent. A job that is gone, a read
crates/forge-web/src/pages/ci_runs.rsmodified+341 -28
@@ -13,7 +13,7 @@ use std::future::Future;
13 use std::path::Path;13 use std::path::Path;
14 use std::time::Duration;14 use std::time::Duration;
15 15
16-use forge_core::ci::{CiJob, CiRun, JobSample, JobState, RunState};16+use forge_core::ci::{CiJob, CiRun, JobSample, JobState, JobStep, RunState, StepSample, StepState};
17 use forge_core::{Action, Denied, Store, User, authorize};17 use forge_core::{Action, Denied, Store, User, authorize};
18 use forge_git::browse::{RefInfo, RefKind, commit_reachable, reachable_commits, read_commit};18 use forge_git::browse::{RefInfo, RefKind, commit_reachable, reachable_commits, read_commit};
19 use futures_util::{Stream, StreamExt, stream};19 use futures_util::{Stream, StreamExt, stream};
@@ -41,7 +41,7 @@ use crate::i18n::{
41 };41 };
42 use crate::pages::ci_estimate::{self, Est, Step};42 use crate::pages::ci_estimate::{self, Est, Step};
43 use crate::pages::ci_fail::{self, FailFirst, fail_first_block};43 use crate::pages::ci_fail::{self, FailFirst, fail_first_block};
44-use crate::pages::ci_job::{Tail, log_tail_of};44+use crate::pages::ci_job::{Tail, log_from, log_tail_of};
45 use crate::pages::refs::load_refs;45 use crate::pages::refs::load_refs;
46 use crate::pages::repo::repo_head;46 use crate::pages::repo::repo_head;
47 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable};47 use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable};
@@ -420,6 +420,25 @@ struct JobLine {
420 rerun: Option<String>,420 rerun: Option<String>,
421 /// A running job whose cancel was requested: it shows as stopping until its runner stops it.421 /// A running job whose cancel was requested: it shows as stopping until its runner stops it.
422 stopping: bool,422 stopping: bool,
423+ /// The job's steps under its row. Only the selected job has lines; the others have none.
424+ steps: Vec<StepLine>,
425+ /// The job's bar along the bottom of its row: one segment per step. Empty for a job with no steps.
426+ step_bar: Vec<Rect>,
427+}
428+
429+/// One step of the selected job, drawn as a line under its row in the jobs pane.
430+struct StepLine {
431+ name: String,
432+ /// The classes of the step's mark, which carry its state's colour.
433+ mark: &'static str,
434+ duration: String,
435+ /// Unix seconds a running step's duration counts from.
436+ since: Option<String>,
437+ /// The expected duration of a running step, as "~2m".
438+ expected: Option<String>,
439+ /// The link that opens the step's part of the log. None when the job's log was pruned.
440+ href: Option<String>,
441+ selected: bool,
423 }442 }
424 443
425 /// One artifact of the run: its download link, the job that made it, its name and size.444 /// One artifact of the run: its download link, the job that made it, its name and size.
@@ -486,6 +505,8 @@ struct JobLog {
486 truncated: bool,505 truncated: bool,
487 offset: String,506 offset: String,
488 first_line: String,507 first_line: String,
508+ /// Whether the log is one step's part of the job's log: the pre opens at its top, not its end.
509+ at_step: bool,
489 }510 }
490 511
491 /// A box in an SVG, with its class and its position and size in the SVG's units.512 /// A box in an SVG, with its class and its position and size in the SVG's units.
@@ -660,6 +681,19 @@ struct Timing {
660 started: Option<i64>,681 started: Option<i64>,
661 finished: Option<i64>,682 finished: Option<i64>,
662 cancel_requested: bool,683 cancel_requested: bool,
684+ /// The job's log size in bytes. 0 means the log was pruned.
685+ log_bytes: i64,
686+ /// The job's steps, in order, for the timeline's lanes under the selected job.
687+ steps: Vec<StepSpan>,
688+}
689+
690+/// One step of a job on the timeline: its state as the job state its box takes, its start and its end
691+/// in unix seconds (None while it runs).
692+struct StepSpan {
693+ name: String,
694+ state: JobState,
695+ start: i64,
696+ end: Option<i64>,
663 }697 }
664 698
665 impl Timing {699 impl Timing {
@@ -693,8 +727,13 @@ const TRACK_X: i64 = 100;
693 const TRACK_W: i64 = 530;727 const TRACK_W: i64 = 530;
694 const AXIS_H: i64 = 24;728 const AXIS_H: i64 = 24;
695 const ROW_H: i64 = 40;729 const ROW_H: i64 = 40;
730+/// A step's lane under its job's row on the timeline.
731+const STEP_H: i64 = 20;
696 const BAR_DY: i64 = 9;732 const BAR_DY: i64 = 9;
697 const BAR_H: i64 = 22;733 const BAR_H: i64 = 22;
734+/// The narrowest segment of a job's step bar, and the gap between segments, in its SVG units.
735+const STEP_BAR_MIN: i64 = 8;
736+const STEP_BAR_GAP: i64 = 6;
698 /// The narrowest a box is drawn, so a short lead-in or job still shows.737 /// The narrowest a box is drawn, so a short lead-in or job still shows.
699 const MIN_BOX_W: i64 = 3;738 const MIN_BOX_W: i64 = 3;
700 /// The most intervals an axis has, so its ticks stay readable.739 /// The most intervals an axis has, so its ticks stay readable.
@@ -849,7 +888,14 @@ fn row_sub(job: &Timing, lang: Lang) -> Option<String> {
849 /// its box at its real start and end, a hatched lead-in from its queueing, and an elbow connector with888 /// its box at its real start and end, a hatched lead-in from its queueing, and an elbow connector with
850 /// an arrowhead from each needed job's end to the start of the job that needs it. A blocked job is an889 /// an arrowhead from each needed job's end to the start of the job that needs it. A blocked job is an
851 /// outline from its needs' end, and a skipped or cancelled one is an outline across the track.890 /// outline from its needs' end, and a skipped or cancelled one is an outline across the track.
852-fn gantt(jobs: &[Timing], origin: i64, run_end: Option<i64>, now: i64, lang: Lang) -> Gantt {891+fn gantt(
892+ jobs: &[Timing],
893+ origin: i64,
894+ run_end: Option<i64>,
895+ now: i64,
896+ lang: Lang,
897+ selected: Option<usize>,
898+) -> Gantt {
853 let last = jobs899 let last = jobs
854 .iter()900 .iter()
855 .filter_map(|job| job.end(now))901 .filter_map(|job| job.end(now))
@@ -858,9 +904,26 @@ fn gantt(jobs: &[Timing], origin: i64, run_end: Option<i64>, now: i64, lang: Lan
858 .unwrap_or(now);904 .unwrap_or(now);
859 let (step, len) = axis((last - origin).max(1));905 let (step, len) = axis((last - origin).max(1));
860 let x = |at: i64| TRACK_X + place(at - origin, len, TRACK_W);906 let x = |at: i64| TRACK_X + place(at - origin, len, TRACK_W);
861- let row_mid = |i: usize| AXIS_H + i as i64 * ROW_H + ROW_H / 2;907+ // The selected job's steps take a lane each under its row, so every row below it moves down.
908+ let row_height = |i: usize| {
909+ ROW_H
910+ + if selected == Some(i) {
911+ jobs[i].steps.len() as i64 * STEP_H
912+ } else {
913+ 0
914+ }
915+ };
916+ let tops: Vec<i64> = (0..jobs.len())
917+ .scan(AXIS_H, |top, i| {
918+ let at = *top;
919+ *top += row_height(i);
920+ Some(at)
921+ })
922+ .collect();
923+ let row_top = |i: usize| tops[i];
924+ let row_mid = |i: usize| row_top(i) + ROW_H / 2;
862 let track_end = TRACK_X + TRACK_W;925 let track_end = TRACK_X + TRACK_W;
863- let height = AXIS_H + jobs.len() as i64 * ROW_H;926+ let height = AXIS_H + (0..jobs.len()).map(&row_height).sum::<i64>();
864 let mut g = Gantt {927 let mut g = Gantt {
865 view_box: format!("0 0 {GANTT_W} {height}"),928 view_box: format!("0 0 {GANTT_W} {height}"),
866 origin: origin.to_string(),929 origin: origin.to_string(),
@@ -926,8 +989,7 @@ fn gantt(jobs: &[Timing], origin: i64, run_end: Option<i64>, now: i64, lang: Lan
926 let mut targets: Vec<Option<(i64, bool, bool)>> = Vec::with_capacity(jobs.len());989 let mut targets: Vec<Option<(i64, bool, bool)>> = Vec::with_capacity(jobs.len());
927 for (i, job) in jobs.iter().enumerate() {990 for (i, job) in jobs.iter().enumerate() {
928 let row = &rows[i];991 let row = &rows[i];
929- let top = AXIS_H + i as i64 * ROW_H;992+ let bar_y = row_top(i) + BAR_DY;
930- let bar_y = top + BAR_DY;
931 let label_y = (bar_y + BAR_H / 2 + 4).to_string();993 let label_y = (bar_y + BAR_H / 2 + 4).to_string();
932 g.labels.push(Label {994 g.labels.push(Label {
933 class: "ci-gname",995 class: "ci-gname",
@@ -1076,6 +1138,36 @@ fn gantt(jobs: &[Timing], origin: i64, run_end: Option<i64>, now: i64, lang: Lan
1076 },1138 },
1077 }1139 }
1078 }1140 }
1141+ // The selected job's steps: a lane each under its row, with a box at the step's times.
1142+ if let Some(i) = selected.filter(|i| *i < jobs.len()) {
1143+ for (k, step) in jobs[i].steps.iter().enumerate() {
1144+ let lane = row_top(i) + ROW_H + k as i64 * STEP_H;
1145+ let end = step.end.unwrap_or(now);
1146+ let left = x(step.start);
1147+ let width = (x(end) - left).max(MIN_BOX_W);
1148+ let mut bar = Rect::new(
1149+ format!("ci-gstep {}", tone(step.state)),
1150+ left,
1151+ lane + (STEP_H - 10) / 2,
1152+ width,
1153+ 10,
1154+ );
1155+ bar.title = Some(format!(
1156+ "{} \u{b7} {}",
1157+ step.name,
1158+ span_text((end - step.start).max(0))
1159+ ));
1160+ g.rects.push(bar);
1161+ g.labels.push(Label {
1162+ class: "ci-gsub",
1163+ x: "12".to_owned(),
1164+ y: (lane + STEP_H / 2 + 4).to_string(),
1165+ anchor: "start",
1166+ text: gantt_name(&step.name),
1167+ ..Default::default()
1168+ });
1169+ }
1170+ }
1079 let xn = x(now);1171 let xn = x(now);
1080 for (i, job) in jobs.iter().enumerate() {1172 for (i, job) in jobs.iter().enumerate() {
1081 let Some((tx, child_moves, spans)) = targets[i] else {1173 let Some((tx, child_moves, spans)) = targets[i] else {
@@ -1199,7 +1291,126 @@ fn timing_of(job: &CiJob, runner: String, lang: Lang) -> Timing {
1199 started: job.started_at.as_deref().and_then(unix_of),1291 started: job.started_at.as_deref().and_then(unix_of),
1200 finished: job.finished_at.as_deref().and_then(unix_of),1292 finished: job.finished_at.as_deref().and_then(unix_of),
1201 cancel_requested: job.cancel_requested,1293 cancel_requested: job.cancel_requested,
1294+ log_bytes: job.log_bytes,
1295+ steps: Vec::new(),
1296+ }
1297+}
1298+
1299+/// The job state a step's box takes on the timeline: a passed step is a success, a failed one a failure.
1300+fn step_job_state(state: StepState) -> JobState {
1301+ match state {
1302+ StepState::Passed => JobState::Success,
1303+ StepState::Failed => JobState::Failure,
1304+ StepState::Cancelled => JobState::Cancelled,
1305+ StepState::Running => JobState::Running,
1306+ }
1307+}
1308+
1309+/// The steps of a job as the timeline draws them. A step whose start does not read is left out.
1310+fn step_spans(steps: &[JobStep], job: JobState) -> Vec<StepSpan> {
1311+ steps
1312+ .iter()
1313+ .filter_map(|step| {
1314+ Some(StepSpan {
1315+ name: step.name.clone(),
1316+ state: step_job_state(step.state(job)),
1317+ start: unix_of(&step.started_at)?,
1318+ end: step.finished_at.as_deref().and_then(unix_of),
1319+ })
1320+ })
1321+ .collect()
1322+}
1323+
1324+/// A step's share of its job's bar: its state, its elapsed seconds and, while it runs, its expected ones.
1325+struct BarStep {
1326+ state: StepState,
1327+ elapsed: i64,
1328+ expected: Option<i64>,
1329+}
1330+
1331+/// The bar along a job's row: one segment per step, as wide as its seconds (a running step counts the
1332+/// larger of its elapsed and expected seconds), with a gap between segments. A running step with an
1333+/// estimate is a track of its full width with its elapsed share filled in the accent.
1334+fn step_bar(steps: &[BarStep]) -> Vec<Rect> {
1335+ let weight = |step: &BarStep| step.expected.unwrap_or(0).max(step.elapsed).max(1);
1336+ let total: i64 = steps.iter().map(weight).sum();
1337+ let gaps = STEP_BAR_GAP * (steps.len() as i64 - 1).max(0);
1338+ // Every segment gets its least first, so 32 short steps beside a long one still all fit.
1339+ let room = (LIST_BAR_W - gaps - STEP_BAR_MIN * steps.len() as i64).max(0);
1340+ let mut rects = Vec::with_capacity(steps.len() + 1);
1341+ let mut x = 0;
1342+ for step in steps {
1343+ let weight = weight(step);
1344+ let w = STEP_BAR_MIN + weight * room / total;
1345+ match (step.state, step.expected) {
1346+ (StepState::Running, Some(expected)) => {
1347+ rects.push(Rect::new("ci-sbar-track", x, 0, w, 3));
1348+ let done = step.elapsed.min(expected) * w / weight;
1349+ rects.push(Rect::new("ci-sbar-run", x, 0, done, 3));
1350+ }
1351+ (StepState::Running, None) => rects.push(Rect::new("ci-sbar-run", x, 0, w, 3)),
1352+ (StepState::Passed, _) => rects.push(Rect::new("ci-sbar-pass", x, 0, w, 3)),
1353+ (StepState::Failed, _) => rects.push(Rect::new("ci-sbar-fail", x, 0, w, 3)),
1354+ (StepState::Cancelled, _) => rects.push(Rect::new("ci-sbar-off", x, 0, w, 3)),
1355+ }
1356+ x += w + STEP_BAR_GAP;
1357+ }
1358+ rects
1359+}
1360+
1361+/// The rail's step lines of a job and the bar under its row. The lines are kept for the selected job
1362+/// only, and `wanted` marks the step the log shows. A running step's expected time comes from the
1363+/// repo's step samples.
1364+fn job_steps(
1365+ job: &Timing,
1366+ steps: &[JobStep],
1367+ samples: &[StepSample],
1368+ run: &CiRun,
1369+ pick: &str,
1370+ wanted: Option<i64>,
1371+ now: i64,
1372+ lang: Lang,
1373+) -> (Vec<StepLine>, Vec<Rect>) {
1374+ let mut lines = Vec::with_capacity(steps.len());
1375+ let mut bar = Vec::with_capacity(steps.len());
1376+ for step in steps {
1377+ let state = step.state(job.state);
1378+ let running = state == StepState::Running;
1379+ let started = unix_of(&step.started_at);
1380+ let elapsed = started.map_or(0, |at| {
1381+ let end = step.finished_at.as_deref().and_then(unix_of).unwrap_or(now);
1382+ (end - at).max(0)
1383+ });
1384+ let expected = running
1385+ .then(|| ci_estimate::step_expected(samples, &run.git_ref, &job.name, &step.name))
1386+ .flatten();
1387+ bar.push(BarStep {
1388+ state,
1389+ elapsed,
1390+ expected,
1391+ });
1392+ // A step of a job whose log was pruned has no part of the log to open.
1393+ let href = (job.log_bytes != 0).then(|| format!("{pick}&step={}", step.seq));
1394+ lines.push(StepLine {
1395+ name: step.name.clone(),
1396+ mark: match state {
1397+ StepState::Passed => "ci-st-pass",
1398+ StepState::Running => "ci-st-run",
1399+ StepState::Failed => "ci-st-fail",
1400+ StepState::Cancelled => "ci-st-off",
1401+ },
1402+ duration: duration_text(
1403+ lang,
1404+ Some(step.started_at.as_str()),
1405+ step.finished_at.as_deref(),
1406+ ),
1407+ since: started.filter(|_| running).map(|at| at.to_string()),
1408+ expected: expected.map(|secs| format!("~{}", span_text(secs))),
1409+ selected: href.is_some() && wanted == Some(step.seq),
1410+ href,
1411+ });
1202 }1412 }
1413+ (lines, step_bar(&bar))
1203 }1414 }
1204 1415
1205 /// "test OOM" for a failed run: the first failed job's message, or its name and state.1416 /// "test OOM" for a failed run: the first failed job's message, or its name and state.
@@ -1275,7 +1486,12 @@ fn last_line(tail: &[String]) -> Option<&str> {
1275 tail.iter()1486 tail.iter()
1276 .rev()1487 .rev()
1277 .map(|line| line.trim())1488 .map(|line| line.trim())
1278- .find(|line| !line.is_empty())1489+ .find(|line| !line.is_empty() && !is_group_marker(line))
1490+}
1491+
1492+/// Whether a log line only opens or closes a group: it says nothing about what the job did.
1493+fn is_group_marker(line: &str) -> bool {
1494+ line.starts_with("::group::") || line.starts_with("::endgroup::")
1279 }1495 }
1280 1496
1281 /// The last lines of a log, read from its tail only, without ANSI codes and trailing blank lines.1497 /// The last lines of a log, read from its tail only, without ANSI codes and trailing blank lines.
@@ -1354,7 +1570,12 @@ struct SplitPage {
1354 /// The split view of the runs: the list (left) and the selected run (right). Both routes render it.1570 /// The split view of the runs: the list (left) and the selected run (right). Both routes render it.
1355 /// `number` is the run the URL names. Without one, the newest run of the list page is selected.1571 /// `number` is the run the URL names. Without one, the newest run of the list page is selected.
1356 /// The list is live on every page: a run's state, its hint and its age change on any page of it.1572 /// The list is live on every page: a run's state, its hint and its age change on any page of it.
1357-async fn runs_split(cx: &Cx, number: Option<&str>, job: Option<&str>) -> Result<SplitPage> {1573+async fn runs_split(
1574+ cx: &Cx,
1575+ number: Option<&str>,
1576+ job: Option<&str>,
1577+ step: Option<i64>,
1578+) -> Result<SplitPage> {
1358 let owner = path_param::<Owner>(cx);1579 let owner = path_param::<Owner>(cx);
1359 let name = path_param::<Repo>(cx);1580 let name = path_param::<Repo>(cx);
1360 let ctx = load_repo(cx, owner, name).await?;1581 let ctx = load_repo(cx, owner, name).await?;
@@ -1549,6 +1770,7 @@ async fn runs_split(cx: &Cx, number: Option<&str>, job: Option<&str>) -> Result<
1549 lang,1770 lang,
1550 now,1771 now,
1551 job,1772 job,
1773+ step,
1552 )1774 )
1553 .await?,1775 .await?,
1554 )1776 )
@@ -1623,9 +1845,29 @@ async fn run_detail(
1623 lang: Lang,1845 lang: Lang,
1624 now: i64,1846 now: i64,
1625 wanted: Option<&str>,1847 wanted: Option<&str>,
1848+ wanted_step: Option<i64>,
1626 ) -> Result<RunDetail> {1849 ) -> Result<RunDetail> {
1627- let jobs = timings_of(state, &run.id, runners, lang).await?;1850+ let mut jobs = timings_of(state, &run.id, runners, lang).await?;
1628 let picked = pick_job(&jobs, wanted);1851 let picked = pick_job(&jobs, wanted);
1852+ let mut steps_of: HashMap<String, Vec<JobStep>> = HashMap::new();
1853+ for step in state.store.steps_for_run(&run.id).await? {
1854+ steps_of.entry(step.job_id.clone()).or_default().push(step);
1855+ }
1856+ for job in jobs.iter_mut() {
1857+ let spans = steps_of
1858+ .get(&job.id)
1859+ .map_or_else(Vec::new, |steps| step_spans(steps, job.state));
1860+ job.steps = spans;
1861+ }
1862+ // A running step's expected time is judged from the samples of the run's branch.
1863+ let step_samples = if run.state == RunState::Running {
1864+ state
1865+ .store
1866+ .recent_step_samples(&run.repo_id, std::slice::from_ref(&run.git_ref))
1867+ .await?
1868+ } else {
1869+ Vec::new()
1870+ };
1629 let est = if run.state == RunState::Running {1871 let est = if run.state == RunState::Running {
1630 let samples = state1872 let samples = state
1631 .store1873 .store
@@ -1635,8 +1877,8 @@ async fn run_detail(
1635 } else {1877 } else {
1636 None1878 None
1637 };1879 };
1638- let gantt =1880+ let gantt = (!jobs.is_empty())
1639- (!jobs.is_empty()).then(|| gantt(&jobs, origin_of(run, now), run_end(run, now), now, lang));1881+ .then(|| gantt(&jobs, origin_of(run, now), run_end(run, now), now, lang, picked));
1640 let writer = header.writer_csrf.is_some();1882 let writer = header.writer_csrf.is_some();
1641 let rerunnable = writer && header.reachable;1883 let rerunnable = writer && header.reachable;
1642 let mut lines = Vec::with_capacity(jobs.len());1884 let mut lines = Vec::with_capacity(jobs.len());
@@ -1655,6 +1897,17 @@ async fn run_detail(
1655 });1897 });
1656 }1898 }
1657 let tail = log_last_lines(&log_path(&state.config.data_dir, &job.id)).await;1899 let tail = log_last_lines(&log_path(&state.config.data_dir, &job.id)).await;
1900+ let pick = format!("{}?job={}", run_href(title, run.number), job.id);
1901+ let (steps, step_bar) = job_steps(
1902+ job,
1903+ steps_of.get(&job.id).map(Vec::as_slice).unwrap_or_default(),
1904+ &step_samples,
1905+ run,
1906+ &pick,
1907+ wanted_step,
1908+ now,
1909+ lang,
1910+ );
1658 let preview = match last_line(&tail) {1911 let preview = match last_line(&tail) {
1659 Some(line) => line.to_owned(),1912 Some(line) => line.to_owned(),
1660 None if job.state == JobState::Queued && !job.message.is_empty() => job.message.clone(),1913 None if job.state == JobState::Queued && !job.message.is_empty() => job.message.clone(),
@@ -1672,7 +1925,13 @@ async fn run_detail(
1672 lines.push(JobLine {1925 lines.push(JobLine {
1673 id: job.id.clone(),1926 id: job.id.clone(),
1674 selected: picked == Some(index),1927 selected: picked == Some(index),
1675- pick: format!("{}?job={}", run_href(title, run.number), job.id),1928+ steps: if picked == Some(index) {
1929+ steps
1930+ } else {
1931+ Vec::new()
1932+ },
1933+ step_bar,
1934+ pick,
1676 expanded: !tail.is_empty() && starts_expanded(job.state, jobs.len()),1935 expanded: !tail.is_empty() && starts_expanded(job.state, jobs.len()),
1677 preview,1936 preview,
1678 tail: tail.join("\n"),1937 tail: tail.join("\n"),
@@ -1697,12 +1956,26 @@ async fn run_detail(
1697 let log = match picked {1956 let log = match picked {
1698 Some(index) => {1957 Some(index) => {
1699 let job = &jobs[index];1958 let job = &jobs[index];
1700- let Tail {1959+ let path = log_path(&state.config.data_dir, &job.id);
1701- text,1960+ // A step the URL names opens at its own line in the log, not at the job's end.
1702- truncated,1961+ let step = wanted_step
1703- offset,1962+ .and_then(|seq| steps_of.get(&job.id)?.iter().find(|step| step.seq == seq))
1704- first_line,1963+ .filter(|_| job.log_bytes != 0);
1705- } = log_tail_of(&log_path(&state.config.data_dir, &job.id), RUN_LOG_BYTES).await?;1964+ let (
1965+ Tail {
1966+ text,
1967+ truncated,
1968+ offset,
1969+ first_line,
1970+ },
1971+ at_step,
1972+ ) = match step {
1973+ Some(step) => {
1974+ let from = u64::try_from(step.log_offset).unwrap_or(0);
1975+ (log_from(&path, from, RUN_LOG_BYTES).await?, true)
1976+ }
1977+ None => (log_tail_of(&path, RUN_LOG_BYTES).await?, false),
1978+ };
1706 let href = job_href(title, &job.id);1979 let href = job_href(title, &job.id);
1707 Some(JobLog {1980 Some(JobLog {
1708 log_href: format!("{href}/log.txt"),1981 log_href: format!("{href}/log.txt"),
@@ -1718,6 +1991,7 @@ async fn run_detail(
1718 truncated,1991 truncated,
1719 offset: offset.to_string(),1992 offset: offset.to_string(),
1720 first_line: first_line.to_string(),1993 first_line: first_line.to_string(),
1994+ at_step,
1721 })1995 })
1722 }1996 }
1723 None => None,1997 None => None,
@@ -1807,6 +2081,11 @@ fn job_from_query(cx: &Cx) -> Option<String> {
1807 query_value(cx, "job")2081 query_value(cx, "job")
1808 }2082 }
1809 2083
2084+/// The step number `?step=` names, if the URL has a valid one.
2085+fn step_from_query(cx: &Cx) -> Option<i64> {
2086+ query_value(cx, "step")?.parse().ok()
2087+}
2088+
1810 /// The value of one query parameter, if the URL has it.2089 /// The value of one query parameter, if the URL has it.
1811 fn query_value(cx: &Cx, key: &str) -> Option<String> {2090 fn query_value(cx: &Cx, key: &str) -> Option<String> {
1812 let query = uri(cx).query()?;2091 let query = uri(cx).query()?;
@@ -2159,8 +2438,38 @@ async fn run_jobs(lang: Lang, run: &RunDetail) -> Result<impl View> {
2159 } else {2438 } else {
2160 <span class="ci-tl-dur" data-since=(job.since.as_deref())>(job.duration.as_str())</span>2439 <span class="ci-tl-dur" data-since=(job.since.as_deref())>(job.duration.as_str())</span>
2161 }2440 }
2441+ if !job.step_bar.is_empty() {
2442+ <svg class="ci-tl-stepbar" viewBox="0 0 1000 3" preserveAspectRatio="none" aria-hidden="true" focusable="false">
2443+ for r in job.step_bar.iter() {
2444+ <rect class=(r.class.as_str()) x=(r.x.as_str()) y=(r.y.as_str()) width=(r.w.as_str()) height=(r.h.as_str())/>
2445+ }
2446+ </svg>
2447+ }
2162 </a>2448 </a>
2163 </li>2449 </li>
2450+ for step in job.steps.iter() {
2451+ <li data-kb-row="">
2452+ if let Some(href) = step.href.as_ref() {
2453+ <a class=(if job.sub { "ci-tl-step ci-tl-step-sub" } else { "ci-tl-step" }) href=(href.as_str()) aria-current=(if step.selected { "true" } else { "false" })>
2454+ <span class=(format!("ci-tl-stepmark {}", step.mark))></span>
2455+ <span class="ci-tl-stepname">(step.name.as_str())</span>
2456+ <span class="ci-tl-dur" data-since=(step.since.as_deref())>(step.duration.as_str())</span>
2457+ if let Some(expected) = step.expected.as_ref() {
2458+ <span class="ci-tl-stepexp">(expected.as_str())</span>
2459+ }
2460+ </a>
2461+ } else {
2462+ <div class=(if job.sub { "ci-tl-step ci-tl-step-sub" } else { "ci-tl-step" })>
2463+ <span class=(format!("ci-tl-stepmark {}", step.mark))></span>
2464+ <span class="ci-tl-stepname">(step.name.as_str())</span>
2465+ <span class="ci-tl-dur" data-since=(step.since.as_deref())>(step.duration.as_str())</span>
2466+ if let Some(expected) = step.expected.as_ref() {
2467+ <span class="ci-tl-stepexp">(expected.as_str())</span>
2468+ }
2469+ </div>
2470+ }
2471+ </li>
2472+ }
2164 }2473 }
2165 </ul>2474 </ul>
2166 }2475 }
@@ -2234,7 +2543,8 @@ async fn run_log(lang: Lang, run: &RunDetail, timeline: bool) -> Result<impl Vie
2234 </ul>2543 </ul>
2235 </section>2544 </section>
2236 }2545 }
2237- if let Some(fail) = run.failing.clone() {2546+ // A reader who picked a step came for that step: the failure's box would leave it no room.
2547+ if let Some(fail) = run.failing.clone().filter(|_| !run.log.as_ref().is_some_and(|log| log.at_step)) {
2238 fail_first_block(lang: lang, fail: fail)2548 fail_first_block(lang: lang, fail: fail)
2239 }2549 }
2240 if let Some(log) = run.log.as_ref() {2550 if let Some(log) = run.log.as_ref() {
@@ -2244,7 +2554,7 @@ async fn run_log(lang: Lang, run: &RunDetail, timeline: bool) -> Result<impl Vie
2244 " " <a href=(log.log_href.as_str())>(crate::pages::passkeys::s(lang, "Full log", "Tam günlük"))</a>2554 " " <a href=(log.log_href.as_str())>(crate::pages::passkeys::s(lang, "Full log", "Tam günlük"))</a>
2245 </p>2555 </p>
2246 }2556 }
2247- <pre class="ci-log ci-tl-code" data-empty=(crate::pages::passkeys::s(lang, "No output yet.", "Henüz çıktı yok.")) data-live=(log.live.as_deref()) data-live-log="true" data-offset=(log.offset.as_str()) data-first=(log.first_line.as_str())>(log.text.as_str())</pre>2557+ <pre class="ci-log ci-tl-code" data-empty=(crate::pages::passkeys::s(lang, "No output yet.", "Henüz çıktı yok.")) data-live=(log.live.as_deref()) data-live-log="true" data-offset=(log.offset.as_str()) data-first=(log.first_line.as_str()) data-log-start=(log.at_step.then_some("true"))>(log.text.as_str())</pre>
2248 } else {2558 } else {
2249 <p class="muted ci-tl-pad">(g::t(lang, K::NoJobs))</p>2559 <p class="muted ci-tl-pad">(g::t(lang, K::NoJobs))</p>
2250 }2560 }
@@ -2321,7 +2631,7 @@ async fn runs_list_page(cx: &Cx) -> Result<impl View> {
2321 page_title,2631 page_title,
2322 list,2632 list,
2323 detail,2633 detail,
2324- } = runs_split(cx, None, None).await?;2634+ } = runs_split(cx, None, None, None).await?;
2325 Ok(view! {2635 Ok(view! {
2326 shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(),2636 shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(),
2327 runs_body(head: head, lang: lang, notice: notice, live: live, list: list, detail: detail))2637 runs_body(head: head, lang: lang, notice: notice, live: live, list: list, detail: detail))
@@ -2334,6 +2644,7 @@ async fn runs_list_page(cx: &Cx) -> Result<impl View> {
2334 async fn run_page(cx: &Cx) -> Result<impl View> {2644 async fn run_page(cx: &Cx) -> Result<impl View> {
2335 let number = path_param::<RunNumber>(cx).to_owned();2645 let number = path_param::<RunNumber>(cx).to_owned();
2336 let wanted = job_from_query(cx);2646 let wanted = job_from_query(cx);
2647+ let wanted_step = step_from_query(cx);
2337 let SplitPage {2648 let SplitPage {
2338 ctx,2649 ctx,
2339 head,2650 head,
@@ -2343,7 +2654,7 @@ async fn run_page(cx: &Cx) -> Result<impl View> {
2343 page_title,2654 page_title,
2344 list,2655 list,
2345 detail,2656 detail,
2346- } = runs_split(cx, Some(&number), wanted.as_deref()).await?;2657+ } = runs_split(cx, Some(&number), wanted.as_deref(), wanted_step).await?;
2347 let Some(run) = detail else {2658 let Some(run) = detail else {
2348 return Err(not_found().into());2659 return Err(not_found().into());
2349 };2660 };
@@ -2933,6 +3244,8 @@ mod tests {
2933 started,3244 started,
2934 finished,3245 finished,
2935 cancel_requested: false,3246 cancel_requested: false,
3247+ log_bytes: 1,
3248+ steps: Vec::new(),
2936 }3249 }
2937 }3250 }
2938 3251
@@ -3082,7 +3395,7 @@ mod tests {
3082 Some(4692),3395 Some(4692),
3083 );3396 );
3084 build.needs = vec!["test".to_owned()];3397 build.needs = vec!["test".to_owned()];
3085- let g = gantt(&[test, build], 0, Some(4692), 4692, Lang::En);3398+ let g = gantt(&[test, build], 0, Some(4692), 4692, Lang::En, None);
3086 assert_eq!(g.view_box, "0 0 640 104");3399 assert_eq!(g.view_box, "0 0 640 104");
3087 let bars: Vec<&Rect> = g3400 let bars: Vec<&Rect> = g
3088 .rects3401 .rects
@@ -3121,7 +3434,7 @@ mod tests {
3121 let mut build = timing("build", JobState::Success, Some(900), Some(900), Some(1200));3434 let mut build = timing("build", JobState::Success, Some(900), Some(900), Some(1200));
3122 build.needs = vec!["test".to_owned()];3435 build.needs = vec!["test".to_owned()];
3123 let test = timing("test", JobState::Failure, Some(0), Some(0), Some(600));3436 let test = timing("test", JobState::Failure, Some(0), Some(0), Some(600));
3124- let g = gantt(&[build, test], 0, Some(1200), 1200, Lang::En);3437+ let g = gantt(&[build, test], 0, Some(1200), 1200, Lang::En, None);
3125 let link = &g.links[0];3438 let link = &g.links[0];
3126 assert!(link.hot, "a failed need lights its connector");3439 assert!(link.hot, "a failed need lights its connector");
3127 assert_eq!(link.rel, "j1 j0");3440 assert_eq!(link.rel, "j1 j0");
@@ -3137,7 +3450,7 @@ mod tests {
3137 build.needs = vec!["test".to_owned()];3450 build.needs = vec!["test".to_owned()];
3138 let mut lint = timing("lint", JobState::Skipped, None, None, None);3451 let mut lint = timing("lint", JobState::Skipped, None, None, None);
3139 lint.needs = vec!["build".to_owned()];3452 lint.needs = vec!["build".to_owned()];
3140- let g = gantt(&[test, build, lint], 0, Some(30), 30, Lang::En);3453+ let g = gantt(&[test, build, lint], 0, Some(30), 30, Lang::En, None);
3141 // Only build has a need with an end; the connector rides the moving edge.3454 // Only build has a need with an end; the connector rides the moving edge.
3142 assert_eq!(g.links.len(), 1);3455 assert_eq!(g.links.len(), 1);
3143 let link = &g.links[0];3456 let link = &g.links[0];
@@ -3151,7 +3464,7 @@ mod tests {
3151 let broken = timing("broken", JobState::Failure, Some(0), Some(0), Some(30));3464 let broken = timing("broken", JobState::Failure, Some(0), Some(0), Some(30));
3152 let mut skipme = timing("skipme", JobState::Skipped, None, None, None);3465 let mut skipme = timing("skipme", JobState::Skipped, None, None, None);
3153 skipme.needs = vec!["broken".to_owned()];3466 skipme.needs = vec!["broken".to_owned()];
3154- let g = gantt(&[broken, skipme], 0, Some(30), 30, Lang::En);3467+ let g = gantt(&[broken, skipme], 0, Some(30), 30, Lang::En, None);
3155 let part = &g.links[0].parts[0];3468 let part = &g.links[0].parts[0];
3156 // Out of broken's end (365), down onto the top edge of skipme's outline.3469 // Out of broken's end (365), down onto the top edge of skipme's outline.
3157 assert_eq!(part.x, 365);3470 assert_eq!(part.x, 365);
@@ -3162,7 +3475,7 @@ mod tests {
3162 #[test]3475 #[test]
3163 fn a_queued_job_shows_its_lead_in_before_it_starts() {3476 fn a_queued_job_shows_its_lead_in_before_it_starts() {
3164 let test = timing("test", JobState::Success, Some(0), Some(4), Some(10));3477 let test = timing("test", JobState::Success, Some(0), Some(4), Some(10));
3165- let g = gantt(&[test], 0, Some(10), 10, Lang::En);3478+ let g = gantt(&[test], 0, Some(10), 10, Lang::En, None);
3166 let lead = g3479 let lead = g
3167 .rects3480 .rects
3168 .iter()3481 .iter()
docs/ci.mdmodified+22 -0
@@ -290,6 +290,28 @@ A line that is exactly `::group::name` starts a collapsible section and `::endgr
290 themselves are not shown. Streaming keeps working while the job runs. The page shows the last 512 KiB; the290 themselves are not shown. Streaming keeps working while the job runs. The page shows the last 512 KiB; the
291 full log is at `log.txt`.291 full log is at `log.txt`.
292 292
293+A top-level group is a step of the job. Forge stores its name, when it started and ended, and where it
294+begins in the log. It estimates the step's duration the way it estimates the job's. Nested groups stay
295+plain sections.
296+
297+A step is closed by `::endgroup::`. A step still open when the job ends takes the job's result, so a
298+failing command under `sh -e` leaves its step failed.
299+
300+A job has at most 32 steps, and names are cut to 80 characters. Any program in the job can print these
301+lines, so a stray `::endgroup::` closes a step early.
302+
303+Print `exec 2>&1` first. The runner reads stdout and stderr separately, so without it a marker on stdout
304+can overtake the last stderr lines. For example:
305+
306+```sh
307+exec 2>&1
308+echo "::group::Unit tests"
309+cargo test --workspace
310+echo "::endgroup::"
311+```
312+
313+Step times come from when the log arrives, so they are good to about a second.
314+
293 ### Releases315 ### Releases
294 316
295 A `[release]` table publishes a release from a tag run. It needs at least one glob in `[on] tags`.317 A `[release]` table publishes a release from a tag run. It needs at least one glob in `[on] tags`.
style/_lang_ci.scssmodified+17 -0
@@ -86,6 +86,23 @@
86 grid-template-columns: minmax(0, 1fr);86 grid-template-columns: minmax(0, 1fr);
87 }87 }
88 88
89+ // The page scrolls here. A pane share of a fixed height left a run with a long title no room at all.
90+ .ci-split.fit-pane {
91+ height: auto;
92+ overflow: visible;
93+ }
94+
95+ .ci-split > .ci-detail,
96+ .ci-split > .ci-run {
97+ height: auto;
98+ overflow: visible;
99+ }
100+
101+ .ci-split > .ci-detail > .ci-tl-main,
102+ .ci-split > .ci-run > .ci-tl-main {
103+ flex: none;
104+ }
105+
89 .ci-split:has(> .ci-run) > .ci-side {106 .ci-split:has(> .ci-run) > .ci-side {
90 display: none;107 display: none;
91 }108 }
style/_shell.scssmodified+3 -1
@@ -253,10 +253,12 @@
253 }253 }
254 }254 }
255 255
256+// The shortcut sits right after the hint: at the far end of the bar it read as the key for the link
257+// beside it.
256 .pathbar-edit {258 .pathbar-edit {
257 display: flex;259 display: flex;
258 align-items: center;260 align-items: center;
259- justify-content: space-between;261+ justify-content: flex-start;
260 gap: 8px;262 gap: 8px;
261 flex: 1 1 0;263 flex: 1 1 0;
262 height: 100%;264 height: 100%;
style/_timeline_ci.scssmodified+122 -1
@@ -225,6 +225,7 @@
225 }225 }
226 226
227 .ci-tl-job {227 .ci-tl-job {
228+ position: relative;
228 display: flex;229 display: flex;
229 align-items: center;230 align-items: center;
230 gap: 10px;231 gap: 10px;
@@ -257,6 +258,115 @@
257 padding-left: 28px;258 padding-left: 28px;
258 }259 }
259 260
261+// The job's bar: a 3 px band along the bottom of its row, one segment per step. It sits over the row's
262+// hairline and takes no room, so the row keeps its height.
263+.ci-tl-stepbar {
264+ position: absolute;
265+ left: 0;
266+ bottom: 0;
267+ display: block;
268+ width: 100%;
269+ height: 3px;
270+ pointer-events: none;
271+
272+ .ci-sbar-pass {
273+ fill: var(--border-strong);
274+ }
275+
276+ .ci-sbar-fail {
277+ fill: var(--bad);
278+ }
279+
280+ .ci-sbar-off,
281+ .ci-sbar-track {
282+ fill: var(--border);
283+ }
284+
285+ .ci-sbar-run {
286+ fill: var(--accent);
287+ }
288+}
289+
290+// A step under the selected job: a 30 px line with a 6 px mark, its name and its duration at the right.
291+// Indented past the job's dot, one level more for a matrix combination. The selected step has an
292+// accent edge on the left, and a failed step's name reads in --text.
293+.ci-tl-step {
294+ display: flex;
295+ align-items: center;
296+ gap: 8px;
297+ height: 30px;
298+ min-width: 0;
299+ padding: 0 14px 0 34px;
300+ box-shadow: inset 0 -1px var(--border);
301+ color: var(--text-2);
302+ text-decoration: none;
303+ font-size: 12px;
304+
305+ &.ci-tl-step-sub {
306+ padding-left: 48px;
307+ }
308+
309+ &:hover {
310+ background: var(--surface-2);
311+ text-decoration: none;
312+ }
313+
314+ &[aria-current="true"] {
315+ color: var(--text);
316+ background: var(--surface-2);
317+ box-shadow: inset 2px 0 var(--accent), inset 0 -1px var(--border);
318+ }
319+
320+ .ci-tl-dur {
321+ margin-left: auto;
322+ flex: none;
323+ font-family: var(--mono);
324+ font-size: 11px;
325+ color: var(--text-2);
326+ }
327+}
328+
329+.ci-tl-stepmark {
330+ flex: none;
331+ width: 6px;
332+ height: 6px;
333+ border-radius: 50%;
334+ background: var(--muted);
335+
336+ &.ci-st-run {
337+ background: var(--accent);
338+ }
339+
340+ &.ci-st-fail {
341+ background: var(--bad);
342+ }
343+
344+ &.ci-st-off {
345+ background: transparent;
346+ border: 1px solid var(--muted);
347+ box-sizing: border-box;
348+ }
349+}
350+
351+.ci-tl-stepname {
352+ flex: 1 1 auto;
353+ min-width: 0;
354+ overflow: hidden;
355+ text-overflow: ellipsis;
356+ white-space: nowrap;
357+}
358+
359+.ci-st-fail ~ .ci-tl-stepname {
360+ color: var(--text);
361+}
362+
363+.ci-tl-stepexp {
364+ flex: none;
365+ font-family: var(--mono);
366+ font-size: 11px;
367+ color: var(--muted);
368+}
369+
260 .ci-tl-name {370 .ci-tl-name {
261 flex: 1 1 auto;371 flex: 1 1 auto;
262 min-width: 0;372 min-width: 0;
@@ -406,6 +516,11 @@
406 }516 }
407 517
408 // The code area: --bg, mono 12.5 px on a 1.7 line, numbers right aligned in their own column.518 // The code area: --bg, mono 12.5 px on a 1.7 line, numbers right aligned in their own column.
519+// A group's name sticks to the pane's edge, not inside its padding, or lines show above it.
520+.ci-tl-code details.lg > summary {
521+ top: -14px;
522+}
523+
409 .ci-tl-code {524 .ci-tl-code {
410 flex: 1 1 0;525 flex: 1 1 0;
411 min-height: 0;526 min-height: 0;
@@ -526,7 +641,13 @@
526 overflow: visible;641 overflow: visible;
527 }642 }
528 643
529- .ci-tl-code {644+ // These panels share out a fixed height on a wide window; here there is none to share.
645+ .ci-tl-panel {
646+ flex: none;
647+ }
648+
649+ .ci-tl-panel-log > .ci-log.ci-tl-code {
650+ flex: none;
530 max-height: 60vh;651 max-height: 60vh;
531 }652 }
532 653
style/main.scssmodified+30 -0
@@ -5060,7 +5060,13 @@ button.ci-mini {
5060 }5060 }
5061 }5061 }
5062 5062
5063+ // The group's name stays at the top of the log while its lines are read. It is opaque, so the lines
5064+ // scroll under it, and the code area's scroll is the one that sticks it.
5063 details.lg > summary {5065 details.lg > summary {
5066+ position: sticky;
5067+ top: 0;
5068+ z-index: 1;
5069+ background: var(--bg);
5064 cursor: pointer;5070 cursor: pointer;
5065 font-weight: 600;5071 font-weight: 600;
5066 color: var(--text);5072 color: var(--text);
@@ -6013,6 +6019,30 @@ html.js form.runner-load[data-dirty-form][data-dirty] .runner-save {
6013 }6019 }
6014 }6020 }
6015 6021
6022+// A step's box under the selected job: the job colours, at a lower opacity so the job's own bar leads.
6023+.ci-gstep {
6024+ rx: 3px;
6025+ opacity: 0.7;
6026+
6027+ &.ci-ok {
6028+ fill: var(--ok);
6029+ }
6030+
6031+ &.ci-bad {
6032+ fill: var(--bad);
6033+ }
6034+
6035+ &.ci-run {
6036+ fill: var(--heat-3);
6037+ }
6038+
6039+ &.ci-muted {
6040+ fill: var(--surface-2);
6041+ stroke: var(--border-strong);
6042+ stroke-width: 1;
6043+ }
6044+}
6045+
6016 .ci-glead {6046 .ci-glead {
6017 fill: url(#ci-hatch);6047 fill: url(#ci-hatch);
6018 }6048 }