diff --git a/Cargo.lock b/Cargo.lock index ee095b4..02668d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -473,7 +473,7 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "logos-devnet" -version = "0.9.3" +version = "0.9.4" dependencies = [ "anyhow", "bs58", diff --git a/Cargo.toml b/Cargo.toml index 4487160..8e5d997 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "logos-devnet" -version = "0.9.3" +version = "0.9.4" edition = "2024" rust-version = "1.89" description = "A local LEZ chain for Logos development: one command to start it, fund accounts and deploy programs" diff --git a/README.md b/README.md index 748f9c4..7184e1e 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ cargo install --locked logos-devnet Or take a binary from the [latest release](https://github.com/drptbl/logos-devnet/releases/latest), built for macOS (`aarch64-apple-darwin`, `x86_64-apple-darwin`) and Linux (`x86_64-unknown-linux-musl`, `aarch64-unknown-linux-musl`, static, so any distribution), and check it against its `.sha256`: ```bash -v=v0.9.3 t=aarch64-apple-darwin +v=v0.9.4 t=aarch64-apple-darwin curl -fsSL --remote-name-all https://github.com/drptbl/logos-devnet/releases/download/$v/logos-devnet-$v-$t.tar.gz{,.sha256} shasum -a 256 -c logos-devnet-$v-$t.tar.gz.sha256 \ && tar -xzf logos-devnet-$v-$t.tar.gz \ @@ -101,7 +101,7 @@ modules = ["chat_module"] # or "chat_module@0.3.0" for that version A program can come from a release instead of a path: `up` downloads its `url` once, with `curl`, into `~/.logos-devnet/downloads`, which every home shares, and deploys it only if its SHA-256 is the `sha256` given (as `shasum -a 256` prints it). -`up` deploys missing programs, makes and funds missing accounts and sessions, and changes nothing the second time (0.6 s). A `mutable` program whose binary changed is updated in place, with the same id. An immutable one keeps its old build, and `up` and `deploy` fail saying so, so tests don't run against it: `reset` deploys the new build. A module added to a session's `modules` is installed into it. Modules come from the catalog at its latest version, `lez_core` at `0.5.1`, unless the file names one: `chat_module@0.3.0`. A session keeps the versions it was made with, so `up` refuses another version for an existing one: `session rm` it, and `up` makes it again. A pin on what it installed unpinned is checked against the version its daemon reports, and recorded when it matches. `up` checks the whole file before it touches the devnet. A stopped sequencer replays its chain's history before it serves, which takes a while on a long chain (166k blocks took about 15 minutes): `up` waits as long as its log grows, up to an hour, and says so. +`up` deploys missing programs, makes and funds missing accounts and sessions, and changes nothing the second time (0.6 s). A `mutable` program whose binary changed is updated in place, with the same id. An immutable one keeps its old build, and `up` and `deploy` fail saying so, so tests don't run against it: `reset` deploys the new build. A module added to a session's `modules` is installed into it. Modules come from the catalog at its latest version, `lez_core` at `0.5.1`, unless the file names one: `chat_module@0.3.0`. A session keeps the versions it was made with, so `up` refuses another version for an existing one: `session rm` it, and `up` makes it again. A pin on what it installed unpinned is checked against the version its daemon reports, and recorded when it matches. `up` checks the whole file before it touches the devnet. A stopped sequencer replays its chain's history before it serves, which takes a while on a long chain (186k blocks took about 34 minutes): `up` waits as long as its log shows something new, up to 4 hours, and says so. A sequencer that only repeats lines it logged lately for 3 minutes, e.g. retrying an error, counts as stuck. Projects share one devnet, `~/.logos-devnet` on port 3040, unless the file sets `home`, e.g. `home = ".logos-devnet"`, for a devnet of the project's own. Downloads stay shared. Give it `[devnet] port = 0` too: it takes a free port on the first `up` and keeps it, so it runs next to other devnets, and `logos-devnet env` shows it. With a fixed `port` in the file, `--port` applies for that run, and the next `up` goes back to the file's port. With `port = 0`, `--port` is remembered. On a shared devnet, a `[devnet]` section that disagrees with the running chain is refused rather than restarting the chain under the other projects: `down` and `up` apply it, or `reset` for `lez` and `dev_mode`, which only a new chain takes. A `reset` there funds every project's account groups again, and each project's next `up` deploys its programs on the new chain. @@ -279,7 +279,7 @@ With `--json`, a command prints one JSON document and nothing else on stdout. No The repo is a GitHub Action. On a Linux runner it installs `logos-devnet`, starts the devnet from your project file and exports the env into the job: ```yaml -- uses: drptbl/logos-devnet@v0.9.3 +- uses: drptbl/logos-devnet@v0.9.4 with: args: --max-txs-per-block 100 # optional, more options for up - run: cargo test # LOGOS_DEVNET_SEQUENCER, LOGOS_PROGRAM_*, LOGOS_DEVNET_ACCOUNTS_*, RISC0_DEV_MODE are set diff --git a/examples/github-actions/devnet.yml b/examples/github-actions/devnet.yml index 35617d3..3d7c6d9 100644 --- a/examples/github-actions/devnet.yml +++ b/examples/github-actions/devnet.yml @@ -21,7 +21,7 @@ jobs: # Installs logos-devnet, starts the devnet from logos-devnet.toml, and exports its env # (LOGOS_DEVNET_SEQUENCER, LOGOS_PROGRAM_*, LOGOS_DEVNET_ACCOUNTS_*, RISC0_DEV_MODE). - id: devnet - uses: drptbl/logos-devnet@v0.9.3 + uses: drptbl/logos-devnet@v0.9.4 - run: cargo test - name: The devnet's logs if: failure() diff --git a/skills/logos-devnet/SKILL.md b/skills/logos-devnet/SKILL.md index 7cb8579..7051586 100644 --- a/skills/logos-devnet/SKILL.md +++ b/skills/logos-devnet/SKILL.md @@ -82,7 +82,7 @@ Each refusal changes nothing. `up` prefixes a program's refusal with `program , not ` or `its daemon has no package` | A session keeps the versions it was made with: `session rm `, then `up` makes it again. | | `not a RISC Zero program binary` | Deploy the guest's `.bin` from `cargo risczero build`, not its ELF. | | `no Docker daemon answers` | Start Docker (OrbStack, Docker Desktop or Colima). | -| `no block, and nothing in the sequencer's log` / `the sequencer stopped while starting` | Read `logos-devnet logs`. A long chain loading is no error: `up` waits as long as the log grows. | +| `no block, and nothing new in the sequencer's log` / `the sequencer stopped while starting` | Read `logos-devnet logs`. A long chain loading is no error: `up` waits as long as the log shows something new. | ## Debugging diff --git a/src/devnet.rs b/src/devnet.rs index d81b28f..3dc41fa 100644 --- a/src/devnet.rs +++ b/src/devnet.rs @@ -23,7 +23,7 @@ use crate::report::{ Sessions, Status, WalletConfig, }; use crate::rpc::Rpc; -use crate::runtime::{BATCH_CHUNK, Docker, Native, Runtime, WalletArg}; +use crate::runtime::{BATCH_CHUNK, Docker, Native, Runtime, WalletArg, log_line_text}; use crate::session::{self, Session, SessionInfo}; /// The faucet's genesis balance in lepta: enough that a devnet never runs dry. @@ -32,14 +32,17 @@ const FAUCET_BALANCE: u64 = 1_000_000_000_000_000_000; const FAUCET_LABEL: &str = "faucet"; /// What `fund`, sessions and account groups send when no amount is given. pub const DEFAULT_FUND: u64 = 10_000_000_000; -/// How `up` waits for a starting sequencer's first block. A long chain loads for minutes first -/// (166k blocks took 15), logging as it goes, so `up` waits as long as the log grows. +/// How `up` waits for a starting sequencer's first block. A long chain replays first, logging +/// a different line for each block (186k blocks took 34 min), so `up` waits as long as the log +/// shows something new. A sequencer stuck repeating one line counts as quiet. const READY_WAIT: ReadyWait = ReadyWait { quiet: Duration::from_secs(180), - limit: Duration::from_secs(3600), + limit: Duration::from_secs(4 * 3600), poll: Duration::from_millis(500), log_every: Duration::from_secs(10), }; +/// How many of the sequencer's recent distinct last lines `up` remembers while it waits. +const RECENT_LINES: usize = 32; /// When `up` says it's still waiting, and then how often. const LOADING_NOTICE: Duration = Duration::from_secs(30); const LOADING_NOTICE_EVERY: Duration = Duration::from_secs(120); @@ -871,7 +874,7 @@ impl Devnet { &Startup { serves: &|| rpc.last_block_id().is_ok_and(|head| head >= 1), running: &|| self.runtime.running(), - log_mark: &|| self.runtime.log_mark(), + log_mark: &|| self.runtime.last_log_line().map(|l| log_line_text(&l)), }, &READY_WAIT, ) @@ -1837,9 +1840,9 @@ fn labelled(list: &str, label: &str) -> Option { /// How long `wait_for_blocks` waits. struct ReadyWait { - /// The longest the sequencer's log may go without a new line. + /// The longest the sequencer's log may go without a line it didn't just write. quiet: Duration, - /// The longest it waits in all, however busy the log. + /// The longest it waits in all, however busy the log: a last resort, under CI's 6 h. limit: Duration, /// How often it asks for a block. poll: Duration, @@ -1853,16 +1856,18 @@ struct Startup<'a> { serves: &'a dyn Fn() -> bool, /// Whether it still runs. running: &'a dyn Fn() -> bool, - /// Something that changes whenever it writes to its log, e.g. its last line. + /// Its last log line, without the time, or `None` when it can't be read. log_mark: &'a dyn Fn() -> Option, } -/// Waits until the sequencer serves a block. It may take as long as it keeps writing to its -/// log, up to `wait.limit`: it fails after `wait.quiet` without a new line, or when the +/// Waits until the sequencer serves a block. It may take as long as its log shows something new, +/// up to `wait.limit`: it fails after `wait.quiet` with the same last line, or when the /// sequencer stops. A log that can't be read counts as busy, since not knowing isn't quiet. fn wait_for_blocks(startup: &Startup, wait: &ReadyWait) -> Result<()> { let start = Instant::now(); - let mut mark = (startup.log_mark)(); + // Recent distinct last lines: one among them is no news, so a sequencer going round a + // short loop, e.g. an error and a retry, counts as quiet. + let mut recent: std::collections::VecDeque = (startup.log_mark)().into_iter().collect(); let mut last_change = start; let mut last_check = start; let mut next_notice = LOADING_NOTICE; @@ -1875,32 +1880,39 @@ fn wait_for_blocks(startup: &Startup, wait: &ReadyWait) -> Result<()> { } if last_check.elapsed() >= wait.log_every { last_check = Instant::now(); - let now = (startup.log_mark)(); - if now.is_none() || now != mark { - mark = now; - last_change = last_check; + match (startup.log_mark)() { + // Not knowing isn't quiet. + None => last_change = last_check, + Some(line) if !recent.contains(&line) => { + if recent.len() == RECENT_LINES { + recent.pop_front(); + } + recent.push_back(line); + last_change = last_check; + } + Some(_) => {} } } if last_change.elapsed() > wait.quiet { bail!( - "no block, and nothing in the sequencer's log for {} s. See `logos-devnet logs`", + "no block, and nothing new in the sequencer's log for {} s. See `logos-devnet logs`", wait.quiet.as_secs() ); } let waited = start.elapsed(); if waited > wait.limit { bail!( - "no block within {} min, though the sequencer keeps logging. See `logos-devnet \ - logs`", - wait.limit.as_secs() / 60 + "no block within {}, though the sequencer keeps logging. See `logos-devnet logs`", + duration_text(wait.limit) ); } if waited >= next_notice { eprintln!( "No block yet after {}: a long chain takes a while to load. Waiting as long as \ - the sequencer keeps logging, up to {} min; `logos-devnet logs -f` shows it.", + the sequencer's log shows something new, up to {}; `logos-devnet logs -f` shows \ + it.", duration_text(waited), - wait.limit.as_secs() / 60 + duration_text(wait.limit) ); next_notice += LOADING_NOTICE_EVERY; } @@ -1908,11 +1920,12 @@ fn wait_for_blocks(startup: &Startup, wait: &ReadyWait) -> Result<()> { } } -/// `30 s`, or `4 min` from two minutes on. +/// `30 s`, `4 min` from two minutes on, or `4 h` from two hours on. fn duration_text(d: Duration) -> String { match d.as_secs() { s if s < 120 => format!("{s} s"), - s => format!("{} min", s / 60), + s if s < 7200 => format!("{} min", s / 60), + s => format!("{} h", s / 3600), } } @@ -2124,6 +2137,8 @@ mod tests { enum Log { Busy, Quiet, + /// Two lines in turn, as a sequencer retrying an error logs them. + Looping, Unreadable, } @@ -2135,6 +2150,10 @@ mod tests { let log_mark = move || match log { Log::Busy => Some(format!("{:?}", start.elapsed())), Log::Quiet => Some("the same line".to_owned()), + Log::Looping => Some( + ["error: no peer", "retrying in 5s"][start.elapsed().as_millis() as usize / 10 % 2] + .to_owned(), + ), Log::Unreadable => None, }; wait_for_blocks( @@ -2154,15 +2173,27 @@ mod tests { #[test] fn waits_while_a_long_chain_loads() { - // Replaying 166k blocks took 15 min, far past the quiet limit, the log busy throughout. + // Replaying 186k blocks took 34 min, far past the quiet limit, the log busy throughout. starting_for(Duration::from_millis(600), Log::Busy, None).unwrap(); } #[test] fn gives_up_on_a_sequencer_that_went_quiet() { let err = starting_for(Duration::from_secs(60), Log::Quiet, None).unwrap_err(); + // A sequencer stuck repeating one line, e.g. retrying an error, never got further. + assert!( + err.to_string() + .contains("nothing new in the sequencer's log"), + "{err}" + ); + } + + #[test] + fn gives_up_on_a_sequencer_going_round_in_a_loop() { + let err = starting_for(Duration::from_secs(60), Log::Looping, None).unwrap_err(); assert!( - err.to_string().contains("nothing in the sequencer's log"), + err.to_string() + .contains("nothing new in the sequencer's log"), "{err}" ); } @@ -2185,6 +2216,7 @@ mod tests { fn says_how_long_it_waited() { assert_eq!(duration_text(Duration::from_secs(30)), "30 s"); assert_eq!(duration_text(Duration::from_secs(250)), "4 min"); + assert_eq!(duration_text(Duration::from_secs(4 * 3600)), "4 h"); } #[test] diff --git a/src/fetch.rs b/src/fetch.rs index d82ffcd..1917034 100644 --- a/src/fetch.rs +++ b/src/fetch.rs @@ -144,6 +144,30 @@ pub(crate) mod tests { use std::io::{Read, Write}; use std::net::TcpListener; + /// Reads a whole HTTP request, head and body. A server that answers and closes with some + /// of it unread makes the OS reset the connection, and the client sees no answer. + pub(crate) fn read_request(stream: &mut impl Read) { + let mut seen = Vec::new(); + let mut chunk = [0u8; 4096]; + // The request's length, once its head is in: the head and a Content-Length body. + let length = |seen: &[u8]| { + let end = seen.windows(4).position(|w| w == b"\r\n\r\n")?; + let head = String::from_utf8_lossy(&seen[..end]).to_ascii_lowercase(); + let body = head + .lines() + .find_map(|l| l.strip_prefix("content-length:")) + .and_then(|n| n.trim().parse::().ok()) + .unwrap_or(0); + Some(end + 4 + body) + }; + while length(&seen).is_none_or(|wanted| seen.len() < wanted) { + match stream.read(&mut chunk) { + Ok(0) | Err(_) => return, + Ok(n) => seen.extend_from_slice(&chunk[..n]), + } + } + } + /// Serves `body` to each of `requests` requests on 127.0.0.1, with `status`. pub(crate) fn serve(status: &'static str, body: &'static [u8], requests: usize) -> String { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); @@ -151,8 +175,7 @@ pub(crate) mod tests { std::thread::spawn(move || { for stream in listener.incoming().take(requests) { let mut stream = stream.unwrap(); - let mut request = [0u8; 1024]; - let _ = stream.read(&mut request); + read_request(&mut stream); let head = format!( "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len() diff --git a/src/rpc.rs b/src/rpc.rs index 5165da3..1524b77 100644 --- a/src/rpc.rs +++ b/src/rpc.rs @@ -101,13 +101,12 @@ mod tests { /// An Rpc against a one-request server that answers `body`. fn answering(body: &'static str) -> Rpc { - use std::io::{Read, Write}; + use std::io::Write; let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); let url = format!("http://{}", listener.local_addr().unwrap()); std::thread::spawn(move || { let (mut stream, _) = listener.accept().unwrap(); - let mut request = [0u8; 4096]; - let _ = stream.read(&mut request); + crate::fetch::tests::read_request(&mut stream); let head = format!( "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len() diff --git a/src/runtime/docker.rs b/src/runtime/docker.rs index c47ebc1..32d9436 100644 --- a/src/runtime/docker.rs +++ b/src/runtime/docker.rs @@ -275,17 +275,9 @@ impl Runtime for Docker { run_attached(cmd.arg("sequencer")) } - fn log_mark(&self) -> Option { - // Its last line, with Docker's timestamp to the nanosecond, so a repeated line counts. + fn last_log_line(&self) -> Option { let mut cmd = self.compose(); - cmd.args([ - "logs", - "--tail", - "1", - "--timestamps", - "--no-log-prefix", - "sequencer", - ]); + cmd.args(["logs", "--tail", "1", "--no-log-prefix", "sequencer"]); stdout_within(&mut cmd, Duration::from_secs(10)).ok() } } diff --git a/src/runtime/mod.rs b/src/runtime/mod.rs index 3bbcb28..507f33c 100644 --- a/src/runtime/mod.rs +++ b/src/runtime/mod.rs @@ -89,9 +89,33 @@ pub trait Runtime { fn wallet_batch(&self, home: &Path, runs: &[Vec]) -> Result>; /// Prints the sequencer's log. fn logs(&self, follow: bool) -> Result<()>; - /// Something that changes whenever the sequencer writes to its log, to tell one still - /// working from one that went quiet. `None` when it can't be read. - fn log_mark(&self) -> Option; + /// The sequencer's last log line, empty while it has logged nothing, to tell one still + /// working from one that went quiet or repeats itself. `None` when it can't be read. + fn last_log_line(&self) -> Option; +} + +/// A sequencer log line without the time it starts with, `[2026-11-15T18:45:51Z INFO ...`, so +/// a line repeated later reads the same. +pub(crate) fn log_line_text(line: &str) -> String { + let line = line.trim(); + let text = line + .strip_prefix('[') + .and_then(|rest| rest.split_once(' ')) + .map_or(line, |(_, rest)| rest); + text.to_owned() +} + +/// The last non-empty line of the file at `path`, read from its end: empty when it has none. +pub(crate) fn last_line(path: &Path) -> Option { + use std::io::{Seek, SeekFrom}; + let mut file = std::fs::File::open(path).ok()?; + let len = file.metadata().ok()?.len(); + file.seek(SeekFrom::Start(len.saturating_sub(8192))).ok()?; + let mut tail = Vec::new(); + file.read_to_end(&mut tail).ok()?; + let tail = String::from_utf8_lossy(&tail); + let line = tail.lines().rev().find(|l| !l.trim().is_empty()); + Some(line.unwrap_or_default().to_owned()) } /// Runs `cmd` with stdin closed and returns its stdout. On failure the error carries both @@ -336,6 +360,33 @@ fn combined(output: &Output) -> String { mod tests { use super::*; + #[test] + fn a_log_line_without_its_time() { + let at = |t: &str| { + format!("[2026-11-15T18:45:{t}Z INFO risc0_zkvm::exec] execution time: 1.3ms") + }; + assert_eq!(log_line_text(&at("51")), log_line_text(&at("52"))); + assert_eq!( + log_line_text(&at("51")), + "INFO risc0_zkvm::exec] execution time: 1.3ms" + ); + assert_eq!(log_line_text("plain\n"), "plain"); + } + + #[test] + fn reads_the_last_line_of_a_long_log() { + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("sequencer.log"); + let mut text = "x".repeat(20_000); + text.push_str("\nfirst\nlast line\n"); + std::fs::write(&log, text).unwrap(); + assert_eq!(last_line(&log).as_deref(), Some("last line")); + assert_eq!(last_line(&dir.path().join("missing")), None); + // A sequencer that has logged nothing yet is quiet, not unknown. + std::fs::write(&log, "").unwrap(); + assert_eq!(last_line(&log).as_deref(), Some("")); + } + #[test] fn gives_up_on_a_command_that_hangs() { let started = Instant::now(); diff --git a/src/runtime/native.rs b/src/runtime/native.rs index 716f41f..84bf5e8 100644 --- a/src/runtime/native.rs +++ b/src/runtime/native.rs @@ -229,9 +229,8 @@ impl Runtime for Native { run_attached(cmd.arg(self.log_file())) } - fn log_mark(&self) -> Option { - let size = std::fs::metadata(self.log_file()).ok()?.len(); - Some(size.to_string()) + fn last_log_line(&self) -> Option { + super::last_line(&self.log_file()) } }