diff --git a/docs/architecture/core/compare-and-merge/merge.md b/docs/architecture/core/compare-and-merge/merge.md index 7838010ab8..3495df428f 100644 --- a/docs/architecture/core/compare-and-merge/merge.md +++ b/docs/architecture/core/compare-and-merge/merge.md @@ -169,7 +169,7 @@ consumer. | Part | Rule | Source | | --- | --- | --- | | Plan | Values, fresh serials and changed names as point records keyed by serial and name. | [`build.rs`](../../../../core/crates/layerfs-content/src/merge/build.rs), [`rows.rs`](../../../../core/crates/layerfs-content/src/merge/rows.rs) | -| Fresh serials | From the caller's `fresh` callback; a file value keeps its source serial only when that cannot give one serial two values. | [`build.rs`](../../../../core/crates/layerfs-content/src/merge/build.rs) | +| Fresh serials | From the caller's `fresh` callback; a file value keeps its source serial only when that cannot give one serial two values. A mounted Workspace that installs the result may still have the old serial held by its kernel (a cwd, an open descriptor): each request that names it answers ESTALE and the mount keeps serving ([kernel routes](../../engine/kernel-routes/fuse.md#requests-and-replies-request-attributesrs)). | [`build.rs`](../../../../core/crates/layerfs-content/src/merge/build.rs), [`eval.rs`](../../../../engine/crates/layerfs-workspace/src/mutation/eval.rs) | | Spill | Runs of at most 60 KiB chunks; up to 8 MiB held in memory, then the caller's `IndexedConstructionBacking` records. Without records a `Resident` store is used. | [`spill.rs`](../../../../core/crates/layerfs-content/src/merge/spill.rs) | | Result | One backed update of `into`, the same canonical producer and route as a Workspace Commit. No plan rows: `into`'s root unchanged. | [`build.rs`](../../../../core/crates/layerfs-content/src/merge/build.rs) | | Outcome | Conflicts and `.lww` decisions sorted by path; `clean()` is true when there are no conflicts. | [`entry.rs`](../../../../core/crates/layerfs-content/src/merge/entry.rs), [`types.rs`](../../../../core/crates/layerfs-content/src/merge/types.rs) | diff --git a/docs/architecture/engine/kernel-routes/fuse.md b/docs/architecture/engine/kernel-routes/fuse.md index 82e45952a4..29a18e2d34 100644 --- a/docs/architecture/engine/kernel-routes/fuse.md +++ b/docs/architecture/engine/kernel-routes/fuse.md @@ -93,6 +93,9 @@ installed a root other than the one shown, for each `Stale::Inode` or Retained(error) or panic -> failure kept, mount terminal ``` +A request that ends itself (fenced, failed base demand, stale serial) is +`Complete`, not `Retained`, so it never makes the mount terminal. + | Item | Meaning | Source | | --- | --- | --- | | `MountRequests` | Per-mount request owner: counts, retained failures, parked threads, its `Fence`; no daemon-wide dispatcher | [`requests.rs`](../../../../engine/crates/layerfs-fuse/src/dispatch/requests.rs) | @@ -109,6 +112,7 @@ reader holds its loop; two loops let one request proceed while another waits. | --- | --- | --- | | Fenced step (forced teardown) | `ENOTCONN`, counted on the fence | [`terminal.rs`](../../../../engine/crates/layerfs-fuse/src/request/terminal.rs) | | Failed base demand of this request | `EIO`; the mount keeps serving | [`terminal.rs`](../../../../engine/crates/layerfs-fuse/src/request/terminal.rs) | +| Stale serial: a LOOKUP, GETATTR, OPEN, OPENDIR, READ, READLINK or READDIR names a serial that neither a local row nor the base has, because an install dropped it while the kernel held it (a merge rebuilt that directory or file under a fresh serial, or took the other side's removal) | `ESTALE` for that request alone; nothing is retained and the mount keeps serving. Only the engine's own `Stale` answer counts (`ports::stale`): an uncertain, retained or owner failure that carries one stays retained. A name that binds an absent inode, or a count leaving its range, is still corruption and still retained | [`terminal.rs`](../../../../engine/crates/layerfs-fuse/src/request/terminal.rs), [`ports.rs`](../../../../engine/crates/layerfs-mount-ports/src/ports.rs), [`eval.rs`](../../../../engine/crates/layerfs-workspace/src/mutation/eval.rs) | | `Refusal` | `EEXIST`, `ENOENT`, `ENOTDIR`, `EISDIR`, `ENOTEMPTY`, `EPERM`, `EOPNOTSUPP`, `EINVAL`, `EMLINK`, `EFBIG` | [`attributes.rs`](../../../../engine/crates/layerfs-fuse/src/attributes.rs) | | `Declined::NoSpace`, `Contended`, `TargetTooLong` | `ENOSPC`, `EAGAIN`, `ENAMETOOLONG` | [`attributes.rs`](../../../../engine/crates/layerfs-fuse/src/attributes.rs) | | Missing LOOKUP name | Negative entry (node 0), 60 s entry TTL; every create, link, mkdir, symlink or rename through the mount replaces it | [`reply.rs`](../../../../engine/crates/layerfs-fuse/src/request/reply.rs) | diff --git a/docs/architecture/engine/overlay/README.md b/docs/architecture/engine/overlay/README.md index 5e77de8312..0143688286 100644 --- a/docs/architecture/engine/overlay/README.md +++ b/docs/architecture/engine/overlay/README.md @@ -131,7 +131,7 @@ commits or rolls back with that job's SQL through undo journals. | Map | Holds | Source | | --- | --- | --- | -| `mount`, `kernel`, `parents` | One kernel connection, `(mount, serial)` lookup counts, retained directory parents | [`open/kernel.rs`](../../../../engine/crates/layerfs-overlay/src/open/kernel.rs) | +| `mount`, `kernel`, `parents` | One kernel connection, `(mount, serial)` lookup counts, retained directory parents with the name each was recorded under (an install rewrites none; `kernel_ancestors` returns the links for the caller to check against its view) | [`open/kernel.rs`](../../../../engine/crates/layerfs-overlay/src/open/kernel.rs) | | `files`, `directories`, `cookies` | Open descriptors, open directories and published READDIR cookie pages | same, [`open/directories.rs`](../../../../engine/crates/layerfs-overlay/src/open/directories.rs) | | `reads`, `lookups`, `operations`, `captured` | Read windows, lookup references, operation owners, captured readers | [`open/kernel.rs`](../../../../engine/crates/layerfs-overlay/src/open/kernel.rs) | | `custody`, `sources`, `orphans` | Per-serial opens, lookups and readers; held `BaseSource` windows; orphans | same | diff --git a/docs/architecture/engine/workspace/operations.md b/docs/architecture/engine/workspace/operations.md index 5c7e1d8fdc..c0bf44c592 100644 --- a/docs/architecture/engine/workspace/operations.md +++ b/docs/architecture/engine/workspace/operations.md @@ -37,6 +37,7 @@ What each filesystem operation on a [Workspace](README.md) reads and publishes, | --- | --- | | A removed inode keeps a row with `nlink` 0, so serial-addressed access does not fall through to the base | [`remove.rs`](../../../../engine/crates/layerfs-workspace/src/operations/namespace/remove.rs) | | Moving a directory to another parent needs ancestry evidence: a path caller passes `destination_path`, walked from the root and verified; a kernel caller uses the connection's retained parent index | [`rename.rs`](../../../../engine/crates/layerfs-workspace/src/operations/namespace/rename.rs), [`types.rs`](../../../../engine/crates/layerfs-workspace/src/operations/types.rs) | +| The retained parent index keeps, per kernel-known directory, its parent and its name there, written by LOOKUP, MKDIR, a READDIRPLUS handle and a rename (to another parent or in place). An install rewrites none of it, and a merged install can move a directory the kernel holds as a cwd or descriptor with no LOOKUP to follow. So a kernel rename of a directory checks every link from the destination up to the root against the current view (the parent must still bind that name to that directory) before its cycle check; a link that no longer holds is `AncestryMismatch` (EINVAL), and the next LOOKUP of that directory records its current place | [`rename.rs`](../../../../engine/crates/layerfs-workspace/src/operations/namespace/rename.rs), [`kernel_mutation.rs`](../../../../engine/crates/layerfs-overlay/src/lifetime/kernel_mutation.rs), [`kernel_directory.rs`](../../../../engine/crates/layerfs-overlay/src/lifetime/kernel_directory.rs) | | Renaming one name of an inode onto another name of the same inode succeeds and changes nothing | [`rename.rs`](../../../../engine/crates/layerfs-workspace/src/operations/namespace/rename.rs) | | A file renamed over a file records a `predecessor`, offered to Commit as a delta base | same | | Parent `entries` and `subdirs` move in the same row as the binding; leaving range is an error, never clamped | [`eval.rs`](../../../../engine/crates/layerfs-workspace/src/mutation/eval.rs) | @@ -59,7 +60,12 @@ What each filesystem operation on a [Workspace](README.md) reads and publishes, window, whiteouts included, so a window can be empty and still continue. A name bound for the whole enumeration is returned exactly once; names changed meanwhile may or may not appear. A directory created above the installed -floor makes no base demand +floor makes no base demand. The base page may spend `PAGE_ROWS` rows of the +longest name, as the directory reader charges them (`NAME_LENGTH_BYTES` + +`DIRECTORY_LEAF_SERIAL_BYTES` + 255 bytes each), so it ends on its row bound. +Should a base page still end with a continuation before the window's other +keys, the merge stops at the base's last fetched name: a local key past it +would skip the base names between ([`namespace/list.rs`](../../../../engine/crates/layerfs-workspace/src/operations/namespace/list.rs)). ## Attributes @@ -143,7 +149,12 @@ Facts carried between visits are used only while the Workspace still has the base they came from, so an install between visits costs another read, never a stale answer. OPEN names an inode the kernel still references, so a file whose last name is gone stays openable. A data visit holds nothing after its -job. +job. A serial the kernel names by itself (GETATTR, OPEN, OPENDIR, a LOOKUP's +directory, READ, READLINK and READDIR of an open handle) that no local row or +base inode has any more was dropped by an install while the kernel held it: +the request fails with `OverlayError::Stale` (ESTALE on FUSE, `NFS3ERR_STALE` +on NFS) and nothing else changes (`Eval::held`). A name bound to an absent +inode is still `InvalidRecord`. ## Kernel directories diff --git a/engine/crates/layerfs-daemon/tests/stale_handles.rs b/engine/crates/layerfs-daemon/tests/stale_handles.rs new file mode 100644 index 0000000000..3a315fa762 --- /dev/null +++ b/engine/crates/layerfs-daemon/tests/stale_handles.rs @@ -0,0 +1,146 @@ +//! A merged install changes what a held cwd names, and the mount serves on. +//! +//! Each case holds a directory of Workspace A as a process's cwd. Another +//! Workspace publishes a change to that directory, and A's next Commit merges +//! it and installs the merged root. No path walk refreshes the held cwd: the +//! kernel still names it by its old inode. The held process makes the checked +//! requests itself, from that cwd, once it is released. +//! +//! - The merge drops the directory's serial: GETATTR, OPENDIR and LOOKUP +//! through the cwd answer ESTALE for each request alone, nothing is retained +//! and the mount keeps serving (review finding #7). +//! - The merge moves the directory under another one: a rename of that other +//! directory into the cwd is refused instead of making a cycle cut off from +//! the root, and the kernel parent index follows the next LOOKUP (#17). +#![cfg(target_os = "linux")] +#[allow(dead_code)] +#[path = "support/installed_store.rs"] +mod installed; +#[allow(dead_code)] +#[path = "support/namespace_model.rs"] +mod model; +#[allow(dead_code)] +#[path = "support/mounted.rs"] +mod mounted; +#[allow(dead_code)] +#[path = "support/mounted_commit.rs"] +mod rig; +use layerfs_bridge::control::{ReadyMount, Reply}; +use mounted::COMMAND; +use rig::{bash_in, passed, root, Background, Rig}; + +/// A's Commit merges with the other Workspace's and installs the result. +fn merged(rig: &Rig, a: &ReadyMount) { + passed( + &bash_in(COMMAND, root(a), "printf alpha > from-a"), + "A changes another file", + ); + let done = rig.commit(a.token).expect("A commits"); + assert!( + matches!(done.reply, Reply::MergeCommitted(_)), + "A's Commit merges: {:?}", + done.reply + ); +} +/// No request of the mount was retained: it is not terminal. +fn serving(rig: &Rig, a: &ReadyMount, what: &str) { + let work = rig.harness.status(a.token).kernel.unwrap().work.unwrap(); + assert_eq!(work.retained, 0, "{what}: {work:?}"); +} +/// The held process waits for its release, then runs `checks` in its cwd; +/// a failed check is reported on its standard error. +fn held(directory: &std::path::Path, checks: &str) -> Background { + let script = format!("read line; set -u\n{checks}"); + Background::spawn(COMMAND, directory, &script) +} + +#[test] +fn a_held_directory_the_merge_dropped_answers_estale_and_the_mount_serves_on() { + let rig = Rig::new("stale-dropped-serial"); + let a = rig.mount(1); + passed( + &bash_in( + COMMAND, + root(&a), + "mkdir -p doomed/inner && printf x > doomed/f", + ), + "A makes doomed", + ); + rig.committed(a.token, "A publishes doomed"); + let b = rig.mount(2); + // GETATTR, OPENDIR and LOOKUP of the dropped directory, from inside it. + let process = held( + &root(&a).join("doomed"), + "stale() { case $1 in *'Stale file handle'*) ;; *) echo \"$2: $1\" >&2; exit 1;; esac; } + out=$(stat . 2>&1) && { echo \"stat passed: $out\" >&2; exit 1; }; stale \"$out\" stat + out=$(ls . 2>&1) && { echo \"ls passed: $out\" >&2; exit 1; }; stale \"$out\" ls + out=$(stat f 2>&1) && { echo \"lookup passed: $out\" >&2; exit 1; }; stale \"$out\" lookup + exit 0", + ); + passed( + &bash_in(COMMAND, root(&b), "rm -rf doomed"), + "B removes doomed", + ); + rig.committed(b.token, "B publishes the removal"); + merged(&rig, &a); + let status = process.release(); + assert!(status.success(), "the held cwd was not stale: {status:?}"); + serving(&rig, &a, "after the stale requests"); + passed( + &bash_in( + COMMAND, + root(&a), + "test \"$(cat from-a)\" = alpha && test ! -e doomed \ + && printf beta > after && test \"$(cat after)\" = beta", + ), + "the mount serves on", + ); + serving(&rig, &a, "after serving on"); + rig.unmount(&a); + rig.unmount(&b); + rig.finish(); +} + +#[test] +fn a_rename_into_a_held_directory_the_merge_moved_makes_no_cycle() { + let rig = Rig::new("stale-parent-index"); + let a = rig.mount(1); + passed(&bash_in(COMMAND, root(&a), "mkdir x y"), "A makes x and y"); + rig.committed(a.token, "A publishes x and y"); + let b = rig.mount(2); + // A's kernel still holds y as the cwd it looked up at the root. Moving x + // into it would make x and y a cycle cut off from the root. The first + // attempt runs before any LOOKUP of y's new place, so only the checked + // parent index can refuse it; after `test -d x/y` it is a known cycle. + let mount = root(&a).display().to_string(); + let process = held( + &root(&a).join("y"), + &format!( + "m={mount} + refused() {{ case $1 in *'Invalid argument'*|*'subdirectory of itself'*) ;; *) echo \"$2: $1\" >&2; exit 1;; esac; }} + out=$(mv -T $m/x x2 2>&1) && {{ echo 'stale index: x moved into y' >&2; exit 1; }}; refused \"$out\" stale + test -d $m/x && test ! -e x2 || {{ echo 'x moved' >&2; exit 1; }} + test -d $m/x/y || {{ echo 'y is not under x' >&2; exit 1; }} + out=$(mv -T $m/x x2 2>&1) && {{ echo 'cycle: x moved into y' >&2; exit 1; }}; refused \"$out\" cycle + mkdir $m/z && mv -T $m/z z && test -d $m/x/y/z || {{ echo 'z did not move in' >&2; exit 1; }} + exit 0" + ), + ); + passed(&bash_in(COMMAND, root(&b), "mv y x/y"), "B moves y under x"); + rig.committed(b.token, "B publishes the move"); + merged(&rig, &a); + let status = process.release(); + assert!(status.success(), "a rename made a cycle: {status:?}"); + serving(&rig, &a, "after the refused renames"); + passed( + &bash_in( + COMMAND, + root(&a), + "test \"$(cat from-a)\" = alpha && test -d x/y/z && test ! -e y", + ), + "the mount serves on", + ); + rig.unmount(&a); + rig.unmount(&b); + rig.finish(); +} diff --git a/engine/crates/layerfs-fuse/src/request/directory.rs b/engine/crates/layerfs-fuse/src/request/directory.rs index 1f886e75b6..553b93ee36 100644 --- a/engine/crates/layerfs-fuse/src/request/directory.rs +++ b/engine/crates/layerfs-fuse/src/request/directory.rs @@ -61,6 +61,12 @@ impl KernelFilesystem { reply.error(Errno::EINVAL); RequestDisposition::Complete } + // The open directory's serial was dropped by an install: + // this request alone answers ESTALE. + Ok(Err(failure)) if failure.stale() => { + reply.error(Errno::ESTALE); + terminal::directory(&fence, failure).await + } // The typed failure still owns whatever was acquired. Ok(Err(failure)) if failure.fenced() => { reply.error(terminal::STOPPED); @@ -173,7 +179,7 @@ async fn enumerate( } Ok(DirectoryStep::Batch(batch)) => batch, Err(error) => { - reply.error(terminal::errno(error.fenced())); + reply.error(terminal::errno(error.fenced(), error.stale())); return terminal::directory(fence, error).await; } }; @@ -215,7 +221,7 @@ async fn enumerate( // A fenced publication published nothing: the offered entries // are never sent. Any other failure here is retained. Err(error) => { - reply.error(terminal::errno(error.fenced())); + reply.error(terminal::errno(error.fenced(), error.stale())); return terminal::directory(fence, error).await; } }; diff --git a/engine/crates/layerfs-fuse/src/request/mutate.rs b/engine/crates/layerfs-fuse/src/request/mutate.rs index 4426190056..8e820c11eb 100644 --- a/engine/crates/layerfs-fuse/src/request/mutate.rs +++ b/engine/crates/layerfs-fuse/src/request/mutate.rs @@ -92,7 +92,7 @@ impl MutationReply { let mutation = match KernelMutation::perform(services, request).await { Ok(mutation) => mutation, Err(failure) => { - self.error(terminal::errno(failure.fenced())); + self.error(terminal::errno(failure.fenced(), false)); return terminal::mutation(&fence, failure).await; } }; diff --git a/engine/crates/layerfs-fuse/src/request/reply.rs b/engine/crates/layerfs-fuse/src/request/reply.rs index 7985ed950e..e624403143 100644 --- a/engine/crates/layerfs-fuse/src/request/reply.rs +++ b/engine/crates/layerfs-fuse/src/request/reply.rs @@ -84,7 +84,7 @@ impl ReadReply { RequestDisposition::Complete } Err(error) => { - reply.error(terminal::errno(error.fenced())); + reply.error(terminal::errno(error.fenced(), error.stale())); terminal::read(&fence, error).await } } @@ -108,7 +108,7 @@ impl ReadReply { { Ok(answer) => answer, Err(error) => { - self.error(terminal::errno(error.fenced())); + self.error(terminal::errno(error.fenced(), error.stale())); return terminal::read(&fence, error).await; } }; diff --git a/engine/crates/layerfs-fuse/src/request/terminal.rs b/engine/crates/layerfs-fuse/src/request/terminal.rs index 2ad65b36db..34f3831087 100644 --- a/engine/crates/layerfs-fuse/src/request/terminal.rs +++ b/engine/crates/layerfs-fuse/src/request/terminal.rs @@ -1,13 +1,17 @@ //! How an admitted request ends itself instead of being retained with its //! mount fenced: after its mount's stopped fence refused it before an -//! attempt, or after a base demand made for it alone failed. +//! attempt, after a base demand made for it alone failed, or after a read or +//! directory visit found that the serial it names was dropped by an install. //! //! Forced teardown stops the fence after its abort write. A request waiting //! for owner admission or a Store reader then fails with `Fenced` instead of //! attempting anything; its single reply attempt answers [`STOPPED`] and is //! counted on the fence. A request whose canonical base demand failed carries //! `BaseDemandFailed`; its single reply attempt answers `EIO`, its cause is -//! already in the mount's bounded record, and later requests are served. +//! already in the mount's bounded record, and later requests are served. A +//! read or directory request whose serial an install dropped while the kernel +//! held it (`stale()`: a merge rebuilt that directory or file under a fresh +//! serial) answers `ESTALE` and is not recorded; the mount serves on. //! //! Either way the request then releases what it still owns through the //! disposal ports, which the fence never refuses, and makes no further demand. @@ -27,10 +31,13 @@ use layerfs_mount_ports::{ /// the request's reply ownership. pub(super) const STOPPED: Errno = Errno::ENOTCONN; -/// The one reply of a failed request: stopped, or a failure of its own. -pub(super) fn errno(fenced: bool) -> Errno { +/// The one reply of a failed request: stopped, a stale serial, or a failure +/// of its own. +pub(super) fn errno(fenced: bool, stale: bool) -> Errno { if fenced { STOPPED + } else if stale { + Errno::ESTALE } else { Errno::EIO } @@ -38,7 +45,7 @@ pub(super) fn errno(fenced: bool) -> Errno { pub(super) async fn read(fence: &Fence, failure: ReadFailure) -> RequestDisposition { if failure.fenced() { fence.replied(); - } else if failure.base_demand().is_none() { + } else if failure.base_demand().is_none() && !failure.stale() { return RequestDisposition::Retained(Box::new(failure)); } match failure.relinquish().await { @@ -62,7 +69,7 @@ pub(super) async fn mutation(fence: &Fence, failure: MutationFailure) -> Request pub(super) async fn directory(fence: &Fence, failure: DirectoryFailure) -> RequestDisposition { if failure.fenced() { fence.replied(); - } else if failure.base_demand().is_none() { + } else if failure.base_demand().is_none() && !failure.stale() { return RequestDisposition::Retained(Box::new(failure)); } match failure.relinquish().await { diff --git a/engine/crates/layerfs-mount-ports/src/operations/directory.rs b/engine/crates/layerfs-mount-ports/src/operations/directory.rs index 61c8732d82..bf45a8217d 100644 --- a/engine/crates/layerfs-mount-ports/src/operations/directory.rs +++ b/engine/crates/layerfs-mount-ports/src/operations/directory.rs @@ -104,12 +104,18 @@ impl DirectoryFailure { pub fn rewound(&self) -> bool { self.reason.is::() } - /// Ends an enumeration that was fenced, whose base demand failed or - /// whose offset a rewind retired. It holds nothing in the engine, so - /// nothing is released and no job is submitted; an unpublished batch - /// made no offset valid. Any other failure is returned unchanged. + /// The open directory's serial is one an install dropped + /// ([`crate::ports::stale`]): ESTALE for this request alone. + pub fn stale(&self) -> bool { + crate::ports::stale(&self.reason) + } + /// Ends an enumeration that was fenced, whose base demand failed, whose + /// offset a rewind retired or whose serial is stale. It holds nothing in + /// the engine, so nothing is released and no job is submitted; an + /// unpublished batch made no offset valid. Any other failure is returned + /// unchanged. pub async fn relinquish(self) -> Result<(), DirectoryFailure> { - if !self.fenced() && self.base_demand().is_none() && !self.rewound() { + if !self.fenced() && self.base_demand().is_none() && !self.rewound() && !self.stale() { return Err(self); } Ok(()) @@ -287,10 +293,18 @@ impl DirectoryBatch { /// `accepted` is the prefix the reply buffer took; only published offsets /// can make a handle's fence answer, so a reused reply adopts nothing. pub fn adopt(&mut self, accepted: usize) { - let entries: Vec<(u64, bool)> = self.batch.entries[..accepted] + let entries: Vec<(u64, bool, Vec)> = self.batch.entries[..accepted] .iter() .filter(|entry| entry.stat.is_some()) - .map(|entry| (entry.serial, entry.kind == InodeKind::Directory)) + .map(|entry| { + let directory = entry.kind == InodeKind::Directory; + let name = if directory { + entry.name.clone() + } else { + Vec::new() + }; + (entry.serial, directory, name) + }) .collect(); if let Some(offer) = self.batch.publish.as_mut() { offer.adopt(entries); diff --git a/engine/crates/layerfs-mount-ports/src/operations/lookup.rs b/engine/crates/layerfs-mount-ports/src/operations/lookup.rs index 0a77df6119..09709f7471 100644 --- a/engine/crates/layerfs-mount-ports/src/operations/lookup.rs +++ b/engine/crates/layerfs-mount-ports/src/operations/lookup.rs @@ -1,5 +1,5 @@ //! LOOKUP/GETATTR/OPEN/OPENDIR share the existing atomic semantic plan. -use crate::ports::{BaseDemandFailed, Fenced, RequestServices, ServiceError, ServiceReply}; +use crate::ports::{stale, BaseDemandFailed, Fenced, RequestServices, ServiceError, ServiceReply}; use layerfs_overlay::KernelMount; use layerfs_workspace::{ KernelReadDecision, KernelReadFailure, KernelReadOperation, KernelReadOutcome, KernelReadValue, @@ -101,11 +101,17 @@ impl ReadFailure { pub fn base_demand(&self) -> Option<&BaseDemandFailed> { self.reason.downcast_ref() } - /// Ends a request that was fenced or whose base demand failed. It holds - /// nothing in the engine, so nothing is released and no job is - /// submitted. Any other failure is returned unchanged. + /// The kernel named a serial an install dropped ([`stale`]): ESTALE for + /// this request alone. + pub fn stale(&self) -> bool { + stale(&self.reason) + } + /// Ends a request that was fenced, whose base demand failed or whose + /// serial is stale. It holds nothing in the engine, so nothing is + /// released and no job is submitted. Any other failure is returned + /// unchanged. pub async fn relinquish(self) -> Result<(), ReadFailure> { - if !self.fenced() && self.base_demand().is_none() { + if !self.fenced() && self.base_demand().is_none() && !self.stale() { return Err(self); } Ok(()) diff --git a/engine/crates/layerfs-mount-ports/src/ports.rs b/engine/crates/layerfs-mount-ports/src/ports.rs index 1bfd63ba81..54685dd055 100644 --- a/engine/crates/layerfs-mount-ports/src/ports.rs +++ b/engine/crates/layerfs-mount-ports/src/ports.rs @@ -1,8 +1,8 @@ //! External engine/Store boundaries; all waiting returns to the kernel pool. -use layerfs_overlay::{KernelCookieOffer, KernelMount, Publication}; +use layerfs_overlay::{KernelCookieOffer, KernelMount, OverlayError, Publication}; use layerfs_workspace::{ - BaseView, KernelDirectoryWindow, KernelMutationOutcome, KernelReadOperation, KernelReadOutcome, - KernelVisitRequest, KernelWindow, VisitFacts, WriteData, + BaseView, KernelDirectoryWindow, KernelMutationOutcome, KernelReadFailure, KernelReadOperation, + KernelReadOutcome, KernelVisitRequest, KernelWindow, VisitFacts, WorkspaceError, WriteData, }; use std::{ error::Error, @@ -109,6 +109,27 @@ impl Fence { self.0.terminal_replies.fetch_add(1, Ordering::AcqRel); } } +/// Whether a failed read or directory step is the engine's own answer that +/// the kernel named a serial the current view no longer has: an install +/// dropped it while the kernel still held it (a cwd, an open descriptor or a +/// cached inode). Only two shapes qualify: a reading visit whose job answered +/// `OverlayError::Stale` and rolled back, and the Workspace's `Stale` from the +/// window finished outside the owner. Both precede any publication and own +/// nothing in the engine, so the request alone answers ESTALE. No wrapper is +/// looked through: an uncertain, retained or owner failure that merely +/// carries a `Stale` cause is not stale. +pub fn stale(reason: &ServiceError) -> bool { + let reason: &(dyn Error + 'static) = reason.as_ref(); + if let Some(failure) = reason.downcast_ref::() { + return failure.original.decision.is_none() + && matches!(failure.original.result, Err(OverlayError::Stale)); + } + matches!( + reason.downcast_ref::(), + Some(WorkspaceError::Overlay(OverlayError::Stale)) + ) +} + /// A stopped fence refused this acquisition before any attempt: no job was /// submitted and no provider demand was made. It is never the result of an /// attempted operation. diff --git a/engine/crates/layerfs-mount-ports/tests/stale.rs b/engine/crates/layerfs-mount-ports/tests/stale.rs new file mode 100644 index 0000000000..4dc1246989 --- /dev/null +++ b/engine/crates/layerfs-mount-ports/tests/stale.rs @@ -0,0 +1,50 @@ +//! Which failed steps end their request alone as a stale serial: only the +//! engine's own Stale answer, never a wrapper that merely carries one. +use layerfs_content::ContentError; +use layerfs_mount_ports::ports::{stale, ServiceError}; +use layerfs_overlay::{KernelObservation, OverlayError}; +use layerfs_workspace::{KernelReadDecision, KernelReadFailure, WorkspaceError}; +use std::sync::Arc; + +/// A reading visit whose job answered `result` with no decision. +fn visit(result: Result<(), OverlayError>) -> ServiceError { + Box::new(KernelReadFailure { + reason: "kernel read visit did not produce a usable original answer", + original: Arc::new(KernelObservation:: { + decision: None, + result: result.map(|()| None), + open_candidate: None, + directory_candidate: None, + }), + }) +} + +#[test] +fn only_the_engines_own_stale_answer_is_a_stale_serial() { + // The visit's job answered Stale and rolled back. + assert!(stale(&visit(Err(OverlayError::Stale)))); + // The window finished outside the owner found the serial gone. + assert!(stale( + &(Box::new(WorkspaceError::Overlay(OverlayError::Stale)) as ServiceError) + )); + + // An uncertain outcome is never classified from its cause. + assert!(!stale(&visit(Err(OverlayError::Uncertain { + cause: Box::new(OverlayError::Stale), + completion: None, + })))); + // Corruption stays what it is. + assert!(!stale( + &(Box::new(WorkspaceError::Content(ContentError::InvalidRecord( + "directory entry count" + ))) as ServiceError) + )); + assert!(!stale(&visit(Err(OverlayError::Invalid( + "kernel entry final" + ))))); + // A bare overlay Stale, as an owner wrapper's cause would show it, is not + // one of the two shapes. + assert!(!stale(&(Box::new(OverlayError::Stale) as ServiceError))); + // A decided visit carries no stale answer. + assert!(!stale(&visit(Ok(())))); +} diff --git a/engine/crates/layerfs-overlay/src/contract/kernel.rs b/engine/crates/layerfs-overlay/src/contract/kernel.rs index 1546c7f0ce..61a33d2fbf 100644 --- a/engine/crates/layerfs-overlay/src/contract/kernel.rs +++ b/engine/crates/layerfs-overlay/src/contract/kernel.rs @@ -20,6 +20,18 @@ impl KernelMount { } } +/// One step of a kernel-known directory's retained parent chain: the +/// directory, its parent and the name it had there when the step was recorded +/// (at LOOKUP, MKDIR, a READDIRPLUS handle or a move through the mount). An +/// install can change the view beneath a recorded step; a caller that needs +/// the current ancestry checks each step's name against the current view. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct KernelLink { + pub serial: u64, + pub parent: u64, + pub name: Vec, +} + /// Result of the caller's bounded semantic decision over one SourceRows view. /// None requires no acquisition (for example missing facts or a negative name). pub enum KernelDecision { diff --git a/engine/crates/layerfs-overlay/src/contract/kernel_directory.rs b/engine/crates/layerfs-overlay/src/contract/kernel_directory.rs index 341578b6e1..5ef2bf29cd 100644 --- a/engine/crates/layerfs-overlay/src/contract/kernel_directory.rs +++ b/engine/crates/layerfs-overlay/src/contract/kernel_directory.rs @@ -127,18 +127,24 @@ impl KernelCookieOffer { /// The entries whose handles this publication hands out, in reply order: /// the publishing visit takes one kernel lookup reference for each of /// them and records a directory's parent, so a handle the client later - /// presents resolves without a LOOKUP of its own. - pub fn adopt(&mut self, entries: impl IntoIterator) { + /// presents resolves without a LOOKUP of its own. Each entry is its + /// serial, whether it is a directory and its name in the listing. + pub fn adopt(&mut self, entries: impl IntoIterator)>) { self.handled = entries .into_iter() - .map(|(serial, directory)| KernelCookieEntry { serial, directory }) + .map(|(serial, directory, name)| KernelCookieEntry { + serial, + directory, + name, + }) .collect(); } } /// One entry whose handle a READDIRPLUS reply hands out. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq)] pub struct KernelCookieEntry { pub serial: u64, - /// A directory's parent is recorded with its reference. + /// A directory's parent and name are recorded with its reference. pub directory: bool, + pub name: Vec, } diff --git a/engine/crates/layerfs-overlay/src/contract/types.rs b/engine/crates/layerfs-overlay/src/contract/types.rs index 2a946a9b5a..111ba64a29 100644 --- a/engine/crates/layerfs-overlay/src/contract/types.rs +++ b/engine/crates/layerfs-overlay/src/contract/types.rs @@ -129,7 +129,8 @@ pub struct DirectoryEntryChange { pub struct Changes { /// Semantically removed non-root inode; distinguishes zero-count root metadata. pub detached: Option, - /// A directory moved to another parent by this same name publication. + /// A directory moved to another parent, or renamed in its own, by this + /// same name publication. /// Updates retained kernel parent identity without enumerating open handles. pub moved_directory: Option<(u64, u64)>, /// Exact descriptor authority for mutations of independently owned orphans. diff --git a/engine/crates/layerfs-overlay/src/lib.rs b/engine/crates/layerfs-overlay/src/lib.rs index 1f830464d1..892fc929b0 100644 --- a/engine/crates/layerfs-overlay/src/lib.rs +++ b/engine/crates/layerfs-overlay/src/lib.rs @@ -38,7 +38,8 @@ pub use contract::indexed_operation_record::{ OperationRecordExpectedValue, }; pub use contract::kernel::{ - KernelApplied, KernelDecision, KernelEffect, KernelMount, KernelMountState, KernelObservation, + KernelApplied, KernelDecision, KernelEffect, KernelLink, KernelMount, KernelMountState, + KernelObservation, }; pub use contract::kernel_directory::{ KernelCookieOffer, KernelDirectory, KernelDirectoryCursor, KernelDirectoryPage, diff --git a/engine/crates/layerfs-overlay/src/lifetime/kernel.rs b/engine/crates/layerfs-overlay/src/lifetime/kernel.rs index eae178754e..d20f36d5c4 100644 --- a/engine/crates/layerfs-overlay/src/lifetime/kernel.rs +++ b/engine/crates/layerfs-overlay/src/lifetime/kernel.rs @@ -28,7 +28,7 @@ impl Overlay { }; self.open.borrow_mut().mount = Some((mount, false)); self.insert_kernel_lookup(mount, root, true, 0)?; - self.set_kernel_parent(mount, root, root)?; + self.set_kernel_parent(mount, root, root, &[])?; Ok(mount) }) } @@ -48,7 +48,7 @@ impl Overlay { .parents .rows .iter() - .filter(|(_, (owner, _))| *owner == revoked.owner) + .filter(|(_, row)| row.owner == revoked.owner) .map(|(key, _)| *key) .collect::>(); (references, parents) diff --git a/engine/crates/layerfs-overlay/src/lifetime/kernel_cookie.rs b/engine/crates/layerfs-overlay/src/lifetime/kernel_cookie.rs index 2e319984ad..9881e5722f 100644 --- a/engine/crates/layerfs-overlay/src/lifetime/kernel_cookie.rs +++ b/engine/crates/layerfs-overlay/src/lifetime/kernel_cookie.rs @@ -141,7 +141,12 @@ impl Overlay { for entry in &offer.handled { self.add_kernel_lookup(directory.mount, entry.serial)?; if entry.directory { - self.set_kernel_parent(directory.mount, entry.serial, directory.serial)?; + self.set_kernel_parent( + directory.mount, + entry.serial, + directory.serial, + &entry.name, + )?; } } Ok(()) diff --git a/engine/crates/layerfs-overlay/src/lifetime/kernel_directory.rs b/engine/crates/layerfs-overlay/src/lifetime/kernel_directory.rs index c938811610..3a9932cf9f 100644 --- a/engine/crates/layerfs-overlay/src/lifetime/kernel_directory.rs +++ b/engine/crates/layerfs-overlay/src/lifetime/kernel_directory.rs @@ -1,33 +1,47 @@ //! Exact kernel directory owners and retained current parent relationships. use crate::{ - db::integer, KernelDirectory, KernelMount, Overlay, OverlayError, OverlayResult, ReferenceKind, + db::integer, open::KernelParent, KernelDirectory, KernelLink, KernelMount, Overlay, + OverlayError, OverlayResult, ReferenceKind, }; impl Overlay { - /// Called by the deciding lookup/mutation transaction for a directory only. + /// Called by the deciding lookup/mutation transaction for a directory only, + /// with the name that binds it in `parent` in that transaction's view. /// Its FK follows existing independent file custody, including open dirs. pub(crate) fn set_kernel_parent( &self, mount: KernelMount, serial: u64, parent: u64, + name: &[u8], ) -> OverlayResult<()> { integer(serial)?; integer(parent)?; - self.open - .borrow_mut() - .parents - .put(serial, (mount.owner, parent)); + self.open.borrow_mut().parents.put( + serial, + KernelParent { + owner: mount.owner, + parent, + name: name.into(), + }, + ); Ok(()) } pub(crate) fn kernel_parent(&self, mount: KernelMount, serial: u64) -> OverlayResult { + self.kernel_link(mount, serial).map(|link| link.parent) + } + pub(crate) fn kernel_link(&self, mount: KernelMount, serial: u64) -> OverlayResult { self.available()?; self.open .borrow() .parents .rows .get(&serial) - .filter(|(owner, _)| *owner == mount.owner) - .map(|(_, parent)| *parent) + .filter(|row| row.owner == mount.owner) + .map(|row| KernelLink { + serial, + parent: row.parent, + name: row.name.to_vec(), + }) .ok_or(OverlayError::Stale) } pub(crate) fn retain_kernel_directory( diff --git a/engine/crates/layerfs-overlay/src/lifetime/kernel_mutation.rs b/engine/crates/layerfs-overlay/src/lifetime/kernel_mutation.rs index f8c697aa79..038b6a0771 100644 --- a/engine/crates/layerfs-overlay/src/lifetime/kernel_mutation.rs +++ b/engine/crates/layerfs-overlay/src/lifetime/kernel_mutation.rs @@ -1,8 +1,8 @@ //! One kernel mutation transaction: its publication together with the kernel //! lookup and open custody that the mutation's own reply hands to the kernel. use crate::{ - db::integer, Changes, KernelApplied, KernelEffect, KernelMount, Overlay, OverlayError, - OverlayResult, + db::integer, Changes, KernelApplied, KernelEffect, KernelLink, KernelMount, Overlay, + OverlayError, OverlayResult, }; /// Longest parent chain one cycle check reads: the canonical component limit @@ -76,7 +76,17 @@ impl Overlay { } }; if directory { - self.set_kernel_parent(mount, serial, parent)?; + // The one binding this job published for the directory. + let name = changes + .directory_entries + .iter() + .find(|entry| { + entry.parent == parent + && matches!(entry.binding, crate::Binding::Bound { serial: bound, .. } if bound == serial) + }) + .map(|entry| entry.name.as_slice()) + .ok_or(OverlayError::Invalid("kernel entry binding"))?; + self.set_kernel_parent(mount, serial, parent, name)?; } Ok(KernelApplied { publication, file }) } @@ -140,20 +150,28 @@ impl Overlay { } Ok(()) } - /// The retained parent chain of one kernel-known directory, from itself to - /// the root. Every step is an indexed point read of a row this connection - /// recorded at LOOKUP, MKDIR or a directory move; a missing step is Stale, - /// never an assumed root. No name, reverse index or subtree is read. - pub fn kernel_ancestors(&self, mount: KernelMount, serial: u64) -> OverlayResult> { + /// The retained parent chain of one kernel-known directory, from itself up + /// to the root: one link per directory below the root, each with the name + /// it was recorded under. Every step is an indexed point read of a row + /// this connection recorded at LOOKUP, MKDIR, a READDIRPLUS handle or a + /// move; a missing step is Stale, never an assumed root. No reverse index + /// or subtree is read. An install does not rewrite these rows, so a + /// caller that relies on the chain checks each link against its view. + pub fn kernel_ancestors( + &self, + mount: KernelMount, + serial: u64, + ) -> OverlayResult> { self.check_kernel_attached(mount)?; - let mut chain = vec![serial]; + let mut chain = Vec::new(); let mut current = serial; while current != mount.root { - if chain.len() == ANCESTRY_STEPS { + if chain.len() + 1 == ANCESTRY_STEPS { return Err(OverlayError::Invalid("kernel ancestry depth")); } - current = self.kernel_parent(mount, current)?; - chain.push(current); + let link = self.kernel_link(mount, current)?; + current = link.parent; + chain.push(link); } Ok(chain) } diff --git a/engine/crates/layerfs-overlay/src/lifetime/kernel_visit.rs b/engine/crates/layerfs-overlay/src/lifetime/kernel_visit.rs index 5859611296..805f97045f 100644 --- a/engine/crates/layerfs-overlay/src/lifetime/kernel_visit.rs +++ b/engine/crates/layerfs-overlay/src/lifetime/kernel_visit.rs @@ -146,13 +146,14 @@ impl Overlay { /// decision over current rows and base facts it holds or reads from /// memory; it performs no provider I/O. A decision that still needs a /// base fact changes nothing here. A positive LOOKUP takes its kernel - /// lookup reference in the same transaction as the answer. + /// lookup reference in the same transaction as the answer. `lookup` is + /// the LOOKUP's name, recorded with a found directory's parent. pub fn observe_kernel_visit( &self, mount: KernelMount, serial: u64, handle: Option, - lookup: bool, + lookup: Option<&[u8]>, decide: impl FnOnce(SourceRows<'_>, BaseSource) -> OverlayResult>, ) -> KernelObservation { self.observe_visit(mount, serial, handle, lookup, None, decide) @@ -173,7 +174,7 @@ impl Overlay { decide: impl FnOnce(SourceRows<'_>, BaseSource) -> OverlayResult>, ) -> KernelObservation { let opened = Opened::File { request, writable }; - self.observe_visit(mount, serial, None, false, Some(opened), decide) + self.observe_visit(mount, serial, None, None, Some(opened), decide) } /// OPENDIR in one visit, under the kernel's lookup reference on the /// inode. When the same bounded decision finishes with the directory, @@ -189,14 +190,14 @@ impl Overlay { decide: impl FnOnce(SourceRows<'_>, BaseSource) -> OverlayResult>, ) -> KernelObservation { let opened = Opened::Directory { request }; - self.observe_visit(mount, serial, None, false, Some(opened), decide) + self.observe_visit(mount, serial, None, None, Some(opened), decide) } fn observe_visit( &self, mount: KernelMount, serial: u64, handle: Option, - lookup: bool, + lookup: Option<&[u8]>, open: Option, decide: impl FnOnce(SourceRows<'_>, BaseSource) -> OverlayResult>, ) -> KernelObservation { @@ -223,13 +224,13 @@ impl Overlay { }; let Some(inode) = inode else { return Ok(()) }; inode::check(&inode)?; - if lookup { + if let Some(name) = lookup { if inode.nlink == 0 && inode.serial != mount.root { return Err(OverlayError::Missing); } self.add_kernel_lookup(mount, inode.serial)?; if inode.kind == InodeKind::Directory { - self.set_kernel_parent(mount, inode.serial, serial)?; + self.set_kernel_parent(mount, inode.serial, serial, name)?; } } else if inode.serial != serial { return Err(OverlayError::Invalid("kernel observation serial")); diff --git a/engine/crates/layerfs-overlay/src/namespace/compound.rs b/engine/crates/layerfs-overlay/src/namespace/compound.rs index 9a5f8b033d..acc8b739cf 100644 --- a/engine/crates/layerfs-overlay/src/namespace/compound.rs +++ b/engine/crates/layerfs-overlay/src/namespace/compound.rs @@ -24,7 +24,7 @@ pub struct SourceRows<'a> { /// Validated name keys of one compound job, computed before its transaction. pub(crate) struct CheckedChanges { keys: Vec<(i64, Option)>, - moved_directory: Option<(i64, i64)>, + moved_directory: Option<(i64, i64, Vec)>, } impl Overlay { /// Checks source custody once for the bounded point reads of one job. @@ -85,12 +85,13 @@ impl Overlay { return Err(OverlayError::Invalid("created inode final")); } let moved_directory = changes.moved_directory.map(|(serial, parent)| { - if serial == parent || !changes.directory_entries.iter().any(|entry| { + let binding = changes.directory_entries.iter().find(|entry| { entry.parent == parent && matches!(entry.binding, crate::Binding::Bound { serial: target, .. } if target == serial) - }) { + }); + let Some(binding) = binding.filter(|_| serial != parent) else { return Err(OverlayError::Invalid("moved directory final binding")); - } - Ok((integer(serial)?, integer(parent)?)) + }; + Ok((integer(serial)?, integer(parent)?, binding.name.clone())) }).transpose()?; for (index, inode) in changes.inodes.iter().enumerate() { check(inode)?; @@ -255,15 +256,25 @@ impl Overlay { )? as i64; } } - if let Some((serial, parent)) = moved_directory { + if let Some((serial, parent, name)) = moved_directory { let key = *serial as u64; - let held = self.open.borrow().parents.rows.get(&key).copied(); - if let Some((mount, old)) = held { + let held = self + .open + .borrow() + .parents + .rows + .get(&key) + .map(|row| (row.owner, row.parent)); + if let Some((owner, old)) = held { if old != *serial as u64 { - self.open - .borrow_mut() - .parents - .put(key, (mount, *parent as u64)); + self.open.borrow_mut().parents.put( + key, + crate::open::KernelParent { + owner, + parent: *parent as u64, + name: name.as_slice().into(), + }, + ); } } } diff --git a/engine/crates/layerfs-overlay/src/open/kernel.rs b/engine/crates/layerfs-overlay/src/open/kernel.rs index fad637ebd3..d2992ae06b 100644 --- a/engine/crates/layerfs-overlay/src/open/kernel.rs +++ b/engine/crates/layerfs-overlay/src/open/kernel.rs @@ -14,10 +14,18 @@ pub(crate) struct KernelReference { pub count: u64, pub implicit: bool, } +/// One kernel-known directory's retained position: the mount owner that +/// knows it, its parent and its name in that parent when it was recorded. +#[derive(Clone)] +pub(crate) struct KernelParent { + pub owner: u64, + pub parent: u64, + pub name: Box<[u8]>, +} #[derive(Default)] pub(crate) struct OpenState { pub kernel: JournalMap<(u64, u64), KernelReference>, - pub parents: JournalMap, + pub parents: JournalMap, /// Descriptors by owner; requests are (kernel mount owner or 0, request). pub files: OwnerTable<(u64, i64), OpenFile>, pub reads: OwnerTable, diff --git a/engine/crates/layerfs-overlay/src/open/mod.rs b/engine/crates/layerfs-overlay/src/open/mod.rs index f93d6824a6..591c686d56 100644 --- a/engine/crates/layerfs-overlay/src/open/mod.rs +++ b/engine/crates/layerfs-overlay/src/open/mod.rs @@ -7,4 +7,4 @@ pub use directories::OpenDisposals; pub(crate) use directories::{CookiePage, DirectoryState}; pub(crate) mod files; mod kernel; -pub(crate) use kernel::{KernelReference, OpenState}; +pub(crate) use kernel::{KernelParent, KernelReference, OpenState}; diff --git a/engine/crates/layerfs-overlay/tests/kernel_memory.rs b/engine/crates/layerfs-overlay/tests/kernel_memory.rs index 598455720b..3fee2bbca6 100644 --- a/engine/crates/layerfs-overlay/tests/kernel_memory.rs +++ b/engine/crates/layerfs-overlay/tests/kernel_memory.rs @@ -36,7 +36,7 @@ fn remembered_regular_file_allocation_is_measured_without_a_population_cap() { db.open_workspace([2; 32]).unwrap(); let mount = db.create_kernel_mount(1).unwrap(); let lookup = |serial| { - let outcome = db.observe_kernel_visit(mount, 1, None, true, |_, _| { + let outcome = db.observe_kernel_visit(mount, 1, None, Some(b"file"), |_, _| { Ok(KernelDecision::Finished { inode: Some(Inode { serial, diff --git a/engine/crates/layerfs-workspace/src/mutation/eval.rs b/engine/crates/layerfs-workspace/src/mutation/eval.rs index b0ecd1af3c..033efdd2d5 100644 --- a/engine/crates/layerfs-workspace/src/mutation/eval.rs +++ b/engine/crates/layerfs-workspace/src/mutation/eval.rs @@ -2,7 +2,9 @@ use crate::{BaseFacts, Need, Refusal, Time, WorkspaceError, WorkspaceResult}; use layerfs_content::filesystem::PathName; use layerfs_content::ContentError; -use layerfs_overlay::{Inode, InodeKind, KernelMount, NameLayers, Overlay, SourceRows}; +use layerfs_overlay::{ + Inode, InodeKind, KernelMount, NameLayers, Overlay, OverlayError, SourceRows, +}; /// One evaluation inside a single owner job. Every answer comes from rows read /// in this job or from base facts that cannot change while the source is owned. @@ -116,6 +118,29 @@ impl Eval<'_> { Some(None) => Err(ContentError::InvalidRecord("bound inode is absent").into()), } } + /// The inode a kernel request names by its serial alone: GETATTR, OPEN, + /// READLINK, OPENDIR and a LOOKUP's directory. The kernel learned the + /// serial from an earlier view. With no local row and no base inode, an + /// install has dropped it (a merge rebuilt the directory or file under a + /// fresh serial), so the kernel's handle is stale: `OverlayError::Stale` + /// for this request alone, not corruption of the Workspace. + pub fn held(&mut self, serial: u64) -> WorkspaceResult> { + match self.inode(serial)? { + None => Ok(None), + Some(Some(inode)) => Ok(Some(inode)), + Some(None) => Err(OverlayError::Stale.into()), + } + } + /// [`Self::held`] for a directory: a removed one is Missing and another + /// kind NotDirectory, as [`Self::directory`] answers. + pub fn held_directory(&mut self, serial: u64) -> WorkspaceResult> { + match self.held(serial)? { + None => Ok(None), + Some(inode) if !self.alive(&inode) => refuse(Refusal::Missing), + Some(inode) if inode.kind != InodeKind::Directory => refuse(Refusal::NotDirectory), + Some(inode) => Ok(Some(inode)), + } + } } /// The parent's final value after one entry change at `now`. `added` and /// `removed` are the kinds of the binding the directory gains and loses, so diff --git a/engine/crates/layerfs-workspace/src/operations/kernel_data.rs b/engine/crates/layerfs-workspace/src/operations/kernel_data.rs index d343be2889..09c7090820 100644 --- a/engine/crates/layerfs-workspace/src/operations/kernel_data.rs +++ b/engine/crates/layerfs-workspace/src/operations/kernel_data.rs @@ -170,7 +170,9 @@ impl KernelWindow { if self.local.is_none() && self.base.is_none() { self.base = match base.ok_or(NO_BASE)?.inode(serial) { Ok(found) => Some(found.value), - Err(ContentError::PathNotFound) => return Ok(Err(Refusal::Missing)), + // No local row and no inode at the root the visit named: an + // install dropped the serial the kernel still holds. + Err(ContentError::PathNotFound) => return Err(OverlayError::Stale.into()), Err(error) => return Err(error.into()), }; } diff --git a/engine/crates/layerfs-workspace/src/operations/kernel_directory.rs b/engine/crates/layerfs-workspace/src/operations/kernel_directory.rs index 10764718f2..41fbef8d34 100644 --- a/engine/crates/layerfs-workspace/src/operations/kernel_directory.rs +++ b/engine/crates/layerfs-workspace/src/operations/kernel_directory.rs @@ -16,7 +16,7 @@ //! still read once for each entry that needs them. The request then fills its //! reply and a publishing visit records exactly the accepted names. Nothing //! is held between the two visits or after the reply. -use crate::{BaseView, SourceView, ViewStat, Workspace, WorkspaceResult}; +use crate::{BaseView, SourceView, ViewStat, Workspace, WorkspaceError, WorkspaceResult}; use layerfs_content::filesystem::inode::{lookup_many, InodeReadWork}; use layerfs_content::filesystem::Resolved; use layerfs_content::object::inode_leaf::{InodeKind, InodeValue}; @@ -482,7 +482,16 @@ fn merge(base: &BaseView, page: &KernelDirectoryPage) -> WorkspaceResult + { + return Err(OverlayError::Stale.into()); + } + listing => listing?, + }; Ok(MergedNames { names: listing.entries, continuation: listing.continuation, diff --git a/engine/crates/layerfs-workspace/src/operations/kernel_read.rs b/engine/crates/layerfs-workspace/src/operations/kernel_read.rs index ad457daa71..081c8866b2 100644 --- a/engine/crates/layerfs-workspace/src/operations/kernel_read.rs +++ b/engine/crates/layerfs-workspace/src/operations/kernel_read.rs @@ -145,14 +145,15 @@ fn decide( ) -> WorkspaceResult> { match operation { // The source's independent read reference permits removed metadata. + // A serial no row or base inode has any more is stale (`held`). KernelReadOperation::Getattr { serial } | KernelReadOperation::Data { serial } => { - Ok(eval.target(*serial)?.map(|inode| Decided { + Ok(eval.held(*serial)?.map(|inode| Decided { inode, parent: None, })) } KernelReadOperation::Opendir { serial } => { - Ok(eval.directory(*serial)?.map(|inode| Decided { + Ok(eval.held_directory(*serial)?.map(|inode| Decided { inode, parent: None, })) @@ -161,7 +162,7 @@ fn decide( // last name is gone stays openable under that reference, so a // path open racing an unlink or replacement gets the old file. KernelReadOperation::Open { serial, .. } => { - let inode = eval.target(*serial)?; + let inode = eval.held(*serial)?; match inode { Some(inode) if inode.kind == InodeKind::File => Ok(Some(Decided { inode, @@ -175,7 +176,7 @@ fn decide( } } KernelReadOperation::Lookup { parent, name } => { - let directory = eval.directory(*parent)?; + let directory = eval.held_directory(*parent)?; let layers = eval.layers(*parent, name)?; let bound = eval.bound(*parent, directory.as_ref(), name, layers); let (Some(directory), Some(bound)) = (directory, bound) else { diff --git a/engine/crates/layerfs-workspace/src/operations/kernel_visit.rs b/engine/crates/layerfs-workspace/src/operations/kernel_visit.rs index 9447fc5afb..d7c88ca714 100644 --- a/engine/crates/layerfs-workspace/src/operations/kernel_visit.rs +++ b/engine/crates/layerfs-workspace/src/operations/kernel_visit.rs @@ -273,7 +273,10 @@ impl KernelReadVisit { /// carries its descriptor as the observation's open or directory /// candidate. pub fn perform(&self, db: &Overlay) -> KernelReadOutcome { - let lookup = matches!(self.operation, KernelReadOperation::Lookup { .. }); + let lookup = match &self.operation { + KernelReadOperation::Lookup { name, .. } => Some(name.as_bytes()), + _ => None, + }; let decide = |rows: SourceRows<'_>, source: BaseSource| { let mut facts = carried(&self.facts, source); let mut round = 0; diff --git a/engine/crates/layerfs-workspace/src/operations/namespace/list.rs b/engine/crates/layerfs-workspace/src/operations/namespace/list.rs index faf2c17213..500a82e852 100644 --- a/engine/crates/layerfs-workspace/src/operations/namespace/list.rs +++ b/engine/crates/layerfs-workspace/src/operations/namespace/list.rs @@ -1,7 +1,15 @@ //! Bounded three-way ordered name merge; deletion work advances its resume key. use crate::{OverlayRead, SourceView, WorkspaceResult}; +use layerfs_content::filesystem::limits::MAXIMUM_NAME_BYTES; +use layerfs_content::filesystem::sorted::format::{DIRECTORY_LEAF_SERIAL_BYTES, NAME_LENGTH_BYTES}; use layerfs_content::ContentError; use layerfs_overlay::{DirectoryEntry, DirectoryEntryWindow, PAGE_ROWS}; + +/// The bytes one base page may spend: what the directory reader charges a +/// row of the longest name, `PAGE_ROWS` times, so a page of any names holds +/// `PAGE_ROWS` rows and ends on its row bound rather than its byte bound. +const PAGE_BYTES: usize = + PAGE_ROWS * (NAME_LENGTH_BYTES + DIRECTORY_LEAF_SERIAL_BYTES + MAXIMUM_NAME_BYTES); #[derive(Clone, Debug, Eq, PartialEq)] pub struct ViewListing { pub entries: Vec<(Vec, u64)>, @@ -43,7 +51,7 @@ impl SourceView { } let base = if self.inherits(parent, local.parent_inode.as_ref())? { self.base - .list_after_bytes(parent, after, PAGE_ROWS, PAGE_ROWS * 264)? + .list_after_bytes(parent, after, PAGE_ROWS, PAGE_BYTES)? } else { layerfs_content::filesystem::DirectoryListing { entries: Vec::new(), @@ -70,6 +78,13 @@ impl SourceView { let mut visited = 0; let mut last = None; while visited < PAGE_ROWS { + // A base page that ended with a continuation says nothing about + // the names after its last one: a local key past it would skip + // the base names between. The window stops at that last name, + // and the next window resumes after it. + if b == base.entries.len() && base.continuation.is_some() { + break; + } let key = [ base.entries.get(b).map(|(name, _)| name.as_bytes()), local.active.get(a).map(|row| row.name.as_slice()), diff --git a/engine/crates/layerfs-workspace/src/operations/namespace/rename.rs b/engine/crates/layerfs-workspace/src/operations/namespace/rename.rs index 9815fe9b50..a31e855400 100644 --- a/engine/crates/layerfs-workspace/src/operations/namespace/rename.rs +++ b/engine/crates/layerfs-workspace/src/operations/namespace/rename.rs @@ -1,7 +1,7 @@ //! rename: one atomic move, with replacement, parent effects and cycle refusal. use crate::eval::{refuse, touched, Eval}; use crate::remove::{dereferenced, unbind}; -use crate::{Refusal, Time, WorkspaceResult}; +use crate::{Refusal, Time, WorkspaceError, WorkspaceResult}; use layerfs_content::filesystem::limits::MAXIMUM_PATH_COMPONENTS; use layerfs_content::filesystem::PathName; use layerfs_overlay::{Binding, Changes, DirectoryEntryChange, Inode, InodeKind}; @@ -22,14 +22,35 @@ pub(crate) struct Move<'a> { /// /// A kernel request carries serials only. Its evidence is the connection's /// retained parent index instead: one row per kernel-known directory, written -/// by the transactions that looked it up, created it or moved it, and read -/// here in the publishing job. It is engine state, not a caller's claim. +/// by the transactions that looked it up, created it or moved it, with the +/// name it had there, and read here in the publishing job. It is engine +/// state, not a caller's claim. An install never rewrites those rows, and a +/// merged install can move a directory the kernel still holds as a cwd or an +/// open descriptor without any LOOKUP refreshing its row. So every link of +/// the chain is checked against the current view in this job: its parent +/// must still bind its name to it. Directories have exactly one binding, so +/// a chain whose every link holds is the destination's whole current +/// ancestry. A link that no longer holds is refused as a mismatch (EINVAL); +/// the kernel's next LOOKUP of that directory records its current place. fn outside(eval: &mut Eval<'_>, moved: u64, action: &Move<'_>) -> WorkspaceResult> { if let Some((db, mount)) = eval.kernel { - if db - .kernel_ancestors(mount, action.new_parent)? - .contains(&moved) - { + let chain = db.kernel_ancestors(mount, action.new_parent)?; + let mut decided = true; + for link in &chain { + let name = PathName::from_bytes(&link.name) + .map_err(|_| WorkspaceError::Refused(Refusal::AncestryMismatch))?; + let local = eval.rows.inode(link.parent)?; + let layers = eval.layers(link.parent, &name)?; + match eval.bound(link.parent, local.as_ref(), &name, layers) { + None => decided = false, + Some(Some(serial)) if serial == link.serial => {} + Some(_) => return refuse(Refusal::AncestryMismatch), + } + } + if !decided { + return Ok(None); + } + if chain.iter().any(|link| link.serial == moved) { return refuse(Refusal::Invalid); } return Ok(Some(())); @@ -143,12 +164,13 @@ pub(crate) fn rename( inodes.push(dereferenced(old)); } // The moved inode keeps its serial and attributes: no row for it, and no - // row for anything beneath a moved directory. + // row for anything beneath a moved directory. A moved or renamed + // directory's retained kernel parent and name follow it. Ok(Some(Some(Changes { open: None, created: None, detached: None, - moved_directory: (moved.kind == InodeKind::Directory && !same) + moved_directory: (moved.kind == InodeKind::Directory) .then_some((moved.serial, action.new_parent)), inodes, directory_entries: vec![ diff --git a/engine/crates/layerfs-workspace/tests/kernel_data.rs b/engine/crates/layerfs-workspace/tests/kernel_data.rs index 9a2d7e86fb..ab4bc4dfa4 100644 --- a/engine/crates/layerfs-workspace/tests/kernel_data.rs +++ b/engine/crates/layerfs-workspace/tests/kernel_data.rs @@ -9,10 +9,12 @@ use common::name; use harness::{create, resize, write, Bench, T1}; use layerfs_content::filesystem::SymlinkTarget; use layerfs_overlay::{ - Inode, InodeKind, KernelDecision, KernelMount, StatementKind, StoredCounts, WorkspaceState, - READ_WINDOW, + Inode, InodeKind, KernelDecision, KernelMount, OverlayError, StatementKind, StoredCounts, + WorkspaceState, READ_WINDOW, +}; +use layerfs_workspace::{ + CanonicalCache, CanonicalClient, KernelWindow, Operation, Refusal, WorkspaceError, }; -use layerfs_workspace::{CanonicalCache, CanonicalClient, KernelWindow, Operation, Refusal}; use std::sync::Arc; const SMALL: &[u8] = b"original\0\xff"; @@ -57,7 +59,7 @@ fn hold(b: &Bench, mount: KernelMount, serial: u64, kind: InodeKind) { subdirs: 0, }; b.overlay - .observe_kernel_visit(mount, 1, None, true, |_, _| { + .observe_kernel_visit(mount, 1, None, Some(b"file"), |_, _| { Ok(KernelDecision::Finished { inode: Some(inode), value: (), @@ -165,13 +167,16 @@ fn every_window_is_the_ordinary_read_and_takes_the_base_only_for_what_it_inherit reply(&b, window, 3, 0, 4096, true), (Ok(TARGET.to_vec()), true) ); - // An inode the kernel holds that neither the base nor a local row has. + // An inode the kernel holds that neither the base nor a local row has: + // an install dropped its serial, so the kernel's handle is stale. The + // same one base read finds it, and the request alone fails with Stale. hold(&b, mount, 99, InodeKind::File); let window = visit(&b, empty(), mount, 99, 0, 4096); - assert_eq!( - reply(&b, window, 99, 0, 4096, false), - (Err(Refusal::Missing), true) - ); + assert!(window.inherits(0, false)); + assert!(matches!( + window.finish(Some(&base), 99, 0, 4096, false), + Err(WorkspaceError::Overlay(OverlayError::Stale)) + )); // Once the daemon has seen the files, memory answers the inode and the // length inside the job: a window at or beyond the end, and a refusal diff --git a/engine/crates/layerfs-workspace/tests/kernel_stale.rs b/engine/crates/layerfs-workspace/tests/kernel_stale.rs new file mode 100644 index 0000000000..0fef7ce997 --- /dev/null +++ b/engine/crates/layerfs-workspace/tests/kernel_stale.rs @@ -0,0 +1,485 @@ +//! What the kernel holds across an install that changed it, and listings +//! whose base page is cut short by long names. +//! +//! - A serial the kernel holds that an install dropped is stale for each +//! request that names it, and the Workspace keeps serving (finding #7). +//! - A kernel rename checks every retained parent of its destination against +//! the current view, so a directory an install moved cannot be made part of +//! a cycle through a stale parent row (finding #17). +//! - A directory of maximum-length base names with local names after them +//! lists every name exactly once, through the SDK and through READDIR +//! (finding #12). +mod common; +mod harness; +use common::name; +use harness::{rename, unlink, Bench, T1}; +use layerfs_content::{ + filesystem::{ + limits::MAXIMUM_NAME_BYTES, update_filesystem, DirectoryUpdate, FilesystemInput, + FilesystemObjects, FilesystemResources, PathName, + }, + ContentError, +}; +use layerfs_overlay::{Inode, KernelDirectory, KernelMount, OpenFile, OverlayError}; +use layerfs_workspace::{ + CanonicalCache, CanonicalClient, JobOutcome, KernelDirectoryRead, KernelInput, + KernelReadDecision, KernelReadOperation, KernelVisitRequest, Operation, Refusal, VisitFacts, + WorkspaceError, WorkspaceResult, +}; +use std::sync::Arc; + +/// A memory-only client over a cache that holds nothing. +fn empty() -> Arc { + Arc::new(CanonicalClient::resident(Arc::new(CanonicalCache::new( + 1 << 20, + )))) +} +fn lookup(parent: u64, child: &str) -> KernelReadOperation { + KernelReadOperation::Lookup { + parent, + name: name(child), + } +} +/// Installs the present base with `updates` as the next base, through the +/// actual canonical builder and install port, as a merged install does. +fn install(b: &Bench, updates: Vec) { + let store = &b.fixture.store; + let mut sink = store.clone(); + let mut objects = FilesystemObjects::new(store, &mut sink); + let next = update_filesystem( + &mut objects, + &FilesystemInput { + base: Some(b.workspace.base().unwrap().identity()), + scope: b.fixture.scope, + root_serial: 1, + directories: &updates, + inodes: &[], + new_inodes: &[], + resources: FilesystemResources::default(), + }, + None, + ) + .unwrap() + .root; + let capture = b.overlay.capture().unwrap(); + let prepared = b.workspace.prepare_base_install(capture, next).unwrap(); + b.workspace + .install_prepared_base(&b.overlay, prepared) + .unwrap(); +} +fn changes(parent: u64, names: &[(&str, Option)]) -> DirectoryUpdate { + DirectoryUpdate { + parent, + changes: names + .iter() + .map(|(child, serial)| (name(child), *serial)) + .collect(), + } +} +#[derive(Debug)] +enum Seen { + Value(Inode), + Refused(Refusal), + Stale, +} +/// One kernel read (LOOKUP, GETATTR, OPEN, OPENDIR) as owner visits until it +/// decides, reading the base facts an undecided visit names; with the +/// descriptor a decided OPEN or OPENDIR recorded. +fn read( + b: &Bench, + mount: KernelMount, + request: u64, + serial: u64, + operation: KernelReadOperation, +) -> (Seen, Option, Option) { + let mut facts = VisitFacts::default(); + for _ in 0..4 { + let shared = Arc::new(facts.clone()); + let visit = match operation { + KernelReadOperation::Open { writable, .. } => { + b.workspace + .kernel_open_visit(empty(), mount, request, serial, writable, shared) + } + KernelReadOperation::Opendir { .. } => { + b.workspace + .kernel_opendir_visit(empty(), mount, request, serial, shared) + } + _ => b.workspace.kernel_read_visit( + empty(), + mount, + serial, + None, + operation.clone(), + shared, + ), + } + .unwrap(); + let outcome = visit.perform(&b.overlay); + match (&outcome.result, &outcome.decision) { + (Err(OverlayError::Stale), None) => { + assert!(outcome.open_candidate.is_none()); + assert!(outcome.directory_candidate.is_none()); + return (Seen::Stale, None, None); + } + (Ok(None), Some(KernelReadDecision::Needs(needs))) => facts + .supply(&b.workspace.base().unwrap(), needs, None) + .unwrap(), + (Ok(None), Some(KernelReadDecision::Value(decided))) => { + return ( + Seen::Value(decided.inode.clone()), + outcome.open_candidate, + outcome.directory_candidate, + ) + } + (Ok(None), Some(KernelReadDecision::Refused { refusal, .. })) => { + return (Seen::Refused(*refusal), None, None) + } + _ => panic!("undecided kernel read {operation:?}: {outcome:?}"), + } + } + panic!("kernel read {operation:?} was not decided in four visits") +} +/// The decided inode of a kernel read that must decide one. +fn value(b: &Bench, mount: KernelMount, serial: u64, operation: KernelReadOperation) -> Inode { + match read(b, mount, 0, serial, operation.clone()).0 { + Seen::Value(inode) => inode, + other => panic!("{operation:?}: {other:?}"), + } +} +/// One kernel mutation named by the directory `serial`, as owner visits +/// until it decides; an applied one has its reply attempted. +fn mutate( + b: &Bench, + mount: KernelMount, + request: u64, + serial: u64, + operation: Operation, +) -> WorkspaceResult { + let mut facts = VisitFacts::default(); + for _ in 0..4 { + let visit = b + .workspace + .kernel_mutation_visit( + empty(), + KernelVisitRequest { + mount, + request, + serial, + handle: None, + input: KernelInput::Named(operation.clone()), + open: None, + now: T1, + fresh: None, + facts: Arc::new(facts.clone()), + }, + ) + .unwrap(); + match visit.perform(&b.overlay).result { + Ok(JobOutcome::Needs(needs)) => facts + .supply(&b.workspace.base().unwrap(), &needs, None) + .unwrap(), + Ok(JobOutcome::Applied { publication, inode }) => { + b.overlay.reply_attempted(publication).unwrap(); + return Ok(JobOutcome::Applied { publication, inode }); + } + other => return other, + } + } + panic!("kernel mutation {operation:?} was not decided in four visits") +} + +#[test] +fn a_serial_an_install_dropped_is_stale_for_each_kernel_request_and_the_mount_serves_on() { + let b = Bench::new("kernel-stale-dropped"); + let mount = b.overlay.create_kernel_mount(1).unwrap(); + // The kernel holds the directory `cache` (6) and the file `file` (2, + // also named `alias`), and has both open. + assert_eq!(value(&b, mount, 1, lookup(1, "cache")).serial, 6); + assert_eq!(value(&b, mount, 1, lookup(1, "file")).serial, 2); + let directory = read(&b, mount, 10, 6, KernelReadOperation::Opendir { serial: 6 }) + .2 + .expect("cache is open"); + let file = read( + &b, + mount, + 11, + 2, + KernelReadOperation::Open { + serial: 2, + writable: false, + }, + ) + .1 + .expect("file is open"); + // A merged install drops both serials: no name binds them any more. + install( + &b, + vec![changes( + 1, + &[("alias", None), ("cache", None), ("file", None)], + )], + ); + let base = b.workspace.base().unwrap(); + for serial in [2, 6] { + assert!( + matches!(base.inode(serial), Err(ContentError::PathNotFound)), + "serial {serial} is still in the installed base" + ); + assert_eq!(b.overlay.inode(serial).unwrap(), None); + } + + // Every kernel read of either serial is stale: GETATTR, a LOOKUP in the + // dropped directory, OPENDIR and OPEN. + for (request, serial, operation) in [ + (20, 6, KernelReadOperation::Getattr { serial: 6 }), + (21, 6, lookup(6, "state")), + (22, 6, KernelReadOperation::Opendir { serial: 6 }), + (23, 2, KernelReadOperation::Getattr { serial: 2 }), + ( + 24, + 2, + KernelReadOperation::Open { + serial: 2, + writable: false, + }, + ), + ] { + let seen = read(&b, mount, request, serial, operation.clone()).0; + assert!(matches!(seen, Seen::Stale), "{operation:?}: {seen:?}"); + } + // READ through the descriptor opened before the install: the one base + // read finds no inode at the root the visit named. + let window = b + .workspace + .kernel_data_visit(empty(), mount, 2, Some(file.owner_id()), 0, 4096) + .unwrap() + .perform(&b.overlay) + .unwrap(); + assert!(window.local.is_none() && window.inherits(0, false)); + assert!(matches!( + window.finish(Some(&base), 2, 0, 4096, false), + Err(WorkspaceError::Overlay(OverlayError::Stale)) + )); + // READDIR through the handle opened before the install. + let window = b + .workspace + .kernel_directory_visit( + empty(), + mount, + 6, + directory.owner_id(), + KernelDirectoryRead { + offset: 2, + after: None, + attributes: false, + }, + ) + .unwrap() + .perform(&b.overlay) + .unwrap(); + assert!(matches!( + window.finish(Some(&base)), + Err(WorkspaceError::Overlay(OverlayError::Stale)) + )); + + // Nothing was retained or poisoned: the same mount keeps serving reads + // and mutations. + assert_eq!( + value(&b, mount, 1, KernelReadOperation::Getattr { serial: 1 }).serial, + 1 + ); + assert_eq!(value(&b, mount, 1, lookup(1, "node_modules")).serial, 5); + assert!(matches!( + read(&b, mount, 30, 1, lookup(1, "cache")).0, + Seen::Refused(Refusal::Missing) + )); + assert!(matches!( + mutate(&b, mount, 31, 1, unlink(1, "symlink")), + Ok(JobOutcome::Applied { .. }) + )); + assert_eq!(b.lookup(1, "symlink"), None); + b.overlay + .kernel_close_file(mount, 2, file.owner_id()) + .unwrap(); + b.overlay + .close_kernel_directory(mount, 6, directory.owner_id()) + .unwrap(); + b.overlay.revoke_kernel_mount(mount).unwrap(); +} + +#[test] +fn a_kernel_rename_checks_each_retained_parent_against_the_current_view() { + let b = Bench::new("kernel-stale-parents"); + let mount = b.overlay.create_kernel_mount(1).unwrap(); + // The kernel looks up `cache` (6) and `output` (7) at the root. + assert_eq!(value(&b, mount, 1, lookup(1, "cache")).serial, 6); + assert_eq!(value(&b, mount, 1, lookup(1, "output")).serial, 7); + // A merged install moves `output` under `cache` as `y`; it keeps its + // serial, and nothing tells the kernel's parent index. + install( + &b, + vec![ + changes(1, &[("output", None)]), + changes(6, &[("y", Some(7))]), + ], + ); + assert_eq!(b.lookup(6, "y").unwrap().serial, 7); + assert_eq!(b.lookup(1, "output"), None); + + // rename(/cache, /cache/y/x2) through a handle on 7 that the kernel + // still has from the root. The retained row says 7 is `output` at the + // root; the view disagrees, so the rename is refused and moves nothing. + let cycle = || rename((1, "cache"), (7, "x2"), false, None); + assert!(matches!( + mutate(&b, mount, 40, 1, cycle()), + Ok(JobOutcome::Refused(Refusal::AncestryMismatch)) + )); + assert_eq!(b.lookup(1, "cache").unwrap().serial, 6); + assert_eq!(b.lookup(7, "x2"), None); + // A LOOKUP of 7 at its new place records it there: the same rename is + // now a proven cycle. + assert_eq!(value(&b, mount, 6, lookup(6, "y")).serial, 7); + assert!(matches!( + mutate(&b, mount, 41, 1, cycle()), + Ok(JobOutcome::Refused(Refusal::Invalid)) + )); + assert_eq!(b.lookup(1, "cache").unwrap().serial, 6); + // A directory that is not above 7 moves into it. + assert!(matches!( + mutate( + &b, + mount, + 42, + 1, + rename((1, "node_modules"), (7, "nm"), false, None) + ), + Ok(JobOutcome::Applied { .. }) + )); + assert_eq!(b.lookup(7, "nm").unwrap().serial, 5); + // A rename in place moves the retained name with the directory: after + // `y` becomes `y2`, the chain 7 -> 6 -> root still checks out. + assert!(matches!( + mutate(&b, mount, 43, 6, rename((6, "y"), (6, "y2"), false, None)), + Ok(JobOutcome::Applied { .. }) + )); + assert!(matches!( + mutate( + &b, + mount, + 44, + 1, + rename((1, ".git"), (7, "git"), false, None) + ), + Ok(JobOutcome::Applied { .. }) + )); + assert_eq!(b.lookup(7, "git").unwrap().serial, 4); + // And moving `cache` under its own descendant is still a cycle. + assert!(matches!( + mutate(&b, mount, 45, 1, cycle()), + Ok(JobOutcome::Refused(Refusal::Invalid)) + )); + b.overlay.revoke_kernel_mount(mount).unwrap(); +} + +/// `count` base names of the maximum length, all sorting after `.git` and +/// `alias` and before every other fixture name. +fn long_names(count: usize) -> Vec { + (0..count) + .map(|n| format!("b{n:0>width$}", width = MAXIMUM_NAME_BYTES - 1)) + .collect() +} + +#[test] +fn maximum_length_base_names_with_local_names_after_them_are_each_listed_once() { + let b = Bench::new("kernel-stale-long-names"); + // More maximum-length names than one base page of PAGE_ROWS rows would + // hold if a row were charged less than its full width. + let long = long_names(1_100); + install( + &b, + vec![DirectoryUpdate { + parent: 1, + changes: long + .iter() + .map(|child| (PathName::new(child).unwrap(), Some(2))) + .collect(), + }], + ); + // Local names after every long one, and one removed among them. + for child in ["zz-local-a", "zz-local-b"] { + b.applied(harness::create(1, child), T1); + } + b.applied(unlink(1, &long[1_050]), T1); + let mut expected: Vec = [ + ".git", + "alias", + "cache", + "file", + "node_modules", + "output", + "symlink", + "zz-local-a", + "zz-local-b", + ] + .into_iter() + .map(String::from) + .chain(long.iter().cloned()) + .filter(|child| *child != long[1_050]) + .collect(); + expected.sort(); + + // SDK listing: bounded windows, each name exactly once, in order. + assert_eq!(b.names(1), expected); + + // Kernel READDIR: each reply publishes what it lists, and the next + // request resumes at the last offset handed out. + let mount = b.overlay.create_kernel_mount(1).unwrap(); + let directory = read(&b, mount, 50, 1, KernelReadOperation::Opendir { serial: 1 }) + .2 + .expect("the root is open"); + let base = b.workspace.base().unwrap(); + let mut listed = Vec::new(); + let (mut offset, mut after) = (2, None); + for _ in 0..64 { + let batch = b + .workspace + .kernel_directory_visit( + empty(), + mount, + 1, + directory.owner_id(), + KernelDirectoryRead { + offset, + after: after.take(), + attributes: false, + }, + ) + .unwrap() + .perform(&b.overlay) + .unwrap() + .finish(Some(&base)) + .unwrap(); + if batch.entries.is_empty() { + match batch.continuation { + Some(next) => { + after = Some(next); + continue; + } + None => break, + } + } + let names: Vec> = batch.entries.iter().map(|e| e.name.clone()).collect(); + let offer = batch.publish.expect("a fresh reply publishes its names"); + b.overlay.publish_kernel_cookies(&offer, &names).unwrap(); + listed.extend(names.iter().map(|n| String::from_utf8(n.clone()).unwrap())); + if batch.exhausted { + break; + } + offset = batch.first + names.len() as u64 - 1; + } + assert_eq!(listed, expected); + b.overlay + .close_kernel_directory(mount, 1, directory.owner_id()) + .unwrap(); + b.overlay.revoke_kernel_mount(mount).unwrap(); +}