diff --git a/AGENTS.md b/AGENTS.md index 877029a8e..c1a54ca68 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -137,7 +137,7 @@ or `solverforge-solver` differs from `crates//public-api.txt`. A change that adds, removes or changes a public item regenerates that snapshot with `python3 scripts/check-public-api.py --bless` in the same commit, so review sees the surface change. Inside those crates, `pub` means supported surface: -`#![warn(unreachable_pub)]` is on, implementation modules are private, and +`unreachable_pub = "warn"` is set in their Cargo `[lints]` tables, implementation modules are private, and `solverforge-solver` exports every supported item once, at its root. When a public API change also affects how users discover or reason about the @@ -357,15 +357,22 @@ Avoid `#[derive(Clone)]` on generic types when it would introduce unnecessary bo ## Code Organization -- Keep `mod.rs` files limited to module declarations and re-exports. +- Keep every `mod.rs` and `lib.rs` limited to module declarations and `use` + re-exports: no functions, types, impls, constants, macro definitions, + inline module bodies or crate-level attributes. `planning_model!` + manifests and the proc-macro entry points Rust requires in + `solverforge-macros/src/lib.rs` are the only exceptions; lint levels live in + each crate's Cargo `[lints]` table. - Crate roots document the crate with inner `//!` doc comments and public items use `///` (or `/** */`); plain `//` and `/* */` comments never replace them. docs.rs renders only doc comments, so a comment-style sweep must leave them in place. Every crate in the workspace (`solverforge`, `solverforge-core`, `solverforge-config`, `solverforge-scoring`, `solverforge-solver`, `solverforge-console`, `solverforge-macros`, - `solverforge-bridge` and `solverforge-cvrp`) warns on `missing_docs`, so - every new public item needs a doc comment. + `solverforge-bridge` and `solverforge-cvrp`) warns on `missing_docs` through + its Cargo `[lints]` table, which also covers its integration tests, so + every new public item, test crate root and test fixture needs a doc + comment. - Move implementation code into dedicated files. - Keep Rust source and test files under 500 LOC. When a module grows beyond that boundary, split it by subsystem or behavior into adjacent implementation diff --git a/crates/solverforge-bridge/Cargo.toml b/crates/solverforge-bridge/Cargo.toml index 3e27b0aa4..700a62065 100644 --- a/crates/solverforge-bridge/Cargo.toml +++ b/crates/solverforge-bridge/Cargo.toml @@ -15,3 +15,6 @@ solverforge-config = { version = "=0.25.1", path = "../solverforge-config" } solverforge-core = { version = "=0.25.1", path = "../solverforge-core" } solverforge-scoring = { version = "=0.25.1", path = "../solverforge-scoring" } solverforge-solver = { version = "=0.25.1", path = "../solverforge-solver" } + +[lints.rust] +missing_docs = "warn" diff --git a/crates/solverforge-bridge/src/lib.rs b/crates/solverforge-bridge/src/lib.rs index ad0383cd4..07152c60e 100644 --- a/crates/solverforge-bridge/src/lib.rs +++ b/crates/solverforge-bridge/src/lib.rs @@ -6,8 +6,6 @@ //! dynamic state without pretending that one host-language entity class maps to //! one concrete Rust entity type. -#![warn(missing_docs)] - mod backend; mod ids; mod runner; diff --git a/crates/solverforge-config/Cargo.toml b/crates/solverforge-config/Cargo.toml index 83c14fe7b..cd39e9cc7 100644 --- a/crates/solverforge-config/Cargo.toml +++ b/crates/solverforge-config/Cargo.toml @@ -14,3 +14,6 @@ description = "Configuration system for SolverForge constraint solver" serde.workspace = true toml.workspace = true thiserror.workspace = true + +[lints.rust] +missing_docs = "warn" diff --git a/crates/solverforge-config/src/lib.rs b/crates/solverforge-config/src/lib.rs index fca75bc24..8b5add399 100644 --- a/crates/solverforge-config/src/lib.rs +++ b/crates/solverforge-config/src/lib.rs @@ -41,8 +41,6 @@ //! } //! ``` -#![warn(missing_docs)] - mod acceptor; mod director; mod error; diff --git a/crates/solverforge-console/Cargo.toml b/crates/solverforge-console/Cargo.toml index f4d389ca8..426281da0 100644 --- a/crates/solverforge-console/Cargo.toml +++ b/crates/solverforge-console/Cargo.toml @@ -18,3 +18,6 @@ num-format = "0.4.4" [features] verbose-logging = [] + +[lints.rust] +missing_docs = "warn" diff --git a/crates/solverforge-console/src/lib.rs b/crates/solverforge-console/src/lib.rs index 1af6c7318..0db80e5f2 100644 --- a/crates/solverforge-console/src/lib.rs +++ b/crates/solverforge-console/src/lib.rs @@ -8,8 +8,6 @@ //! - **DEBUG**: Progress updates (1/sec with speed and score) //! - **TRACE**: Individual step evaluations -#![warn(missing_docs)] - mod banner; mod format; mod init; diff --git a/crates/solverforge-core/Cargo.toml b/crates/solverforge-core/Cargo.toml index a973f5165..ecf8cdece 100644 --- a/crates/solverforge-core/Cargo.toml +++ b/crates/solverforge-core/Cargo.toml @@ -20,3 +20,10 @@ serde = { workspace = true, optional = true } [dev-dependencies] toml.workspace = true + +[lints.rust] +missing_docs = "warn" +unreachable_pub = "warn" + +[lints.clippy] +type_complexity = "allow" diff --git a/crates/solverforge-core/WIREFRAME.md b/crates/solverforge-core/WIREFRAME.md index 9945cff1c..c42c5e695 100644 --- a/crates/solverforge-core/WIREFRAME.md +++ b/crates/solverforge-core/WIREFRAME.md @@ -66,7 +66,8 @@ src/ │ │ ├── problem_fact.rs — ProblemFactDescriptor struct │ │ ├── var_descriptor.rs — VariableDescriptor struct │ │ └── tests/ -│ │ ├── mod.rs — Shared test helpers and module declarations +│ │ ├── mod.rs — Test module declarations and shared imports +│ │ ├── fixtures.rs — Shared TestEntity/TestSolution fixtures and entity descriptor builder │ │ ├── entity_descriptor.rs — EntityDescriptor tests │ │ ├── solution_descriptor.rs — SolutionDescriptor tests │ │ └── variable_descriptor.rs — VariableDescriptor tests diff --git a/crates/solverforge-core/src/domain/descriptor/tests/fixtures.rs b/crates/solverforge-core/src/domain/descriptor/tests/fixtures.rs new file mode 100644 index 000000000..cec2f8d15 --- /dev/null +++ b/crates/solverforge-core/src/domain/descriptor/tests/fixtures.rs @@ -0,0 +1,39 @@ +//! Shared descriptor test fixtures: a one-variable entity and its solution. + +use crate::domain::descriptor::*; +use crate::domain::EntityCollectionExtractor; + +#[derive(Clone, Debug)] +pub(super) struct TestEntity { + pub id: i64, + pub row: Option, +} + +#[derive(Clone, Debug)] +pub(super) struct TestSolution { + pub entities: Vec, +} + +pub(super) fn get_entities(s: &TestSolution) -> &Vec { + &s.entities +} + +pub(super) fn get_entities_mut(s: &mut TestSolution) -> &mut Vec { + &mut s.entities +} + +pub(super) fn create_test_entity_descriptor() -> EntityDescriptor { + let extractor = Box::new(EntityCollectionExtractor::new( + "TestEntity", + "entities", + get_entities, + get_entities_mut, + )); + + EntityDescriptor::new( + "TestEntity", + std::any::TypeId::of::(), + "entities", + ) + .with_extractor(extractor) +} diff --git a/crates/solverforge-core/src/domain/descriptor/tests/mod.rs b/crates/solverforge-core/src/domain/descriptor/tests/mod.rs index 4eebe290a..e93823f80 100644 --- a/crates/solverforge-core/src/domain/descriptor/tests/mod.rs +++ b/crates/solverforge-core/src/domain/descriptor/tests/mod.rs @@ -1,46 +1,11 @@ // Tests for descriptor types. mod entity_descriptor; +mod fixtures; mod solution_descriptor; mod variable_descriptor; use crate::domain::descriptor::*; use crate::domain::EntityCollectionExtractor; +use fixtures::*; use std::any::Any; - -// Shared test helpers used across descriptor test modules. - -#[derive(Clone, Debug)] -pub(super) struct TestEntity { - pub id: i64, - pub row: Option, -} - -#[derive(Clone, Debug)] -pub(super) struct TestSolution { - pub entities: Vec, -} - -pub(super) fn get_entities(s: &TestSolution) -> &Vec { - &s.entities -} - -pub(super) fn get_entities_mut(s: &mut TestSolution) -> &mut Vec { - &mut s.entities -} - -pub(super) fn create_test_entity_descriptor() -> EntityDescriptor { - let extractor = Box::new(EntityCollectionExtractor::new( - "TestEntity", - "entities", - get_entities, - get_entities_mut, - )); - - EntityDescriptor::new( - "TestEntity", - std::any::TypeId::of::(), - "entities", - ) - .with_extractor(extractor) -} diff --git a/crates/solverforge-core/src/lib.rs b/crates/solverforge-core/src/lib.rs index d1adb39da..6fea9da4b 100644 --- a/crates/solverforge-core/src/lib.rs +++ b/crates/solverforge-core/src/lib.rs @@ -11,9 +11,6 @@ trait bounds from phantom type parameters. Clippy's type_complexity lint triggers on these tuples but the pattern is architecturally required. */ -#![allow(clippy::type_complexity)] -#![warn(missing_docs)] -#![warn(unreachable_pub)] pub mod constraint; pub mod constraint_weights; diff --git a/crates/solverforge-cvrp/Cargo.toml b/crates/solverforge-cvrp/Cargo.toml index 92312e38f..35b098018 100644 --- a/crates/solverforge-cvrp/Cargo.toml +++ b/crates/solverforge-cvrp/Cargo.toml @@ -12,3 +12,6 @@ description = "CVRP domain helpers for SolverForge" [dependencies] solverforge-solver = { version = "=0.25.1", path = "../solverforge-solver" } + +[lints.rust] +missing_docs = "warn" diff --git a/crates/solverforge-cvrp/src/lib.rs b/crates/solverforge-cvrp/src/lib.rs index 0c241a8a9..c8525466a 100644 --- a/crates/solverforge-cvrp/src/lib.rs +++ b/crates/solverforge-cvrp/src/lib.rs @@ -4,8 +4,6 @@ //! the `VrpSolution` trait, and the stock helpers behind //! `#[planning_list_variable(domain = "cvrp")]`. -#![warn(missing_docs)] - mod helpers; mod meters; mod problem_data; diff --git a/crates/solverforge-macros/Cargo.toml b/crates/solverforge-macros/Cargo.toml index f61b83a51..00d06e66a 100644 --- a/crates/solverforge-macros/Cargo.toml +++ b/crates/solverforge-macros/Cargo.toml @@ -21,3 +21,6 @@ proc-macro2.workspace = true [dev-dependencies] solverforge = { path = "../solverforge" } trybuild = "1.0.116" + +[lints.rust] +missing_docs = "warn" diff --git a/crates/solverforge-macros/src/lib.rs b/crates/solverforge-macros/src/lib.rs index b7e7d4e0e..26c80d956 100644 --- a/crates/solverforge-macros/src/lib.rs +++ b/crates/solverforge-macros/src/lib.rs @@ -5,8 +5,6 @@ //! `#[problem_fact]` and `#[solverforge_constraints]`; the generated code //! refers to `::solverforge` paths. -#![warn(missing_docs)] - use proc_macro::TokenStream; mod attr_parse; diff --git a/crates/solverforge-macros/tests/trybuild.rs b/crates/solverforge-macros/tests/trybuild.rs index 3b0f588b8..4e5f339f0 100644 --- a/crates/solverforge-macros/tests/trybuild.rs +++ b/crates/solverforge-macros/tests/trybuild.rs @@ -1,3 +1,5 @@ +//! Compile-pass and compile-fail cases for the SolverForge procedural macros. + use std::path::Path; #[test] diff --git a/crates/solverforge-scoring/Cargo.toml b/crates/solverforge-scoring/Cargo.toml index 2de41f4d5..f6f2a5a95 100644 --- a/crates/solverforge-scoring/Cargo.toml +++ b/crates/solverforge-scoring/Cargo.toml @@ -12,3 +12,11 @@ description = "Incremental constraint scoring for SolverForge" [dependencies] solverforge-core = { version = "=0.25.1", path = "../solverforge-core" } + +[lints.rust] +unreachable_pub = "warn" +missing_docs = "warn" +unsafe_code = "forbid" + +[lints.clippy] +type_complexity = "allow" diff --git a/crates/solverforge-scoring/WIREFRAME.md b/crates/solverforge-scoring/WIREFRAME.md index 8b2e5e402..2b5a5b034 100644 --- a/crates/solverforge-scoring/WIREFRAME.md +++ b/crates/solverforge-scoring/WIREFRAME.md @@ -271,7 +271,10 @@ src/ │ ├── tri_stream.rs — TriConstraintStream, TriConstraintBuilder (via macro) │ ├── quad_stream.rs — QuadConstraintStream, QuadConstraintBuilder (via macro) │ ├── penta_stream.rs — PentaConstraintStream, PentaConstraintBuilder (via macro) +│ ├── chain.rs — Public `stream::chain` re-exports of Chain and ChainBuilder │ ├── chain_stream.rs — Chain/ChainBuilder: arity-free fluent join continuation +│ ├── cross.rs — Public `stream::cross` re-exports of the cross-join streams and builders +│ ├── projected.rs — Public `stream::projected` re-exports of the projected streams and builders │ ├── cross_penta_stream.rs — stream::cross::Penta and its Penta::join → Chain │ ├── cross_penta_stream/scored.rs — PentaScored operator (tree plus authored filter) │ ├── grouped_stream.rs — Re-exports @@ -314,7 +317,8 @@ src/ │ ├── join_target.rs — JoinTarget/ToViewPlan dispatch for self-join, keyed cross-join, comparison, overlap, composed, and predicate cross-join │ ├── key_extract.rs — KeyExtract trait, EntityKeyAdapter struct │ ├── arity_stream_macros/ -│ │ ├── mod.rs — impl_arity_stream! dispatcher macro +│ │ ├── mod.rs — Module declarations; re-exports impl_arity_stream! +│ │ ├── dispatch.rs — impl_arity_stream! dispatcher macro │ │ ├── nary_stream.rs — Module declarations for arity stream macros │ │ └── nary_stream/ │ │ ├── shared.rs — Shared arity stream macro helpers diff --git a/crates/solverforge-scoring/src/lib.rs b/crates/solverforge-scoring/src/lib.rs index 0c3e6c05c..cc17cd2d5 100644 --- a/crates/solverforge-scoring/src/lib.rs +++ b/crates/solverforge-scoring/src/lib.rs @@ -15,10 +15,6 @@ //! there is no `Box` on the scoring path. // Zero-erasure architecture intentionally uses complex generic types -#![allow(clippy::type_complexity)] -#![warn(unreachable_pub)] -#![warn(missing_docs)] -#![forbid(unsafe_code)] // Core modules pub mod api; diff --git a/crates/solverforge-scoring/src/stream/arity_stream_macros/dispatch.rs b/crates/solverforge-scoring/src/stream/arity_stream_macros/dispatch.rs new file mode 100644 index 000000000..5d50f16b3 --- /dev/null +++ b/crates/solverforge-scoring/src/stream/arity_stream_macros/dispatch.rs @@ -0,0 +1,23 @@ +//! `impl_arity_stream!`: picks the per-arity stream macro for a tuple size. + +/* Generates the constraint stream struct, builder struct, and common methods. + +Doctests and unique methods (should be defined outside the macro +in the individual stream files. +*/ +macro_rules! impl_arity_stream { + (bi, $stream:ident, $builder:ident) => { + impl_bi_arity_stream!($stream, $builder); + }; + (tri, $stream:ident, $builder:ident) => { + impl_tri_arity_stream!($stream, $builder); + }; + (quad, $stream:ident, $builder:ident) => { + impl_quad_arity_stream!($stream, $builder); + }; + (penta, $stream:ident, $builder:ident) => { + impl_penta_arity_stream!($stream, $builder); + }; +} + +pub(crate) use impl_arity_stream; diff --git a/crates/solverforge-scoring/src/stream/arity_stream_macros/mod.rs b/crates/solverforge-scoring/src/stream/arity_stream_macros/mod.rs index be1354219..3c1137a5d 100644 --- a/crates/solverforge-scoring/src/stream/arity_stream_macros/mod.rs +++ b/crates/solverforge-scoring/src/stream/arity_stream_macros/mod.rs @@ -6,24 +6,7 @@ #[macro_use] mod nary_stream; -/* Generates the constraint stream struct, builder struct, and common methods. - -Doctests and unique methods (should be defined outside the macro -in the individual stream files. -*/ -macro_rules! impl_arity_stream { - (bi, $stream:ident, $builder:ident) => { - impl_bi_arity_stream!($stream, $builder); - }; - (tri, $stream:ident, $builder:ident) => { - impl_tri_arity_stream!($stream, $builder); - }; - (quad, $stream:ident, $builder:ident) => { - impl_quad_arity_stream!($stream, $builder); - }; - (penta, $stream:ident, $builder:ident) => { - impl_penta_arity_stream!($stream, $builder); - }; -} +#[macro_use] +mod dispatch; -pub(crate) use impl_arity_stream; +pub(crate) use dispatch::impl_arity_stream; diff --git a/crates/solverforge-scoring/src/stream/chain.rs b/crates/solverforge-scoring/src/stream/chain.rs new file mode 100644 index 000000000..1775c55ef --- /dev/null +++ b/crates/solverforge-scoring/src/stream/chain.rs @@ -0,0 +1 @@ +pub use super::chain_stream::{Chain, ChainBuilder}; diff --git a/crates/solverforge-scoring/src/stream/cross.rs b/crates/solverforge-scoring/src/stream/cross.rs new file mode 100644 index 000000000..ed5f7a1fb --- /dev/null +++ b/crates/solverforge-scoring/src/stream/cross.rs @@ -0,0 +1,6 @@ +pub use super::cross_bi_stream::{ + Bi, Builder, ComplementedGrouped, ComplementedGroupedBuilder, Grouped, GroupedBuilder, +}; +pub use super::cross_penta_stream::{Penta, PentaBuilder}; +pub use super::cross_quad_stream::{Quad, QuadBuilder}; +pub use super::cross_tri_stream::Tri; diff --git a/crates/solverforge-scoring/src/stream/mod.rs b/crates/solverforge-scoring/src/stream/mod.rs index 509b9d85a..aa2cfb881 100644 --- a/crates/solverforge-scoring/src/stream/mod.rs +++ b/crates/solverforge-scoring/src/stream/mod.rs @@ -114,28 +114,13 @@ mod weighting_support; mod tests; /// Cross-collection join streams and their builders. -pub mod cross { - pub use super::cross_bi_stream::{ - Bi, Builder, ComplementedGrouped, ComplementedGroupedBuilder, Grouped, GroupedBuilder, - }; - pub use super::cross_penta_stream::{Penta, PentaBuilder}; - pub use super::cross_quad_stream::{Quad, QuadBuilder}; - pub use super::cross_tri_stream::Tri; -} +pub mod cross; /// Chain stream and builder. -pub mod chain { - pub use super::chain_stream::{Chain, ChainBuilder}; -} +pub mod chain; /// Projected streams: rows emitted by a [`Projection`] instead of stored entities. -pub mod projected { - pub use super::projected_stream::{ - Bi, BiBuilder, Builder, ComplementedGrouped, ComplementedGroupedBuilder, DirectedBi, - DirectedBiBuilder, Grouped, GroupedBuilder, JoinedSource, ProjectedJoinTarget, Projection, - ProjectionSink, RowCoordinate, RowOwner, Source, Stream, - }; -} +pub mod projected; pub use balance_stream::{BalanceConstraintBuilder, BalanceConstraintStream}; pub use bi_stream::{BiConstraintBuilder, BiConstraintStream}; diff --git a/crates/solverforge-scoring/src/stream/projected.rs b/crates/solverforge-scoring/src/stream/projected.rs new file mode 100644 index 000000000..9312eb0b4 --- /dev/null +++ b/crates/solverforge-scoring/src/stream/projected.rs @@ -0,0 +1,5 @@ +pub use super::projected_stream::{ + Bi, BiBuilder, Builder, ComplementedGrouped, ComplementedGroupedBuilder, DirectedBi, + DirectedBiBuilder, Grouped, GroupedBuilder, JoinedSource, ProjectedJoinTarget, Projection, + ProjectionSink, RowCoordinate, RowOwner, Source, Stream, +}; diff --git a/crates/solverforge-scoring/tests/group_by_joined.rs b/crates/solverforge-scoring/tests/group_by_joined.rs index 57e335b2c..183fc9c09 100644 --- a/crates/solverforge-scoring/tests/group_by_joined.rs +++ b/crates/solverforge-scoring/tests/group_by_joined.rs @@ -1,3 +1,6 @@ +//! Grouping over self-joined streams: tri, quad and penta joins count +//! combinations and retract them incrementally. + use solverforge_core::score::SoftScore; use solverforge_scoring::api::constraint_set::IncrementalConstraint; use solverforge_scoring::stream::collector::count; diff --git a/crates/solverforge-solver/Cargo.toml b/crates/solverforge-solver/Cargo.toml index dc9fc7fbc..1d289a9d2 100644 --- a/crates/solverforge-solver/Cargo.toml +++ b/crates/solverforge-solver/Cargo.toml @@ -24,3 +24,10 @@ rayon.workspace = true smallvec.workspace = true serde.workspace = true tokio = { workspace = true, features = ["sync"] } + +[lints.rust] +missing_docs = "warn" +unreachable_pub = "warn" + +[lints.clippy] +type_complexity = "allow" diff --git a/crates/solverforge-solver/WIREFRAME.md b/crates/solverforge-solver/WIREFRAME.md index 7fe549994..20c3ee6ad 100644 --- a/crates/solverforge-solver/WIREFRAME.md +++ b/crates/solverforge-solver/WIREFRAME.md @@ -24,6 +24,8 @@ Solver engine: phases, moves, selectors, acceptors, foragers, termination, and s ``` src/ ├── lib.rs — Crate root; module declarations, re-exports +├── __bench.rs — Hidden `__bench` module: re-exports of the bench handles +├── __private.rs — Hidden `__private` module: re-exports of the host-provider contracts ├── bench.rs — Hidden `__bench` handles: CompiledRuntimeRunner and CandidateVisitor ├── bench/neighborhood.rs — CompiledNeighborhood and CompiledNeighborhoodCursor over the lowered local-search composition cursor ├── bench/construction.rs — CompiledScalarPlacer and its placement cursors over the compiled descriptor-placement placer @@ -105,6 +107,7 @@ src/ │ │ ├── segment_layout.rs — Post-move segment coordinate derivation and reverse-identity helpers for sublist moves │ │ ├── ruin.rs — Test-only RuinMove oracle │ │ ├── k_opt.rs — CutPoint and the test-only KOptMove oracle +│ │ ├── list_undo_journal.rs — ListUndoJournal: inline undo storage for arbitrary-length list edits │ │ ├── k_opt_reconnection.rs — KOptReconnection patterns │ │ ├── k_opt_reconnection_tests.rs — Tests │ │ ├── compound_scalar.rs — CompoundScalarMove for atomic multi-scalar edits with exact undo, tabu identity, and affected-entity reporting @@ -340,7 +343,7 @@ src/ │ │ ├── list_construction/cheapest/kernel.rs — Source-indexed cheapest candidate ordering, precedence, and owner filtering │ │ ├── list_construction/cheapest/live.rs — Live score/trace/commit observer for the one cheapest kernel │ │ ├── list_construction/regret.rs — Explicit-source-key public facade for canonical regret insertion -│ │ ├── list_construction/regret/kernel/ — Source-indexed regret evaluation, precedence, fallback, and execution kernel +│ │ ├── list_construction/regret/kernel/ — Source-indexed regret evaluation, precedence, fallback, and execution kernel (`budgets.rs` work budgets, `choice.rs` regret values and comparisons) │ │ ├── list_clarke_wright.rs — ListClarkeWrightPhase │ │ ├── list_clarke_wright/kernel.rs — Canonical savings merge and route assignment (savings.rs generates and sorts savings) shared by public/static/dynamic adapters │ │ ├── list_clarke_wright/tests.rs — Tests diff --git a/crates/solverforge-solver/src/__bench.rs b/crates/solverforge-solver/src/__bench.rs new file mode 100644 index 000000000..9659c3d77 --- /dev/null +++ b/crates/solverforge-solver/src/__bench.rs @@ -0,0 +1,4 @@ +pub use crate::bench::{ + CandidateVisitor, CompiledNeighborhood, CompiledNeighborhoodCursor, CompiledRuntimeRunner, + CompiledScalarPlacement, CompiledScalarPlacementCursor, CompiledScalarPlacer, +}; diff --git a/crates/solverforge-solver/src/__private.rs b/crates/solverforge-solver/src/__private.rs new file mode 100644 index 000000000..7ae7cf479 --- /dev/null +++ b/crates/solverforge-solver/src/__private.rs @@ -0,0 +1,13 @@ +pub use crate::builder::context::candidate_metric::RuntimeCandidateMetric; +pub use crate::builder::context::candidate_metric::RuntimeCandidateMetricBinding; +pub use crate::builder::context::candidate_metric::RuntimeCandidateMetricRegistry; +pub use crate::builder::context::provider::registry::RuntimeProviderRegistry; +pub use crate::builder::context::provider::types::ProviderResolutionError; +pub use crate::builder::context::provider::types::RawProviderCandidate; +pub use crate::builder::context::provider::types::RawProviderEdit; +pub use crate::builder::context::provider::types::RuntimeConflictRepairProviderBinding; +pub use crate::builder::context::provider::types::RuntimeHostCompoundProvider; +pub use crate::builder::context::provider::types::RuntimeHostProviderErrorBoundary; +pub use crate::builder::context::provider::types::RuntimeProviderLimits; +pub use crate::builder::context::provider::types::RuntimeScalarGroupProviderBinding; +pub use crate::builder::search::custom::NoDynamicExtensions; diff --git a/crates/solverforge-solver/src/heuristic/move/list_undo_journal.rs b/crates/solverforge-solver/src/heuristic/move/list_undo_journal.rs new file mode 100644 index 000000000..4471982e2 --- /dev/null +++ b/crates/solverforge-solver/src/heuristic/move/list_undo_journal.rs @@ -0,0 +1,7 @@ +//! Undo storage for list moves with arbitrary-length edit sets. + +/// Inlined undo journal for short list edit sets (K-opt route restorations +/// and similar arbitrary-length undo payloads). Capacity is inline up to 24 +/// elements; longer routes spill to the heap and rely on the move's +/// per-trial journal pool so retained capacity is reused across trials. +pub(crate) type ListUndoJournal = smallvec::SmallVec<[T; 24]>; diff --git a/crates/solverforge-solver/src/heuristic/move/mod.rs b/crates/solverforge-solver/src/heuristic/move/mod.rs index 905fea787..5a6ee6892 100644 --- a/crates/solverforge-solver/src/heuristic/move/mod.rs +++ b/crates/solverforge-solver/src/heuristic/move/mod.rs @@ -12,11 +12,9 @@ //! stable `CandidateId`s, and the selected move is taken from its cursor by //! ownership. -/// Inlined undo journal for short list edit sets (K-opt route restorations -/// and similar arbitrary-length undo payloads). Capacity is inline up to 24 -/// elements; longer routes spill to the heap and rely on the move's -/// per-trial journal pool so retained capacity is reused across trials. -pub(crate) type ListUndoJournal = smallvec::SmallVec<[T; 24]>; +mod list_undo_journal; + +pub(crate) use list_undo_journal::ListUndoJournal; #[cfg(test)] pub(crate) mod change; diff --git a/crates/solverforge-solver/src/heuristic/move/tests/mod.rs b/crates/solverforge-solver/src/heuristic/move/tests/mod.rs index dde405608..0be1483d7 100644 --- a/crates/solverforge-solver/src/heuristic/move/tests/mod.rs +++ b/crates/solverforge-solver/src/heuristic/move/tests/mod.rs @@ -1,119 +1,13 @@ // Tests for the move module. use super::*; +use snapshot_director::SnapshotDirector; use solverforge_core::domain::{ EntityCollectionExtractor, EntityDescriptor, PlanningSolution, SolutionDescriptor, }; use solverforge_core::score::SoftScore; use solverforge_scoring::{Director, ScoreDirector}; use std::any::TypeId; -use std::ptr::NonNull; - -struct SnapshotDirector -where - S: PlanningSolution, - D: Director, -{ - inner: NonNull, - snapshot: S, - score_state: solverforge_scoring::DirectorScoreState, -} - -unsafe impl Send for SnapshotDirector -where - S: PlanningSolution, - D: Director, -{ -} - -impl SnapshotDirector -where - S: PlanningSolution, - D: Director, -{ - fn new(inner: &mut D) -> Self { - Self { - snapshot: inner.clone_working_solution(), - score_state: inner.snapshot_score_state(), - inner: NonNull::from(inner), - } - } - - fn undo_changes(&mut self) { - *self.inner_mut().working_solution_mut() = self.snapshot.clone(); - let current_score_state = self.inner_ref().snapshot_score_state(); - let score_state = std::mem::replace(&mut self.score_state, current_score_state); - self.inner_mut().restore_score_state(score_state); - } - - fn inner_ref(&self) -> &D { - unsafe { self.inner.as_ref() } - } - - fn inner_mut(&mut self) -> &mut D { - unsafe { self.inner.as_mut() } - } -} - -impl Director for SnapshotDirector -where - S: PlanningSolution, - D: Director, -{ - fn working_solution(&self) -> &S { - self.inner_ref().working_solution() - } - - fn working_solution_mut(&mut self) -> &mut S { - self.inner_mut().working_solution_mut() - } - - fn calculate_score(&mut self) -> S::Score { - self.inner_mut().calculate_score() - } - - fn solution_descriptor(&self) -> &SolutionDescriptor { - self.inner_ref().solution_descriptor() - } - - fn clone_working_solution(&self) -> S { - self.inner_ref().clone_working_solution() - } - - fn before_variable_changed(&mut self, descriptor_index: usize, entity_index: usize) { - self.inner_mut() - .before_variable_changed(descriptor_index, entity_index); - } - - fn after_variable_changed(&mut self, descriptor_index: usize, entity_index: usize) { - self.inner_mut() - .after_variable_changed(descriptor_index, entity_index); - } - - fn entity_count(&self, descriptor_index: usize) -> Option { - self.inner_ref().entity_count(descriptor_index) - } - - fn total_entity_count(&self) -> Option { - self.inner_ref().total_entity_count() - } - - fn constraint_metadata(&self) -> Vec> { - self.inner_ref().constraint_metadata() - } - - fn is_incremental(&self) -> bool { - self.inner_ref().is_incremental() - } - - fn snapshot_score_state(&self) -> solverforge_scoring::DirectorScoreState { - self.inner_ref().snapshot_score_state() - } - - fn restore_score_state(&mut self, state: solverforge_scoring::DirectorScoreState) { - self.inner_mut().restore_score_state(state); - } -} mod change; mod composite_preview; @@ -127,6 +21,7 @@ mod list_ruin; mod list_swap; mod list_telemetry; mod ruin; +mod snapshot_director; mod sublist_change; mod sublist_swap; mod tabu_signature_lending; diff --git a/crates/solverforge-solver/src/heuristic/move/tests/snapshot_director.rs b/crates/solverforge-solver/src/heuristic/move/tests/snapshot_director.rs new file mode 100644 index 000000000..1f8c04745 --- /dev/null +++ b/crates/solverforge-solver/src/heuristic/move/tests/snapshot_director.rs @@ -0,0 +1,112 @@ +//! A director wrapper that snapshots the working solution and score state so +//! a test can apply a move, inspect it, and roll it back. + +use solverforge_core::domain::{PlanningSolution, SolutionDescriptor}; +use solverforge_scoring::Director; +use std::ptr::NonNull; + +pub(super) struct SnapshotDirector +where + S: PlanningSolution, + D: Director, +{ + inner: NonNull, + snapshot: S, + score_state: solverforge_scoring::DirectorScoreState, +} + +unsafe impl Send for SnapshotDirector +where + S: PlanningSolution, + D: Director, +{ +} + +impl SnapshotDirector +where + S: PlanningSolution, + D: Director, +{ + pub(super) fn new(inner: &mut D) -> Self { + Self { + snapshot: inner.clone_working_solution(), + score_state: inner.snapshot_score_state(), + inner: NonNull::from(inner), + } + } + + pub(super) fn undo_changes(&mut self) { + *self.inner_mut().working_solution_mut() = self.snapshot.clone(); + let current_score_state = self.inner_ref().snapshot_score_state(); + let score_state = std::mem::replace(&mut self.score_state, current_score_state); + self.inner_mut().restore_score_state(score_state); + } + + fn inner_ref(&self) -> &D { + unsafe { self.inner.as_ref() } + } + + fn inner_mut(&mut self) -> &mut D { + unsafe { self.inner.as_mut() } + } +} + +impl Director for SnapshotDirector +where + S: PlanningSolution, + D: Director, +{ + fn working_solution(&self) -> &S { + self.inner_ref().working_solution() + } + + fn working_solution_mut(&mut self) -> &mut S { + self.inner_mut().working_solution_mut() + } + + fn calculate_score(&mut self) -> S::Score { + self.inner_mut().calculate_score() + } + + fn solution_descriptor(&self) -> &SolutionDescriptor { + self.inner_ref().solution_descriptor() + } + + fn clone_working_solution(&self) -> S { + self.inner_ref().clone_working_solution() + } + + fn before_variable_changed(&mut self, descriptor_index: usize, entity_index: usize) { + self.inner_mut() + .before_variable_changed(descriptor_index, entity_index); + } + + fn after_variable_changed(&mut self, descriptor_index: usize, entity_index: usize) { + self.inner_mut() + .after_variable_changed(descriptor_index, entity_index); + } + + fn entity_count(&self, descriptor_index: usize) -> Option { + self.inner_ref().entity_count(descriptor_index) + } + + fn total_entity_count(&self) -> Option { + self.inner_ref().total_entity_count() + } + + fn constraint_metadata(&self) -> Vec> { + self.inner_ref().constraint_metadata() + } + + fn is_incremental(&self) -> bool { + self.inner_ref().is_incremental() + } + + fn snapshot_score_state(&self) -> solverforge_scoring::DirectorScoreState { + self.inner_ref().snapshot_score_state() + } + + fn restore_score_state(&mut self, state: solverforge_scoring::DirectorScoreState) { + self.inner_mut().restore_score_state(state); + } +} diff --git a/crates/solverforge-solver/src/lib.rs b/crates/solverforge-solver/src/lib.rs index ae36e713b..b8a7d3120 100644 --- a/crates/solverforge-solver/src/lib.rs +++ b/crates/solverforge-solver/src/lib.rs @@ -15,9 +15,6 @@ trait bounds from phantom type parameters. Clippy's type_complexity lint triggers on these tuples but the pattern is architecturally required. */ -#![allow(clippy::type_complexity)] -#![warn(missing_docs)] -#![warn(unreachable_pub)] #[cfg(test)] mod test_utils; @@ -172,29 +169,10 @@ pub use stats::telemetry::Throughput; /// compilation a configured solve runs. Hidden and not part of the supported /// API: no compatibility promise covers them. #[doc(hidden)] -pub mod __bench { - pub use crate::bench::{ - CandidateVisitor, CompiledNeighborhood, CompiledNeighborhoodCursor, CompiledRuntimeRunner, - CompiledScalarPlacement, CompiledScalarPlacementCursor, CompiledScalarPlacer, - }; -} +pub mod __bench; /// Solver internals other SolverForge crates build on: the host-provider /// contracts `solverforge-bridge` re-exports for host-language bindings. /// Hidden and not part of the supported API. #[doc(hidden)] -pub mod __private { - pub use crate::builder::context::candidate_metric::RuntimeCandidateMetric; - pub use crate::builder::context::candidate_metric::RuntimeCandidateMetricBinding; - pub use crate::builder::context::candidate_metric::RuntimeCandidateMetricRegistry; - pub use crate::builder::context::provider::registry::RuntimeProviderRegistry; - pub use crate::builder::context::provider::types::ProviderResolutionError; - pub use crate::builder::context::provider::types::RawProviderCandidate; - pub use crate::builder::context::provider::types::RawProviderEdit; - pub use crate::builder::context::provider::types::RuntimeConflictRepairProviderBinding; - pub use crate::builder::context::provider::types::RuntimeHostCompoundProvider; - pub use crate::builder::context::provider::types::RuntimeHostProviderErrorBoundary; - pub use crate::builder::context::provider::types::RuntimeProviderLimits; - pub use crate::builder::context::provider::types::RuntimeScalarGroupProviderBinding; - pub use crate::builder::search::custom::NoDynamicExtensions; -} +pub mod __private; diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_construction/regret/kernel/budgets.rs b/crates/solverforge-solver/src/manager/phase_factory/list_construction/regret/kernel/budgets.rs new file mode 100644 index 000000000..c985e68e5 --- /dev/null +++ b/crates/solverforge-solver/src/manager/phase_factory/list_construction/regret/kernel/budgets.rs @@ -0,0 +1,5 @@ +//! Work budgets that switch owner-restricted regret insertion to its cheaper +//! fallbacks. + +pub(super) const OWNER_RESTRICTED_REGRET_TRIAL_BUDGET: usize = 16_384; +pub(super) const OWNER_RESTRICTED_BEST_INSERTION_WORK_BUDGET: usize = 8_000_000; diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_construction/regret/kernel/choice.rs b/crates/solverforge-solver/src/manager/phase_factory/list_construction/regret/kernel/choice.rs new file mode 100644 index 000000000..193d3b2b0 --- /dev/null +++ b/crates/solverforge-solver/src/manager/phase_factory/list_construction/regret/kernel/choice.rs @@ -0,0 +1,97 @@ +//! Regret values, the comparisons that pick the next insertion, and the +//! candidate bookkeeping the kernel shares. + +use crate::list_placement::OwnerRestriction; + +#[derive(Debug, PartialEq, Eq)] +pub(super) enum RegretValue { + Finite(Sc), + Forced, +} + +pub(super) enum RegretEvaluation { + Complete(Option), + Interrupted, +} + +impl Copy for RegretValue {} + +impl Clone for RegretValue { + fn clone(&self) -> Self { + *self + } +} + +impl PartialOrd for RegretValue { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for RegretValue { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + match (self, other) { + (Self::Forced, Self::Forced) => std::cmp::Ordering::Equal, + (Self::Forced, Self::Finite(_)) => std::cmp::Ordering::Greater, + (Self::Finite(_), Self::Forced) => std::cmp::Ordering::Less, + (Self::Finite(left), Self::Finite(right)) => left.cmp(right), + } + } +} + +pub(super) fn regret_choice_is_better( + regret: RegretValue, + score: Sc, + best_regret: RegretValue, + best_score: Sc, +) -> bool { + regret > best_regret || (regret == best_regret && score > best_score) +} + +pub(super) fn regret_choice_is_better_with_downstream( + regret: RegretValue, + score: Sc, + downstream: usize, + best_regret: RegretValue, + best_score: Sc, + best_downstream: usize, +) -> bool { + regret_choice_is_better(regret, score, best_regret, best_score) + || (regret == best_regret && score == best_score && downstream > best_downstream) +} + +pub(super) fn precedence_frontier_choice_is_better( + downstream: usize, + regret: RegretValue, + score: Sc, + best_downstream: usize, + best_regret: RegretValue, + best_score: Sc, +) -> bool { + downstream > best_downstream + || (downstream == best_downstream + && regret_choice_is_better(regret, score, best_regret, best_score)) +} + +pub(super) fn source_position_by_index( + source_count: usize, + entries: &[crate::builder::context::SourceElement], +) -> Option>> { + let mut positions = vec![None; source_count]; + for (position, entry) in entries.iter().enumerate() { + let slot = positions.get_mut(entry.source_index)?; + if slot.replace(position).is_some() { + return None; + } + } + Some(positions) +} + +pub(super) fn candidate_entities( + restriction: OwnerRestriction, + entity_count: usize, +) -> impl Iterator { + // Same enumeration order as OwnerRestriction::candidates; the shared + // primitive carries the semantics. + restriction.candidates(entity_count) +} diff --git a/crates/solverforge-solver/src/manager/phase_factory/list_construction/regret/kernel/mod.rs b/crates/solverforge-solver/src/manager/phase_factory/list_construction/regret/kernel/mod.rs index f143497b3..f1833f87c 100644 --- a/crates/solverforge-solver/src/manager/phase_factory/list_construction/regret/kernel/mod.rs +++ b/crates/solverforge-solver/src/manager/phase_factory/list_construction/regret/kernel/mod.rs @@ -5,8 +5,8 @@ //! owner-restricted work bounds, interruption points, and trace transitions //! live in the modules below exactly once. -use crate::list_placement::OwnerRestriction; - +mod budgets; +mod choice; mod evaluation; mod execute; mod fallback; @@ -15,98 +15,9 @@ mod precedence; pub(crate) use super::super::ScoredListConstructionAccess as RegretAccess; pub(crate) use execute::run_regret; -pub(super) const OWNER_RESTRICTED_REGRET_TRIAL_BUDGET: usize = 16_384; -pub(super) const OWNER_RESTRICTED_BEST_INSERTION_WORK_BUDGET: usize = 8_000_000; - -#[derive(Debug, PartialEq, Eq)] -pub(super) enum RegretValue { - Finite(Sc), - Forced, -} - -pub(super) enum RegretEvaluation { - Complete(Option), - Interrupted, -} - -impl Copy for RegretValue {} - -impl Clone for RegretValue { - fn clone(&self) -> Self { - *self - } -} - -impl PartialOrd for RegretValue { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl Ord for RegretValue { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - match (self, other) { - (Self::Forced, Self::Forced) => std::cmp::Ordering::Equal, - (Self::Forced, Self::Finite(_)) => std::cmp::Ordering::Greater, - (Self::Finite(_), Self::Forced) => std::cmp::Ordering::Less, - (Self::Finite(left), Self::Finite(right)) => left.cmp(right), - } - } -} - -pub(super) fn regret_choice_is_better( - regret: RegretValue, - score: Sc, - best_regret: RegretValue, - best_score: Sc, -) -> bool { - regret > best_regret || (regret == best_regret && score > best_score) -} - -pub(super) fn regret_choice_is_better_with_downstream( - regret: RegretValue, - score: Sc, - downstream: usize, - best_regret: RegretValue, - best_score: Sc, - best_downstream: usize, -) -> bool { - regret_choice_is_better(regret, score, best_regret, best_score) - || (regret == best_regret && score == best_score && downstream > best_downstream) -} - -pub(super) fn precedence_frontier_choice_is_better( - downstream: usize, - regret: RegretValue, - score: Sc, - best_downstream: usize, - best_regret: RegretValue, - best_score: Sc, -) -> bool { - downstream > best_downstream - || (downstream == best_downstream - && regret_choice_is_better(regret, score, best_regret, best_score)) -} - -pub(super) fn source_position_by_index( - source_count: usize, - entries: &[crate::builder::context::SourceElement], -) -> Option>> { - let mut positions = vec![None; source_count]; - for (position, entry) in entries.iter().enumerate() { - let slot = positions.get_mut(entry.source_index)?; - if slot.replace(position).is_some() { - return None; - } - } - Some(positions) -} - -pub(super) fn candidate_entities( - restriction: OwnerRestriction, - entity_count: usize, -) -> impl Iterator { - // Same enumeration order as OwnerRestriction::candidates; the shared - // primitive carries the semantics. - restriction.candidates(entity_count) -} +use budgets::{OWNER_RESTRICTED_BEST_INSERTION_WORK_BUDGET, OWNER_RESTRICTED_REGRET_TRIAL_BUDGET}; +use choice::{ + candidate_entities, precedence_frontier_choice_is_better, + regret_choice_is_better_with_downstream, source_position_by_index, RegretEvaluation, + RegretValue, +}; diff --git a/crates/solverforge-solver/tests/construction_buffer_reuse.rs b/crates/solverforge-solver/tests/construction_buffer_reuse.rs index b8908f181..c8d609100 100644 --- a/crates/solverforge-solver/tests/construction_buffer_reuse.rs +++ b/crates/solverforge-solver/tests/construction_buffer_reuse.rs @@ -12,6 +12,9 @@ use solverforge_config::{ }; use solverforge_solver::__bench::CompiledRuntimeRunner; +// Each test binary uses part of the shared model. +#[allow(dead_code)] +#[path = "support/scalar_model.rs"] mod support; struct CountingAllocator; diff --git a/crates/solverforge-solver/tests/runner_compile_threads.rs b/crates/solverforge-solver/tests/runner_compile_threads.rs index 5ff991cfa..f19519ba7 100644 --- a/crates/solverforge-solver/tests/runner_compile_threads.rs +++ b/crates/solverforge-solver/tests/runner_compile_threads.rs @@ -13,6 +13,9 @@ use solverforge_config::{ }; use solverforge_solver::__bench::CompiledRuntimeRunner; +// Each test binary uses part of the shared model. +#[allow(dead_code)] +#[path = "support/scalar_model.rs"] mod support; fn thread_count() -> usize { diff --git a/crates/solverforge-solver/tests/support/mod.rs b/crates/solverforge-solver/tests/support/scalar_model.rs similarity index 86% rename from crates/solverforge-solver/tests/support/mod.rs rename to crates/solverforge-solver/tests/support/scalar_model.rs index 444b9059c..c67e14522 100644 --- a/crates/solverforge-solver/tests/support/mod.rs +++ b/crates/solverforge-solver/tests/support/scalar_model.rs @@ -1,6 +1,5 @@ //! A one-variable scalar model the solver's integration tests compile: //! tasks assigned a worker from `0..4`. Each test binary uses part of it. -#![allow(dead_code)] use std::any::TypeId; @@ -15,14 +14,14 @@ use solverforge_solver::{ }; #[derive(Clone, Debug)] -pub struct Task { - pub worker: Option, +pub(crate) struct Task { + pub(crate) worker: Option, } #[derive(Clone, Debug)] -pub struct Plan { - pub tasks: Vec, - pub score: Option, +pub(crate) struct Plan { + pub(crate) tasks: Vec, + pub(crate) score: Option, } impl PlanningSolution for Plan { @@ -38,7 +37,7 @@ impl PlanningSolution for Plan { } #[derive(Clone, Copy, Debug)] -pub struct NoMeter; +pub(crate) struct NoMeter; impl CrossEntityDistanceMeter for NoMeter { fn distance(&self, _: &Plan, _: usize, _: usize, _: usize, _: usize) -> f64 { @@ -76,7 +75,7 @@ fn descriptor() -> SolutionDescriptor { } /// The search context binding the model's one scalar slot. -pub fn context() -> SearchContext { +pub(crate) fn context() -> SearchContext { let slot = VariableSlot::Scalar(ScalarVariableSlot::new( 0, 0, @@ -93,7 +92,7 @@ pub fn context() -> SearchContext { } /// `count` tasks, none assigned. -pub fn unassigned(count: usize) -> Plan { +pub(crate) fn unassigned(count: usize) -> Plan { Plan { tasks: (0..count).map(|_| Task { worker: None }).collect(), score: None, @@ -101,6 +100,6 @@ pub fn unassigned(count: usize) -> Plan { } /// A director over `plan` scoring the task count. -pub fn director(plan: Plan) -> solverforge_scoring::ScoreDirector { +pub(crate) fn director(plan: Plan) -> solverforge_scoring::ScoreDirector { solverforge_scoring::ScoreDirector::simple(plan, descriptor(), |plan, _| plan.tasks.len()) } diff --git a/crates/solverforge/Cargo.toml b/crates/solverforge/Cargo.toml index 9eb92f9e3..bf15025f9 100644 --- a/crates/solverforge/Cargo.toml +++ b/crates/solverforge/Cargo.toml @@ -35,3 +35,6 @@ rayon.workspace = true serde.workspace = true toml.workspace = true tracing.workspace = true + +[lints.rust] +missing_docs = "warn" diff --git a/crates/solverforge/WIREFRAME.md b/crates/solverforge/WIREFRAME.md index 30b2d35dc..5542f2bf7 100644 --- a/crates/solverforge/WIREFRAME.md +++ b/crates/solverforge/WIREFRAME.md @@ -31,15 +31,25 @@ The CLI lives in the standalone `solverforge-cli` repository and is not part of ``` src/ ├── __internal.rs — Hidden macro support re-exports and helpers +├── analysis.rs — `analysis` facade re-exports +├── builder.rs — `builder` facade re-exports +├── config.rs — `config` facade re-exports +├── console.rs — `console` facade re-export (feature `console`) +├── constraint.rs — `constraint` facade re-exports ├── cvrp.rs — CVRP facade re-exports +├── director.rs — `director` facade re-exports +├── domain.rs — `domain` facade re-exports +├── heuristic.rs — `heuristic` facade re-exports ├── lib.rs — Crate docs (`//!`, Quick Start doctest), top-level re-exports and module declarations +├── phase.rs — `phase` facade re-exports ├── planning.rs — Planning target helpers for scalar groups and conflict repair ├── prelude.rs — Prelude exports +├── stats.rs — `stats` facade re-exports └── stream.rs — Fluent constraint stream facade doc/quick_start/ — Quick Start model (employee, shift, schedule, solver.toml) included by the crate docs and compiled by its doctest ``` -Every workspace crate (the facade, `solverforge-core`, `solverforge-config`, `solverforge-scoring`, `solverforge-solver`, `solverforge-console`, `solverforge-macros`, `solverforge-bridge` and `solverforge-cvrp`) sets `#![warn(missing_docs)]`; CI's clippy `-D warnings` makes an undocumented public item an error. +Every workspace crate (the facade, `solverforge-core`, `solverforge-config`, `solverforge-scoring`, `solverforge-solver`, `solverforge-console`, `solverforge-macros`, `solverforge-bridge` and `solverforge-cvrp`) sets `missing_docs = "warn"` in its Cargo `[lints]` table, which also covers its integration tests; CI's clippy `-D warnings` makes an undocumented public item an error. ## Public Re-exports diff --git a/crates/solverforge/src/analysis.rs b/crates/solverforge/src/analysis.rs new file mode 100644 index 000000000..e2e58a665 --- /dev/null +++ b/crates/solverforge/src/analysis.rs @@ -0,0 +1 @@ +pub use solverforge_scoring::api::analysis::*; diff --git a/crates/solverforge/src/builder.rs b/crates/solverforge/src/builder.rs new file mode 100644 index 000000000..2b4b08ad8 --- /dev/null +++ b/crates/solverforge/src/builder.rs @@ -0,0 +1,4 @@ +pub use solverforge_solver::{ + bind_scalar_groups, local_search, CustomSearchPhase, ListVariableSlot, RuntimeModel, + ScalarGroupBinding, ScalarVariableSlot, Search, SearchContext, ValueSource, VariableSlot, +}; diff --git a/crates/solverforge/src/config.rs b/crates/solverforge/src/config.rs new file mode 100644 index 000000000..a059fe857 --- /dev/null +++ b/crates/solverforge/src/config.rs @@ -0,0 +1 @@ +pub use solverforge_config::*; diff --git a/crates/solverforge/src/console.rs b/crates/solverforge/src/console.rs new file mode 100644 index 000000000..f14f404a2 --- /dev/null +++ b/crates/solverforge/src/console.rs @@ -0,0 +1 @@ +pub use solverforge_console::init; diff --git a/crates/solverforge/src/constraint.rs b/crates/solverforge/src/constraint.rs new file mode 100644 index 000000000..72cfa6e67 --- /dev/null +++ b/crates/solverforge/src/constraint.rs @@ -0,0 +1 @@ +pub use solverforge_scoring::constraint::*; diff --git a/crates/solverforge/src/director.rs b/crates/solverforge/src/director.rs new file mode 100644 index 000000000..11b463250 --- /dev/null +++ b/crates/solverforge/src/director.rs @@ -0,0 +1 @@ +pub use solverforge_scoring::director::*; diff --git a/crates/solverforge/src/domain.rs b/crates/solverforge/src/domain.rs new file mode 100644 index 000000000..9a0163298 --- /dev/null +++ b/crates/solverforge/src/domain.rs @@ -0,0 +1 @@ +pub use solverforge_core::domain::*; diff --git a/crates/solverforge/src/heuristic.rs b/crates/solverforge/src/heuristic.rs new file mode 100644 index 000000000..278d5b8dd --- /dev/null +++ b/crates/solverforge/src/heuristic.rs @@ -0,0 +1,6 @@ +pub use solverforge_solver::{ + CandidateId, CrossEntityDistanceMeter, DefaultCrossEntityDistanceMeter, DefaultDistanceMeter, + Move, MoveAffectedEntity, MoveCandidateRef, MoveCandidateUndo, MoveCursor, MoveSelector, + MoveSelectorIter, MoveStreamContext, MoveTabuScope, MoveTabuSignature, ScopedEntityTabuToken, + ScopedValueTabuToken, SequentialCompositeMoveRef, +}; diff --git a/crates/solverforge/src/lib.rs b/crates/solverforge/src/lib.rs index fcd977837..3339bada4 100644 --- a/crates/solverforge/src/lib.rs +++ b/crates/solverforge/src/lib.rs @@ -85,8 +85,6 @@ //! } //! ``` -#![warn(missing_docs)] - /* ============================================================================ Attribute Macros ============================================================================ @@ -118,76 +116,33 @@ pub use solverforge_core::{ MAX_CONSTRAINT_WEIGHT_MULTIPLIER, }; +/// Score analysis types returned by constraints and score directors. +pub mod analysis; +/// Search declaration building blocks behind `SearchContext` and `Search`. +pub mod builder; /// Every solver configuration type: phases, move selectors, acceptors, /// foragers, termination and the configuration error. -pub mod config { - pub use solverforge_config::*; -} +pub mod config; +/// Built-in constraint implementations that the stream builders produce. +pub mod constraint; /// Stock CVRP profile: problem data, distance meters and route hooks. pub mod cvrp; -/// Solver and phase statistics, telemetry and candidate-trace types. -pub mod stats { - pub use solverforge_solver::{ - AppliedMoveTelemetry, CandidatePullTelemetry, CandidateTraceCompositeIdentity, - CandidateTraceConstructionTarget, CandidateTraceCoordinate, CandidateTraceDigest, - CandidateTraceDisposition, CandidateTraceExecutionPolicy, CandidateTraceExternalDigest, - CandidateTraceHeader, CandidateTraceIdentity, CandidateTraceInputAttestation, - CandidateTraceInputProvenance, CandidateTraceInputProvenanceStatus, - CandidateTraceOperationIdentity, CandidateTracePhaseAttribute, CandidateTracePhasePlan, - CandidateTraceProvenanceStatus, CandidateTraceQualificationError, - CandidateTraceQualificationStatus, CandidateTraceSource, CandidateTraceTelemetry, - MoveTelemetry, PhaseStats, PhaseTelemetry, QualifiedCandidateTraceRunProvenance, - SelectorTelemetry, SolverStats, SolverTelemetry, Throughput, - CANDIDATE_TRACE_FORMAT_VERSION, - }; -} +/// Score directors and their weight modes. +pub mod director; /// Planning-model traits and runtime descriptors (`PlanningSolution`, /// `SolutionDescriptor`, entity and variable descriptors). -pub mod domain { - pub use solverforge_core::domain::*; -} -/// Score analysis types returned by constraints and score directors. -pub mod analysis { - pub use solverforge_scoring::api::analysis::*; -} -/// Built-in constraint implementations that the stream builders produce. -pub mod constraint { - pub use solverforge_scoring::constraint::*; -} -/// Score directors and their weight modes. -pub mod director { - pub use solverforge_scoring::director::*; -} -/// Search declaration building blocks behind `SearchContext` and `Search`. -pub mod builder { - pub use solverforge_solver::{ - bind_scalar_groups, local_search, CustomSearchPhase, ListVariableSlot, RuntimeModel, - ScalarGroupBinding, ScalarVariableSlot, Search, SearchContext, ValueSource, VariableSlot, - }; -} +pub mod domain; /// Moves, move selectors and move cursors for custom search. -pub mod heuristic { - pub use solverforge_solver::{ - CandidateId, CrossEntityDistanceMeter, DefaultCrossEntityDistanceMeter, - DefaultDistanceMeter, Move, MoveAffectedEntity, MoveCandidateRef, MoveCandidateUndo, - MoveCursor, MoveSelector, MoveSelectorIter, MoveStreamContext, MoveTabuScope, - MoveTabuSignature, ScopedEntityTabuToken, ScopedValueTabuToken, SequentialCompositeMoveRef, - }; -} +pub mod heuristic; /// Phases and their parts: local search acceptors and foragers, exhaustive /// search deciders, partitioned search. -pub mod phase { - pub use solverforge_solver::{ - Acceptor, ChildPhases, ExhaustiveSearchConfig, ExhaustiveSearchDecider, - ExhaustiveSearchNode, ExhaustiveSearchPhase, ExplorationType, ForagerDecision, - FunctionalPartitioner, LocalSearchForager, PartitionedSearchConfig, PartitionedSearchPhase, - Phase, ScoreBounder, SimpleDecider, SolutionPartitioner, ThreadCount, - }; -} +pub mod phase; /// Scalar and repair planning types and source-to-target helpers. pub mod planning; /// Glob import for domain models and constraint providers. pub mod prelude; +/// Solver and phase statistics, telemetry and candidate-trace types. +pub mod stats; /// Fluent constraint stream API. pub mod stream; @@ -256,6 +211,4 @@ Console Output (feature-gated) /// banner and solver lifecycle and progress events. Available with the /// `console` feature. #[cfg(feature = "console")] -pub mod console { - pub use solverforge_console::init; -} +pub mod console; diff --git a/crates/solverforge/src/phase.rs b/crates/solverforge/src/phase.rs new file mode 100644 index 000000000..bb104612e --- /dev/null +++ b/crates/solverforge/src/phase.rs @@ -0,0 +1,6 @@ +pub use solverforge_solver::{ + Acceptor, ChildPhases, ExhaustiveSearchConfig, ExhaustiveSearchDecider, ExhaustiveSearchNode, + ExhaustiveSearchPhase, ExplorationType, ForagerDecision, FunctionalPartitioner, + LocalSearchForager, PartitionedSearchConfig, PartitionedSearchPhase, Phase, ScoreBounder, + SimpleDecider, SolutionPartitioner, ThreadCount, +}; diff --git a/crates/solverforge/src/stats.rs b/crates/solverforge/src/stats.rs new file mode 100644 index 000000000..d31a1015a --- /dev/null +++ b/crates/solverforge/src/stats.rs @@ -0,0 +1,12 @@ +pub use solverforge_solver::{ + AppliedMoveTelemetry, CandidatePullTelemetry, CandidateTraceCompositeIdentity, + CandidateTraceConstructionTarget, CandidateTraceCoordinate, CandidateTraceDigest, + CandidateTraceDisposition, CandidateTraceExecutionPolicy, CandidateTraceExternalDigest, + CandidateTraceHeader, CandidateTraceIdentity, CandidateTraceInputAttestation, + CandidateTraceInputProvenance, CandidateTraceInputProvenanceStatus, + CandidateTraceOperationIdentity, CandidateTracePhaseAttribute, CandidateTracePhasePlan, + CandidateTraceProvenanceStatus, CandidateTraceQualificationError, + CandidateTraceQualificationStatus, CandidateTraceSource, CandidateTraceTelemetry, + MoveTelemetry, PhaseStats, PhaseTelemetry, QualifiedCandidateTraceRunProvenance, + SelectorTelemetry, SolverStats, SolverTelemetry, Throughput, CANDIDATE_TRACE_FORMAT_VERSION, +}; diff --git a/crates/solverforge/tests/configurable_solvable.rs b/crates/solverforge/tests/configurable_solvable.rs index 01b5e8546..c79c32543 100644 --- a/crates/solverforge/tests/configurable_solvable.rs +++ b/crates/solverforge/tests/configurable_solvable.rs @@ -1,3 +1,6 @@ +//! `#[planning_solution]` with and without `solver_toml`: the embedded +//! configuration never depends on the working directory. + use std::fs; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{Mutex, OnceLock}; diff --git a/crates/solverforge/tests/configurable_solvable/domain/configurable/mod.rs b/crates/solverforge/tests/configurable_solvable/domain/configurable/mod.rs new file mode 100644 index 000000000..f8dd47fb8 --- /dev/null +++ b/crates/solverforge/tests/configurable_solvable/domain/configurable/mod.rs @@ -0,0 +1,9 @@ +solverforge::planning_model! { + root = "crates/solverforge/tests/configurable_solvable/domain/configurable"; + + mod configurable_solution; + mod dummy_entity; + + pub use configurable_solution::ConfigurableSolution; + pub use dummy_entity::DummyEntity; +} diff --git a/crates/solverforge/tests/configurable_solvable/domain/explicit/mod.rs b/crates/solverforge/tests/configurable_solvable/domain/explicit/mod.rs new file mode 100644 index 000000000..bf1ea5760 --- /dev/null +++ b/crates/solverforge/tests/configurable_solvable/domain/explicit/mod.rs @@ -0,0 +1,9 @@ +solverforge::planning_model! { + root = "crates/solverforge/tests/configurable_solvable/domain/explicit"; + + mod dummy_entity; + mod explicit_configurable_solution; + + pub use dummy_entity::DummyEntity; + pub use explicit_configurable_solution::ExplicitConfigurableSolution; +} diff --git a/crates/solverforge/tests/configurable_solvable/domain/explicit_list/mod.rs b/crates/solverforge/tests/configurable_solvable/domain/explicit_list/mod.rs new file mode 100644 index 000000000..bb7c6b8ef --- /dev/null +++ b/crates/solverforge/tests/configurable_solvable/domain/explicit_list/mod.rs @@ -0,0 +1,11 @@ +solverforge::planning_model! { + root = "crates/solverforge/tests/configurable_solvable/domain/explicit_list"; + + mod dummy_route; + mod dummy_visit; + mod explicit_list_configurable_solution; + + pub use dummy_route::DummyRoute; + pub use dummy_visit::DummyVisit; + pub use explicit_list_configurable_solution::ExplicitListConfigurableSolution; +} diff --git a/crates/solverforge/tests/configurable_solvable/domain/mod.rs b/crates/solverforge/tests/configurable_solvable/domain/mod.rs index 640df0324..87810c318 100644 --- a/crates/solverforge/tests/configurable_solvable/domain/mod.rs +++ b/crates/solverforge/tests/configurable_solvable/domain/mod.rs @@ -1,40 +1,8 @@ -pub mod configurable { - solverforge::planning_model! { - root = "crates/solverforge/tests/configurable_solvable/domain/configurable"; +pub mod configurable; - mod configurable_solution; - mod dummy_entity; +pub mod explicit; - pub use configurable_solution::ConfigurableSolution; - pub use dummy_entity::DummyEntity; - } -} - -pub mod explicit { - solverforge::planning_model! { - root = "crates/solverforge/tests/configurable_solvable/domain/explicit"; - - mod dummy_entity; - mod explicit_configurable_solution; - - pub use dummy_entity::DummyEntity; - pub use explicit_configurable_solution::ExplicitConfigurableSolution; - } -} - -pub mod explicit_list { - solverforge::planning_model! { - root = "crates/solverforge/tests/configurable_solvable/domain/explicit_list"; - - mod dummy_route; - mod dummy_visit; - mod explicit_list_configurable_solution; - - pub use dummy_route::DummyRoute; - pub use dummy_visit::DummyVisit; - pub use explicit_list_configurable_solution::ExplicitListConfigurableSolution; - } -} +pub mod explicit_list; pub use configurable::ConfigurableSolution; pub use explicit::ExplicitConfigurableSolution; diff --git a/crates/solverforge/tests/constraint_accessors.rs b/crates/solverforge/tests/constraint_accessors.rs index 1d4ce7028..a87ceae87 100644 --- a/crates/solverforge/tests/constraint_accessors.rs +++ b/crates/solverforge/tests/constraint_accessors.rs @@ -1,3 +1,6 @@ +//! Score accessors, generated constraint-stream accessors and the generated +//! stream trait on a small planning model. + // Integration test for constraint stream accessors generated by #[planning_solution] // and canonical score-weighted penalize() calls. diff --git a/crates/solverforge/tests/constraint_weights.rs b/crates/solverforge/tests/constraint_weights.rs index 568b0967a..813f13636 100644 --- a/crates/solverforge/tests/constraint_weights.rs +++ b/crates/solverforge/tests/constraint_weights.rs @@ -1,3 +1,6 @@ +//! Constraint weights: solving, validation and score analysis under +//! `#[constraint_weights]`. + // Facade-level runtime constraint weights on a macro-generated model. #[path = "constraint_weights/mod.rs"] diff --git a/crates/solverforge/tests/constraint_weights/plan.rs b/crates/solverforge/tests/constraint_weights/plan.rs index 1d4c07df7..cbd9528c8 100644 --- a/crates/solverforge/tests/constraint_weights/plan.rs +++ b/crates/solverforge/tests/constraint_weights/plan.rs @@ -4,25 +4,32 @@ use solverforge::stream::ConstraintFactory; use crate::{Task, Worker}; +/// Workers, tasks and per-constraint weights for the weighting tests. #[planning_solution( constraints = "constraints", solver_toml = "../fixtures/constraint_weights_solver.toml" )] pub struct Plan { + /// Workers tasks can be assigned to. #[problem_fact_collection] pub workers: Vec, + /// Tasks the solver assigns. #[planning_entity_collection] pub tasks: Vec, + /// Weight multiplier per constraint name. #[constraint_weights] pub weights: ConstraintWeights, + /// The plan's score. #[planning_score] pub score: Option, } +/// Name of the constraint that rewards a task's preferred worker. pub const PREFERRED: &str = "Preferred worker"; +/// Name of the constraint that penalizes each worker's cost. pub const COST: &str = "Worker cost"; fn constraints() -> impl ConstraintSet { diff --git a/crates/solverforge/tests/constraint_weights/task.rs b/crates/solverforge/tests/constraint_weights/task.rs index 1a488da25..a7052a0d1 100644 --- a/crates/solverforge/tests/constraint_weights/task.rs +++ b/crates/solverforge/tests/constraint_weights/task.rs @@ -1,11 +1,15 @@ use solverforge::prelude::*; +/// A task with a preferred worker. #[planning_entity] pub struct Task { + /// Stable task id. #[planning_id] pub id: usize, + /// Id of the worker this task prefers. pub preferred: usize, + /// Assigned worker. #[planning_variable(value_range_provider = "workers")] pub worker: Option, } diff --git a/crates/solverforge/tests/constraint_weights/worker.rs b/crates/solverforge/tests/constraint_weights/worker.rs index 44676dc06..2e81950e6 100644 --- a/crates/solverforge/tests/constraint_weights/worker.rs +++ b/crates/solverforge/tests/constraint_weights/worker.rs @@ -1,8 +1,11 @@ use solverforge::prelude::*; +/// A worker with a cost. #[problem_fact] pub struct Worker { + /// Stable worker id. #[planning_id] pub id: usize, + /// Cost of assigning a task to this worker. pub cost: i64, } diff --git a/crates/solverforge/tests/derive_macros.rs b/crates/solverforge/tests/derive_macros.rs index c626a3a87..9245f715f 100644 --- a/crates/solverforge/tests/derive_macros.rs +++ b/crates/solverforge/tests/derive_macros.rs @@ -1,3 +1,6 @@ +//! The planning derive macros build the expected facts, entities, solutions and +//! descriptors. + // Integration tests for derive macros. use solverforge::__internal::{PlanningId, PlanningSolution as PlanningSolutionTrait}; diff --git a/crates/solverforge/tests/list_clarke_wright_publication.rs b/crates/solverforge/tests/list_clarke_wright_publication.rs index 732379071..6d6457b7f 100644 --- a/crates/solverforge/tests/list_clarke_wright_publication.rs +++ b/crates/solverforge/tests/list_clarke_wright_publication.rs @@ -1,3 +1,6 @@ +//! Clarke-Wright construction publishes its constructed list solution through +//! `SolverManager`. + use solverforge::{SolverEvent, SolverManager}; #[path = "list_clarke_wright_publication/domain/mod.rs"] diff --git a/crates/solverforge/tests/list_cvrp_k_opt_time_window.rs b/crates/solverforge/tests/list_cvrp_k_opt_time_window.rs index 992f0642b..a8b8c6bf6 100644 --- a/crates/solverforge/tests/list_cvrp_k_opt_time_window.rs +++ b/crates/solverforge/tests/list_cvrp_k_opt_time_window.rs @@ -1,3 +1,5 @@ +//! Stock CVRP k-opt moves reject reversals that break a time window. + use solverforge::{SolverEvent, SolverManager}; #[path = "list_cvrp_k_opt_time_window/domain/mod.rs"] diff --git a/crates/solverforge/tests/list_cvrp_union_lowering.rs b/crates/solverforge/tests/list_cvrp_union_lowering.rs index c34f9863d..e39b07928 100644 --- a/crates/solverforge/tests/list_cvrp_union_lowering.rs +++ b/crates/solverforge/tests/list_cvrp_union_lowering.rs @@ -1,3 +1,5 @@ +//! The compiled CVRP union selector lowers every node exactly once. + use solverforge::{SolverEvent, SolverManager}; #[path = "list_cvrp_k_opt_time_window/domain/mod.rs"] diff --git a/crates/solverforge/tests/mixed_variable_order_runtime.rs b/crates/solverforge/tests/mixed_variable_order_runtime.rs index 81c0d20d0..308fe0f97 100644 --- a/crates/solverforge/tests/mixed_variable_order_runtime.rs +++ b/crates/solverforge/tests/mixed_variable_order_runtime.rs @@ -1,3 +1,6 @@ +//! Generic construction orders a list variable before a scalar variable on the +//! same entity. + #[path = "mixed_variable_order_runtime/mod.rs"] mod domain; diff --git a/crates/solverforge/tests/mixed_variable_order_runtime/plan.rs b/crates/solverforge/tests/mixed_variable_order_runtime/plan.rs index ef9a4550b..1a22fd466 100644 --- a/crates/solverforge/tests/mixed_variable_order_runtime/plan.rs +++ b/crates/solverforge/tests/mixed_variable_order_runtime/plan.rs @@ -3,17 +3,21 @@ use solverforge::stream::ConstraintFactory; use crate::{Route, Visit}; +/// Routes and visits for the variable-order test. #[planning_solution( constraints = "constraints", solver_toml = "../fixtures/mixed_variable_order_runtime_solver.toml" )] pub struct Plan { + /// Routes the solver plans. #[planning_entity_collection] pub routes: Vec, + /// Visits the routes may take. #[problem_fact_collection] pub visits: Vec, + /// The plan's score. #[planning_score] pub score: Option, } diff --git a/crates/solverforge/tests/mixed_variable_order_runtime/route.rs b/crates/solverforge/tests/mixed_variable_order_runtime/route.rs index 8ee92c8f8..eded9aea5 100644 --- a/crates/solverforge/tests/mixed_variable_order_runtime/route.rs +++ b/crates/solverforge/tests/mixed_variable_order_runtime/route.rs @@ -1,13 +1,17 @@ use solverforge::prelude::*; +/// A route with a list variable and a scalar variable. #[planning_entity] pub struct Route { + /// Stable route id. #[planning_id] pub id: usize, + /// Visits on this route, in order. #[planning_list_variable(element_collection = "visits")] pub visits: Vec, + /// The visit this route starts with. #[planning_variable(value_range_provider = "visits", allows_unassigned = true)] pub first_visit: Option, } diff --git a/crates/solverforge/tests/mixed_variable_order_runtime/visit.rs b/crates/solverforge/tests/mixed_variable_order_runtime/visit.rs index 0a537c459..570c5f66b 100644 --- a/crates/solverforge/tests/mixed_variable_order_runtime/visit.rs +++ b/crates/solverforge/tests/mixed_variable_order_runtime/visit.rs @@ -1,7 +1,9 @@ use solverforge::prelude::*; +/// A visit a route can take. #[problem_fact] pub struct Visit { + /// Stable visit id. #[planning_id] pub id: usize, } diff --git a/crates/solverforge/tests/parallel_list_local_search.rs b/crates/solverforge/tests/parallel_list_local_search.rs index e216d5816..4aacb0bb2 100644 --- a/crates/solverforge/tests/parallel_list_local_search.rs +++ b/crates/solverforge/tests/parallel_list_local_search.rs @@ -1,3 +1,6 @@ +//! Parallel list local search keeps the trajectory and list shadows identical +//! across thread counts. + use solverforge::{ AppliedMoveTelemetry, CandidateTraceDisposition, SolverEvent, SolverManager, SolverTelemetry, SolverTerminalReason, diff --git a/crates/solverforge/tests/parallel_local_search.rs b/crates/solverforge/tests/parallel_local_search.rs index 7e4f8a3d9..3ca2b9c3d 100644 --- a/crates/solverforge/tests/parallel_local_search.rs +++ b/crates/solverforge/tests/parallel_local_search.rs @@ -1,3 +1,6 @@ +//! Parallel scalar local search keeps a fixed-work trajectory identical across +//! thread counts. + use solverforge::{ CandidateTraceDisposition, SolverEvent, SolverManager, SolverTelemetry, SolverTerminalReason, }; diff --git a/crates/solverforge/tests/projected_publication.rs b/crates/solverforge/tests/projected_publication.rs index dd0f066b1..754ce00ee 100644 --- a/crates/solverforge/tests/projected_publication.rs +++ b/crates/solverforge/tests/projected_publication.rs @@ -1,138 +1,15 @@ +//! Projected and cross-joined streams are public through the facade and infer +//! their output types. + use solverforge::prelude::*; use solverforge::stream::ConstraintFactory; use solverforge::IncrementalConstraint; -#[problem_fact] -pub struct Capacity { - #[planning_id] - pub id: usize, - pub bucket: usize, - pub amount: i64, -} - -#[planning_entity] -pub struct Assignment { - #[planning_id] - pub id: usize, - pub bucket: usize, - pub demand: i64, -} - -pub struct CapacityEntry { - pub bucket: usize, - pub delta: i64, -} - -pub struct AssignmentCapacity { - pub bucket: usize, - pub demand: i64, - pub capacity: i64, -} - -pub struct GroupRow { - pub group: usize, - pub parent: Option, -} - -#[planning_solution] -pub struct Plan { - #[problem_fact_collection] - pub capacities: Vec, - #[planning_entity_collection] - pub assignments: Vec, - #[planning_score] - pub score: Option, -} - -impl solverforge::__internal::PlanningModelSupport for Plan { - fn attach_descriptor_hooks(_descriptor: &mut solverforge::__internal::SolutionDescriptor) {} - - fn attach_runtime_scalar_hooks( - slot: solverforge::__internal::ScalarVariableSlot, - ) -> solverforge::__internal::ScalarVariableSlot { - slot - } - - fn validate_model(_descriptor: &solverforge::__internal::SolutionDescriptor) {} - - fn update_entity_shadows( - _solution: &mut Self, - _descriptor_index: usize, - _entity_index: usize, - ) -> bool { - false - } - - fn update_all_shadows(_solution: &mut Self) -> bool { - false - } -} - -struct AssignmentEntries; - -impl Projection for AssignmentEntries { - type Out = CapacityEntry; - const MAX_EMITS: usize = 1; - - fn project(&self, assignment: &Assignment, sink: &mut Sink) - where - Sink: ProjectionSink, - { - sink.emit(CapacityEntry { - bucket: assignment.bucket, - delta: assignment.demand, - }); - } -} - -struct CapacityEntries; - -impl Projection for CapacityEntries { - type Out = CapacityEntry; - const MAX_EMITS: usize = 1; - - fn project(&self, capacity: &Capacity, sink: &mut Sink) - where - Sink: ProjectionSink, - { - sink.emit(CapacityEntry { - bucket: capacity.bucket, - delta: -capacity.amount, - }); - } -} +#[path = "projected_publication/domain.rs"] +mod domain; -struct GroupRows; - -impl Projection for GroupRows { - type Out = GroupRow; - const MAX_EMITS: usize = 1; - - fn project(&self, assignment: &Assignment, sink: &mut Sink) - where - Sink: ProjectionSink, - { - sink.emit(GroupRow { - group: assignment.bucket, - parent: (assignment.demand >= 0).then_some(assignment.demand as usize), - }); - } -} - -struct CustomCapacityExtract; - -impl solverforge::stream::CollectionExtract for CustomCapacityExtract { - type Item = Capacity; - - fn extract<'s>(&self, plan: &'s Plan) -> &'s [Capacity] { - plan.capacities.as_slice() - } - - // Capacities are problem facts: no planning-variable change alters them. - fn change_source(&self) -> solverforge::stream::ChangeSource { - solverforge::stream::ChangeSource::Static - } -} +pub use domain::{Assignment, AssignmentCapacity, Capacity, CapacityEntry, GroupRow, Plan}; +use domain::{AssignmentEntries, CapacityEntries, CustomCapacityExtract, GroupRows}; #[test] fn projected_stream_is_public_and_infers_output_type() { diff --git a/crates/solverforge/tests/projected_publication/domain.rs b/crates/solverforge/tests/projected_publication/domain.rs new file mode 100644 index 000000000..e76c6e2cc --- /dev/null +++ b/crates/solverforge/tests/projected_publication/domain.rs @@ -0,0 +1,158 @@ +//! The capacity/assignment model and projections the projected-stream tests +//! score. + +use solverforge::prelude::*; + +/// Capacity available in one bucket. +#[problem_fact] +pub struct Capacity { + /// Stable capacity id. + #[planning_id] + pub id: usize, + /// Bucket this capacity belongs to. + pub bucket: usize, + /// Capacity amount. + pub amount: i64, +} + +/// Demand placed in one bucket. +#[planning_entity] +pub struct Assignment { + /// Stable assignment id. + #[planning_id] + pub id: usize, + /// Bucket this demand is placed in. + pub bucket: usize, + /// Demand amount. + pub demand: i64, +} + +/// Projected row: a signed capacity change for one bucket. +pub struct CapacityEntry { + /// Bucket the change applies to. + pub bucket: usize, + /// Signed capacity change. + pub delta: i64, +} + +/// Joined row: one assignment's demand next to its bucket's capacity. +pub struct AssignmentCapacity { + /// Shared bucket. + pub bucket: usize, + /// Assignment demand. + pub demand: i64, + /// Bucket capacity. + pub capacity: i64, +} + +/// Grouped row with an optional parent group. +pub struct GroupRow { + /// Group id. + pub group: usize, + /// Parent group id, if any. + pub parent: Option, +} + +/// Capacities and assignments scored by the projected-stream tests. +#[planning_solution] +pub struct Plan { + /// Bucket capacities. + #[problem_fact_collection] + pub capacities: Vec, + /// Demand assignments. + #[planning_entity_collection] + pub assignments: Vec, + /// The plan's score. + #[planning_score] + pub score: Option, +} + +impl solverforge::__internal::PlanningModelSupport for Plan { + fn attach_descriptor_hooks(_descriptor: &mut solverforge::__internal::SolutionDescriptor) {} + + fn attach_runtime_scalar_hooks( + slot: solverforge::__internal::ScalarVariableSlot, + ) -> solverforge::__internal::ScalarVariableSlot { + slot + } + + fn validate_model(_descriptor: &solverforge::__internal::SolutionDescriptor) {} + + fn update_entity_shadows( + _solution: &mut Self, + _descriptor_index: usize, + _entity_index: usize, + ) -> bool { + false + } + + fn update_all_shadows(_solution: &mut Self) -> bool { + false + } +} + +pub(crate) struct AssignmentEntries; + +impl Projection for AssignmentEntries { + type Out = CapacityEntry; + const MAX_EMITS: usize = 1; + + fn project(&self, assignment: &Assignment, sink: &mut Sink) + where + Sink: ProjectionSink, + { + sink.emit(CapacityEntry { + bucket: assignment.bucket, + delta: assignment.demand, + }); + } +} + +pub(crate) struct CapacityEntries; + +impl Projection for CapacityEntries { + type Out = CapacityEntry; + const MAX_EMITS: usize = 1; + + fn project(&self, capacity: &Capacity, sink: &mut Sink) + where + Sink: ProjectionSink, + { + sink.emit(CapacityEntry { + bucket: capacity.bucket, + delta: -capacity.amount, + }); + } +} + +pub(crate) struct GroupRows; + +impl Projection for GroupRows { + type Out = GroupRow; + const MAX_EMITS: usize = 1; + + fn project(&self, assignment: &Assignment, sink: &mut Sink) + where + Sink: ProjectionSink, + { + sink.emit(GroupRow { + group: assignment.bucket, + parent: (assignment.demand >= 0).then_some(assignment.demand as usize), + }); + } +} + +pub(crate) struct CustomCapacityExtract; + +impl solverforge::stream::CollectionExtract for CustomCapacityExtract { + type Item = Capacity; + + fn extract<'s>(&self, plan: &'s Plan) -> &'s [Capacity] { + plan.capacities.as_slice() + } + + // Capacities are problem facts: no planning-variable change alters them. + fn change_source(&self) -> solverforge::stream::ChangeSource { + solverforge::stream::ChangeSource::Static + } +} diff --git a/crates/solverforge/tests/realtime_constraint_weight_modes.rs b/crates/solverforge/tests/realtime_constraint_weight_modes.rs index ce85445ee..c1a14d4c2 100644 --- a/crates/solverforge/tests/realtime_constraint_weight_modes.rs +++ b/crates/solverforge/tests/realtime_constraint_weight_modes.rs @@ -1,3 +1,6 @@ +//! Mid-solve constraint-weight changes switch between weighted and unit scoring +//! and rescore the job. + // Mid-solve constraint weight changes across the director's weight modes. // // A job whose weights are all `1` scores on the unweighted director; a diff --git a/crates/solverforge/tests/realtime_list_problem_change.rs b/crates/solverforge/tests/realtime_list_problem_change.rs index 9e039f476..d9d35afa2 100644 --- a/crates/solverforge/tests/realtime_list_problem_change.rs +++ b/crates/solverforge/tests/realtime_list_problem_change.rs @@ -1,3 +1,5 @@ +//! A list-variable job routes an element added while it is solving. + use std::time::{Duration, Instant}; use solverforge::{Analyzable, ClosureProblemChange, SolverEvent, SolverManager}; diff --git a/crates/solverforge/tests/realtime_problem_change.rs b/crates/solverforge/tests/realtime_problem_change.rs index 251cf77f7..fb68a4bb3 100644 --- a/crates/solverforge/tests/realtime_problem_change.rs +++ b/crates/solverforge/tests/realtime_problem_change.rs @@ -1,3 +1,6 @@ +//! Real-time problem changes: applied mid-solve, queued while paused, and +//! rejected for finished or unknown jobs. + use solverforge::{ ClosureProblemChange, Director, ProblemChange, SolverEvent, SolverLifecycleState, SolverManager, SolverManagerError, diff --git a/crates/solverforge/tests/relational_join_publication.rs b/crates/solverforge/tests/relational_join_publication.rs index 9581a0cf6..9e4c9882e 100644 --- a/crates/solverforge/tests/relational_join_publication.rs +++ b/crates/solverforge/tests/relational_join_publication.rs @@ -1,3 +1,5 @@ +//! Relational join chains compile through the facade and publish hard scores. + /* Facade publication of the independent-key chained join. Exercises the shipped P3 fluent surface through `solverforge::` paths: diff --git a/crates/solverforge/tests/relational_owned_publication.rs b/crates/solverforge/tests/relational_owned_publication.rs index 8ba1782c9..4e52ac322 100644 --- a/crates/solverforge/tests/relational_owned_publication.rs +++ b/crates/solverforge/tests/relational_owned_publication.rs @@ -1,3 +1,6 @@ +//! Facade projections, groups, anti-joins and flattening work over owned rows +//! without cloning payloads. + #![allow(clippy::type_complexity)] // Test closures spell full row-view types deliberately. use solverforge::stream::{ diff --git a/crates/solverforge/tests/scalar_multi_module_runtime.rs b/crates/solverforge/tests/scalar_multi_module_runtime.rs index 625f84fc1..687508391 100644 --- a/crates/solverforge/tests/scalar_multi_module_runtime.rs +++ b/crates/solverforge/tests/scalar_multi_module_runtime.rs @@ -1,3 +1,6 @@ +//! `planning_model!` attaches scalar hooks declared in a different module from +//! the solution. + #[path = "scalar_multi_module_runtime/mod.rs"] mod domain; diff --git a/crates/solverforge/tests/scalar_multi_module_runtime/plan.rs b/crates/solverforge/tests/scalar_multi_module_runtime/plan.rs index cedc1af7e..3e5ab7261 100644 --- a/crates/solverforge/tests/scalar_multi_module_runtime/plan.rs +++ b/crates/solverforge/tests/scalar_multi_module_runtime/plan.rs @@ -3,17 +3,21 @@ use solverforge::stream::ConstraintFactory; use crate::{Task, WorkTask, Worker}; +/// Workers and tasks for the multi-module scalar hook test. #[planning_solution( constraints = "constraints", solver_toml = "../fixtures/scalar_multi_module_runtime_solver.toml" )] pub struct Plan { + /// Workers tasks can be assigned to. #[problem_fact_collection] pub workers: Vec, + /// Tasks the solver assigns. #[planning_entity_collection] pub tasks: Vec, + /// The plan's score. #[planning_score] pub score: Option, } diff --git a/crates/solverforge/tests/scalar_multi_module_runtime/task.rs b/crates/solverforge/tests/scalar_multi_module_runtime/task.rs index e10511523..5c59bf176 100644 --- a/crates/solverforge/tests/scalar_multi_module_runtime/task.rs +++ b/crates/solverforge/tests/scalar_multi_module_runtime/task.rs @@ -2,11 +2,14 @@ use solverforge::prelude::*; use super::Plan; +/// A task whose worker variable uses hooks declared in this module. #[planning_entity] pub struct Task { + /// Stable task id. #[planning_id] pub id: usize, + /// Assigned worker, if any. #[planning_variable( value_range_provider = "workers", allows_unassigned = true, @@ -34,4 +37,5 @@ pub(super) fn worker_priority(_plan: &Plan, task: &Task, worker: usize) -> i64 { task.id.abs_diff(worker) as i64 } +/// Alias the solution uses for its entity collection. pub type WorkTask = Task; diff --git a/crates/solverforge/tests/scalar_multi_module_runtime/worker.rs b/crates/solverforge/tests/scalar_multi_module_runtime/worker.rs index 8b8ddc02d..f8ee4d42f 100644 --- a/crates/solverforge/tests/scalar_multi_module_runtime/worker.rs +++ b/crates/solverforge/tests/scalar_multi_module_runtime/worker.rs @@ -1,7 +1,9 @@ use solverforge::prelude::*; +/// A worker tasks can be assigned to. #[problem_fact] pub struct Worker { + /// Stable worker id. #[planning_id] pub id: usize, } diff --git a/crates/solverforge/tests/scalar_runtime_publication.rs b/crates/solverforge/tests/scalar_runtime_publication.rs index 6b37c521b..c1e2be8e8 100644 --- a/crates/solverforge/tests/scalar_runtime_publication.rs +++ b/crates/solverforge/tests/scalar_runtime_publication.rs @@ -1,3 +1,5 @@ +//! A scalar-only solution runs construction in the retained runtime. + use solverforge::{SolverEvent, SolverManager, SolverTerminalReason}; #[path = "scalar_runtime_publication/domain/mod.rs"] diff --git a/crates/solverforge/tests/scalar_runtime_selector_assembly.rs b/crates/solverforge/tests/scalar_runtime_selector_assembly.rs index 02a274a2c..28c781f34 100644 --- a/crates/solverforge/tests/scalar_runtime_selector_assembly.rs +++ b/crates/solverforge/tests/scalar_runtime_selector_assembly.rs @@ -1,3 +1,5 @@ +//! A scalar-only solution builds its default move selector. + use solverforge::{SolverEvent, SolverLifecycleState, SolverManager}; #[path = "scalar_runtime_selector_assembly/domain/mod.rs"] diff --git a/crates/solverforge/tests/scalar_target_source_reuse.rs b/crates/solverforge/tests/scalar_target_source_reuse.rs index 78fc735fa..d929f878c 100644 --- a/crates/solverforge/tests/scalar_target_source_reuse.rs +++ b/crates/solverforge/tests/scalar_target_source_reuse.rs @@ -1,3 +1,5 @@ +//! One bound generated source can build several scalar targets. + use solverforge::prelude::*; #[path = "scalar_target_source_reuse/domain/mod.rs"] diff --git a/crates/solverforge/tests/solvable_runtime.rs b/crates/solverforge/tests/solvable_runtime.rs index c2fb952ef..b942f6468 100644 --- a/crates/solverforge/tests/solvable_runtime.rs +++ b/crates/solverforge/tests/solvable_runtime.rs @@ -1,3 +1,6 @@ +//! Runtime facade types: candidate-trace configuration, provenance and events +//! from a manual `Solvable`. + use solverforge::__internal::PlanningSolution as PlanningSolutionTrait; use solverforge::{ CandidateTraceConfig, CandidateTraceExternalDigest, QualifiedCandidateTraceRunProvenance,