Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/continuum-rust-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,12 @@ jobs:
if: fromJSON(needs.changes.outputs.lib_tests)[matrix.crate]
run: cargo test --locked -p "$CRATE" --lib --profile dev-fast --features "$FEATURES"

# ---- continuum-pack: the base layer's load/store keeps its compiler lock (no unwrap, expect or
# panic outside tests; lib.rs) and lint-clean, with its derive; the --lib step above built it ----
- name: cargo clippy -p continuum-pack -p continuum-pack-derive
if: matrix.crate == 'continuum-pack'
run: cargo clippy --locked -p continuum-pack -p continuum-pack-derive --profile dev-fast --all-targets --features continuum-pack/conformance -- -D warnings

# ---- continuum-mind: lib tests, compile-fail doc guards ----
- name: cargo test -p continuum-mind --lib
if: matrix.crate == 'continuum-mind'
Expand Down
25 changes: 25 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 8 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ members = [
"core/continuum-cli-lifecycle",
"core/continuum-tool-protocol",
"core/continuum-base",
"core/continuum-pack",
"core/continuum-pack-derive",
"core/continuum-git",
"core/continuum-host",
"core/continuum-context",
Expand Down Expand Up @@ -282,6 +284,11 @@ candle-core = { version = "0.9" }
candle-nn = { version = "0.9" }
candle-transformers = { version = "0.9" }

# The base layer's one load/store (docs/architecture/PACKAGES.md): any crate packs its state
# with `continuum-pack.workspace = true` (trait, derive, stores; `features = ["conformance"]`
# in dev-dependencies for the generic suite).
continuum-pack = { path = "core/continuum-pack" }

# Serialization
serde = { version = "1", features = ["derive"] }
serde_json = "1"
Expand Down Expand Up @@ -509,7 +516,7 @@ longest_first = [
]
# Audited with their crate name as a path prefix (`continuum-base/time/mod.rs`), not unprefixed
# like the modules cut out of core (source-hygiene lib.rs `audited_files`).
split_prefixed = ["continuum-base"]
split_prefixed = ["continuum-base", "continuum-pack", "continuum-pack-derive"]
# Tested but in no per-file ratchet yet (card 996e3537).
unaudited = ["continuum-host"]
# Not counted by the warnings ratchet yet: base (a split crate outside the count), kernel (~13
Expand Down
17 changes: 14 additions & 3 deletions core/continuum-host/src/durable/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Durable placement: a file placed here survives a crash or power loss whole, or the call fails.
//! Durable placement: a file (or directory) placed here survives a crash or power loss whole, or the call fails.
//! Every write-then-rename in the core goes through `replace` (a mutable file) or `publish_new`
//! (an immutable, content-addressed one); a caller never renames and syncs by hand.
//!
Expand Down Expand Up @@ -70,7 +70,18 @@ pub fn fence(file: &File, path: &Path) -> io::Result<()> {
os::sync_entries(parent(path)?)
}

/// Creates the directory `dir` (its parent must exist) so its entry survives power loss. An
/// existing directory is `AlreadyExists`, as from `std::fs::create_dir`.
pub fn create_dir(dir: &Path) -> io::Result<()> {
std::fs::create_dir(dir)?;
os::sync_entries(parent(dir)?)
}

/// The directory holding `path`; a bare relative name lives in the current directory.
fn parent(path: &Path) -> io::Result<&Path> {
path.parent()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{} has no parent directory", path.display())))
match path.parent() {
Some(p) if p.as_os_str().is_empty() => Ok(Path::new(".")),
Some(p) => Ok(p),
None => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{} has no parent directory", path.display()))),
}
}
11 changes: 11 additions & 0 deletions core/continuum-host/src/durable/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,14 @@ fn publish_new_refuses_an_occupied_address_and_a_failed_fence_is_an_error() {
fault_injection::with_failed_fence(|| assert!(fence(&file, &free).is_err()));
fence(&file, &free).unwrap();
}

// what this catches: a durable directory creation creates the entry and reports an existing one
// as AlreadyExists (a racing creator relies on that kind), on this platform's sync arm.
#[test]
fn create_dir_creates_once_and_an_existing_one_is_already_exists() {
let dir = tempfile::tempdir().unwrap();
let made = dir.path().join("objects");
create_dir(&made).unwrap();
assert!(made.is_dir());
assert_eq!(create_dir(&made).unwrap_err().kind(), io::ErrorKind::AlreadyExists);
}
13 changes: 13 additions & 0 deletions core/continuum-pack-derive/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "continuum-pack-derive"
version = "0.1.0"
edition = "2021"
description = "#[derive(Packable)] for continuum-pack: one line per type, #[pack(...)] attributes name each field's part (field, blob, child, requires)."

[lib]
proc-macro = true

[dependencies]
proc-macro2 = "1"
quote = "1"
syn = { version = "2", features = ["full"] }
146 changes: 146 additions & 0 deletions core/continuum-pack-derive/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
//! `#[derive(Packable)]`: one line per type. Struct attribute
//! `#[pack(kind = "gene", schema = 3, migrate = GENE_MIGRATIONS)]` (migrate optional, an
//! expression of type `&'static [continuum_pack::Migration]`); field attributes name each
//! field's part: `#[pack(blob = "media/type")]` (a `Blob`), `#[pack(child)]` (a `Handle<T>`
//! or `Vec<Handle<T>>`), `#[pack(requires)]` (a `Required`); an unmarked field is a `field`.

use proc_macro::TokenStream;
use proc_macro2::TokenStream as Tokens;
use quote::quote;
use syn::{parse_macro_input, Data, DeriveInput, Expr, Fields, Ident, LitInt, LitStr};

#[proc_macro_derive(Packable, attributes(pack))]
pub fn derive_packable(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
match expand(&input) {
Ok(tokens) => tokens.into(),
Err(e) => e.into_compile_error().into(),
}
}

enum Role {
Field,
Blob(LitStr),
Child,
Requires,
}

fn expand(input: &DeriveInput) -> syn::Result<Tokens> {
if !input.generics.params.is_empty() {
return Err(syn::Error::new_spanned(
&input.generics,
"Packable cannot be derived for a generic type; write pack/unpack by hand",
));
}
let Data::Struct(data) = &input.data else {
return Err(syn::Error::new_spanned(
&input.ident,
"Packable can be derived only for a struct with named fields",
));
};
let Fields::Named(named) = &data.fields else {
return Err(syn::Error::new_spanned(
&input.ident,
"Packable can be derived only for a struct with named fields",
));
};

let (mut kind, mut schema, mut migrate): (Option<LitStr>, Option<LitInt>, Option<Expr>) =
(None, None, None);
for attr in input.attrs.iter().filter(|a| a.path().is_ident("pack")) {
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("kind") {
kind = Some(meta.value()?.parse()?);
} else if meta.path.is_ident("schema") {
schema = Some(meta.value()?.parse()?);
} else if meta.path.is_ident("migrate") {
migrate = Some(meta.value()?.parse()?);
} else {
return Err(meta.error("expected `kind`, `schema` or `migrate`"));
}
Ok(())
})?;
}
let kind = kind
.ok_or_else(|| syn::Error::new_spanned(&input.ident, "missing #[pack(kind = \"...\")]"))?;
let schema = schema
.ok_or_else(|| syn::Error::new_spanned(&input.ident, "missing #[pack(schema = N)]"))?;
let schema_n: u32 = schema.base10_parse()?;
if schema_n == 0 {
return Err(syn::Error::new_spanned(&schema, "schemas start at 1"));
}

let mut packs = Vec::new();
let mut unpacks = Vec::new();
for field in &named.named {
let Some(ident) = field.ident.as_ref() else {
return Err(syn::Error::new_spanned(field, "unnamed field"));
};
let name = ident.to_string();
let (pack, unpack) = match role(field, ident)? {
Role::Field => (
quote! { p.field(#name, &self.#ident)?; },
quote! { u.field(#name)? },
),
Role::Blob(media) => (
quote! { p.blob_value(#name, #media, &self.#ident)?; },
quote! { u.blob(#name, #media)? },
),
Role::Child => (
quote! { ::continuum_pack::ChildPart::pack_part(&self.#ident, #name, p)?; },
quote! { ::continuum_pack::ChildPart::unpack_part(#name, u)? },
),
Role::Requires => (
quote! { p.requires(#name, ::continuum_pack::Required::to_requirement(&self.#ident))?; },
quote! { ::continuum_pack::Required::from_requirement(#name, u.requirement(#name)?)? },
),
};
packs.push(pack);
unpacks.push(quote! { #ident: #unpack });
}

let ty = &input.ident;
let migrations = migrate.map(|m| {
quote! {
fn migrations() -> &'static [::continuum_pack::Migration] { #m }
}
});
Ok(quote! {
impl ::continuum_pack::Packable for #ty {
const KIND: ::continuum_pack::Kind = ::continuum_pack::Kind::new(#kind, #schema_n);
type Context = ();
fn pack(&self, p: &mut ::continuum_pack::Packer<'_>) -> ::core::result::Result<(), ::continuum_pack::PackError> {
#(#packs)*
::core::result::Result::Ok(())
}
fn unpack(u: &mut ::continuum_pack::Unpacker<'_>, _cx: &()) -> ::core::result::Result<Self, ::continuum_pack::PackError> {
::core::result::Result::Ok(Self { #(#unpacks),* })
}
#migrations
}
})
}

fn role(field: &syn::Field, ident: &Ident) -> syn::Result<Role> {
let mut role = Role::Field;
let mut seen = false;
for attr in field.attrs.iter().filter(|a| a.path().is_ident("pack")) {
attr.parse_nested_meta(|meta| {
if seen {
return Err(meta.error(format!("field `{ident}` names more than one part role")));
}
seen = true;
if meta.path.is_ident("blob") {
role = Role::Blob(meta.value()?.parse()?);
} else if meta.path.is_ident("child") {
role = Role::Child;
} else if meta.path.is_ident("requires") {
role = Role::Requires;
} else {
return Err(meta.error("expected `blob = \"media/type\"`, `child` or `requires`"));
}
Ok(())
})?;
}
Ok(role)
}
27 changes: 27 additions & 0 deletions core/continuum-pack/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
[package]
name = "continuum-pack"
version = "0.1.0"
edition = "2021"
description = "One load/store layer for everything a mind owns: a type says WHAT it is (Packable), a store says WHERE bytes go (Store); content-addressed Merkle DAG, one ref flip per commit (docs/architecture/PACKAGES.md)."

[dependencies]
bytes = "1"
continuum-base = { path = "../continuum-base" }
# durable placement of blobs, refs and directories (the OS seam).
continuum-host = { path = "../continuum-host" }
continuum-pack-derive = { path = "../continuum-pack-derive" }
serde = { workspace = true }
# float_roundtrip: a manifest float must parse to the nearest double, or a load/re-save moves its id.
serde_json = { workspace = true, features = ["float_roundtrip"] }
sha2 = { workspace = true }
thiserror = { workspace = true }
# continuum_base::probe! expands to ::tracing::event!.
tracing = { workspace = true }

[features]
# FaultStore and the generic conformance suite (pack::conformance), for this crate's tests and the
# tests of every crate whose types implement Packable; production binaries never link it.
conformance = []

[dev-dependencies]
tempfile = "3"
Loading
Loading