Skip to content
Merged
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
8 changes: 5 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,16 +175,18 @@ All hot-path code must stay monomorphized.
- Do not introduce `Box<dyn Trait>` in hot paths.
- Do not introduce `Arc<T>` or `Rc<T>`.
- Do not introduce `dyn Trait` unless it is an existing intentional boundary.
- Avoid `.clone()` in move evaluation and scoring paths.
- Avoid `.clone()` in move evaluation and scoring paths. Scoring streams do
not require `Clone` on entity types, so generic scoring code cannot clone an
entity; do not add a `Clone` bound to make one compile. Constraint analysis
describes an entity by its type name and `Debug` rendering (`EntityRef`) and
keeps no copy of it.
- Preserve concrete types through the full solver pipeline.

Intentional type-erasure boundaries that should not be "fixed":

- `EntityExtractor` in `solverforge-core`: runtime-erased
`SolutionDescriptor` access only. Canonical generated `RuntimeModel` and
scoring-stream paths retain concrete collection types.
- Analysis `EntityRef` payloads in `solverforge-scoring`: explanation and
reporting boundary only.
- `DynamicScalarAccess`, `DynamicListAccess`, `DynamicListMetadata`, and
`DynamicScalarAssignmentMetadata`: host-language dynamic-model slot
boundaries only.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ help: the trait `CollectionExtract<S>` is implemented for `UniConstraintStream<S
| / impl<S, A, E, F, Sc> CollectionExtract<S> for UniConstraintStream<S, A, E, F, Sc>
| | where
| | S: Send + Sync + 'static,
| | A: Clone + Send + Sync + 'static,
| | A: Send + Sync + 'static,
| | E: CollectionExtract<S, Item = A>,
| | F: UniFilter<S, A>,
| | Sc: Score + 'static,
Expand Down Expand Up @@ -44,7 +44,7 @@ help: the trait `CollectionExtract<S>` is implemented for `UniConstraintStream<S
| / impl<S, A, E, F, Sc> CollectionExtract<S> for UniConstraintStream<S, A, E, F, Sc>
| | where
| | S: Send + Sync + 'static,
| | A: Clone + Send + Sync + 'static,
| | A: Send + Sync + 'static,
| | E: CollectionExtract<S, Item = A>,
| | F: UniFilter<S, A>,
| | Sc: Score + 'static,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ struct Entry {
delta: i64,
}

#[derive(Clone, Debug)]
#[derive(Debug)]
struct Employee {
id: usize,
}
Expand Down
9 changes: 5 additions & 4 deletions crates/solverforge-scoring/WIREFRAME.md
Original file line number Diff line number Diff line change
Expand Up @@ -718,8 +718,9 @@ terminals of one shared node. Weight adapters (`GroupAdapter`/`GroupWeight`,
row. Sharing is compiler-owned; there are no runtime node caches.

A shared terminal requires its operator's rows to implement `ExplainRow`, so
every grouped and complemented builder's `named` requires `Clone + Debug`
entities (projected `Out` rows excepted: they justify nothing themselves).
every grouped and complemented builder's `named` requires `Debug` entities
(projected `Out` rows excepted: they justify nothing themselves). No stream
requires `Clone` on an entity type.
Detailed analysis (`get_matches`, `ConstraintSet::evaluate_detailed[_weighted]`)
reports, for every terminal on the node, one match per row whose coded weight
is not zero, scored at the terminal's multiplier and justified by the row's
Expand Down Expand Up @@ -748,8 +749,8 @@ Constraints own their `ConstraintRef` once. Metadata and analysis types borrow t

**`ConstraintMetadata<'a>`** — `{ constraint_ref: &'a ConstraintRef, is_hard: bool }`; `name()` returns the short constraint name, and `full_name()` returns the package-qualified identity used for exact matching.

**`EntityRef`** — Public fields `{ type_name: String, display: String }` plus a private cloned entity snapshot for typed downcast access.
- Methods: `new()`, `with_display()`, `as_entity::<T>()`, `short_type_name()`
**`EntityRef`** — `{ type_name: String, display: String }`: the entity's type name and `Debug` rendering, taken when a match is explained. It keeps no copy of the entity.
- Methods: `new<T: Debug + ?Sized>(&T)`, `short_type_name()`
- Implements `Hash + Eq` (by display string)

**`ConstraintJustification`** — `{ entities: Vec<EntityRef>, description: String }`.
Expand Down
28 changes: 13 additions & 15 deletions crates/solverforge-scoring/public-api.txt

Large diffs are not rendered by default.

55 changes: 10 additions & 45 deletions crates/solverforge-scoring/src/api/analysis.rs
Original file line number Diff line number Diff line change
@@ -1,54 +1,34 @@
//! Score analysis types for detailed constraint tracking.
//!
//! This module provides types for analyzing constraint matches in detail,
//! including which entities are involved in each match, score explanations,
//! and entity-level indictments.
//! This module provides types for analyzing constraint matches in detail:
//! each match's score and the entities that caused it.

use std::any::Any;
use std::fmt::Debug;
use std::hash::{Hash, Hasher};
use std::sync::Arc;

use solverforge_core::score::Score;
use solverforge_core::ConstraintRef;

/// Reference to an entity involved in a constraint match.
/// Uses type erasure to allow storing references to different entity types
/// in a single collection.
#[derive(Clone)]
/// An entity involved in a constraint match, as constraint analysis reports
/// it: the entity's type name and its `Debug` rendering, taken when the match
/// is explained. It holds no copy of the entity, so explaining a match
/// requires only `Debug` on the entity type.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct EntityRef {
/// Type name of the entity (e.g., "Shift", "Employee").
pub type_name: String,
/// String representation for display.
pub display: String,
// Type-erased entity for programmatic access.
entity: Arc<dyn Any + Send + Sync>,
}

impl EntityRef {
/// Creates a new entity reference from a concrete entity.
pub fn new<T: Clone + Debug + Send + Sync + 'static>(entity: &T) -> Self {
/// Describes `entity` by its type name and `Debug` rendering.
pub fn new<T: Debug + ?Sized>(entity: &T) -> Self {
Self {
type_name: std::any::type_name::<T>().to_string(),
display: format!("{:?}", entity),
entity: Arc::new(entity.clone()),
display: format!("{entity:?}"),
}
}

/// Creates an entity reference with a custom display string.
pub fn with_display<T: Clone + Send + Sync + 'static>(entity: &T, display: String) -> Self {
Self {
type_name: std::any::type_name::<T>().to_string(),
display,
entity: Arc::new(entity.clone()),
}
}

/// Attempts to downcast to the concrete entity type.
pub fn as_entity<T: 'static>(&self) -> Option<&T> {
self.entity.downcast_ref::<T>()
}

/// Returns the short type name (without module path).
pub fn short_type_name(&self) -> &str {
self.type_name
Expand All @@ -67,21 +47,6 @@ impl Debug for EntityRef {
}
}

impl PartialEq for EntityRef {
fn eq(&self, other: &Self) -> bool {
self.type_name == other.type_name && self.display == other.display
}
}

impl Eq for EntityRef {}

impl Hash for EntityRef {
fn hash<H: Hasher>(&self, state: &mut H) {
self.type_name.hash(state);
self.display.hash(state);
}
}

/// Justification for why a constraint matched.
#[derive(Debug, Clone)]
pub struct ConstraintJustification {
Expand Down
21 changes: 12 additions & 9 deletions crates/solverforge-scoring/src/api/tests/analysis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,20 @@ fn test_entity_ref_creation() {
assert!(entity_ref.display.contains("1"));
}

/// Explaining a match needs only `Debug`: the entity type is neither `Clone`
/// nor `'static`, and the reference keeps no copy of it.
#[test]
fn test_entity_ref_downcast() {
let entity = TestEntity {
id: 42,
name: "Answer".to_string(),
};
let entity_ref = EntityRef::new(&entity);
fn test_entity_ref_describes_a_borrowed_debug_only_entity() {
#[derive(Debug)]
struct Borrowed<'a> {
#[allow(dead_code)]
name: &'a str,
}
let name = String::from("Answer");
let entity_ref = EntityRef::new(&Borrowed { name: &name });

let recovered: Option<&TestEntity> = entity_ref.as_entity();
assert!(recovered.is_some());
assert_eq!(recovered.unwrap().id, 42);
assert_eq!(entity_ref.short_type_name(), "Borrowed<'_>");
assert_eq!(entity_ref.display, r#"Borrowed { name: "Answer" }"#);
}

#[test]
Expand Down
4 changes: 2 additions & 2 deletions crates/solverforge-scoring/src/constraint/balance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ where
impl<S, A, K, E, F, KF, Sc> BalanceConstraint<S, A, K, E, F, KF, Sc>
where
S: Send + Sync + 'static,
A: Clone + Send + Sync + 'static,
A: Send + Sync + 'static,
K: Clone + Eq + Hash + Send + Sync + 'static,
E: crate::stream::collection_extract::CollectionExtract<S, Item = A>,
F: UniFilter<S, A>,
Expand Down Expand Up @@ -241,7 +241,7 @@ impl<S, A, K, E, F, KF, Sc> IncrementalConstraint<S, Sc>
for BalanceConstraint<S, A, K, E, F, KF, Sc>
where
S: Send + Sync + 'static,
A: Clone + Send + Sync + 'static,
A: Send + Sync + 'static,
K: Clone + Eq + Hash + Send + Sync + 'static,
E: crate::stream::collection_extract::CollectionExtract<S, Item = A>,
F: UniFilter<S, A>,
Expand Down
4 changes: 2 additions & 2 deletions crates/solverforge-scoring/src/constraint/incremental.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ where
impl<S, A, E, F, W, Sc> IncrementalUniConstraint<S, A, E, F, W, Sc>
where
S: Send + Sync + 'static,
A: Clone + Send + Sync + 'static,
A: Send + Sync + 'static,
E: crate::stream::collection_extract::CollectionExtract<S, Item = A>,
F: Fn(&S, &A) -> bool + Send + Sync,
W: Fn(&A) -> Sc + Send + Sync,
Expand Down Expand Up @@ -96,7 +96,7 @@ where
impl<S, A, E, F, W, Sc> IncrementalConstraint<S, Sc> for IncrementalUniConstraint<S, A, E, F, W, Sc>
where
S: Send + Sync + 'static,
A: Clone + Debug + Send + Sync + 'static,
A: Debug + Send + Sync + 'static,
E: crate::stream::collection_extract::CollectionExtract<S, Item = A>,
F: Fn(&S, &A) -> bool + Send + Sync,
W: Fn(&A) -> Sc + Send + Sync,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ where
Acc: Accumulator<V, R> + 'static,
V: Send + Sync + 'static,
R: Send + Sync + 'static,
B: Clone + Send + Sync + 'static,
B: Send + Sync + 'static,
EB: crate::stream::collection_extract::CollectionExtract<S, Item = B> + 'static,
P: crate::stream::joiner::plan::IndexedPlan + 'static,
for<'a> P:
Expand Down Expand Up @@ -156,7 +156,7 @@ where
Acc: Accumulator<V, R> + 'static,
V: Send + Sync + 'static,
R: Send + Sync + 'static,
B: Clone + Send + Sync + 'static,
B: Send + Sync + 'static,
EB: crate::stream::collection_extract::CollectionExtract<S, Item = B> + 'static,
P: crate::stream::joiner::plan::IndexedPlan + 'static,
for<'a> P:
Expand Down
17 changes: 7 additions & 10 deletions crates/solverforge-scoring/src/constraint/tests/cross_bi_incr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::sync::{
Arc,
};

use crate::api::analysis::EntityRef;
use crate::api::constraint_set::IncrementalConstraint;
use crate::stream::collection_extract::{source, ChangeSource, CollectionExtract};
use crate::stream::collector::sum;
Expand Down Expand Up @@ -298,22 +299,18 @@ fn test_cross_bi_get_matches_works_without_initialize() {
assert_eq!(matches[0].score, SoftScore::of(-1));
assert_eq!(matches[0].justification.entities.len(), 2);
assert_eq!(
matches[0].justification.entities[0]
.as_entity::<Shift>()
.unwrap(),
&Shift {
matches[0].justification.entities[0],
EntityRef::new(&Shift {
employee_id: Some(0),
day: 5,
}
})
);
assert_eq!(
matches[0].justification.entities[1]
.as_entity::<Employee>()
.unwrap(),
&Employee {
matches[0].justification.entities[1],
EntityRef::new(&Employee {
id: 0,
unavailable_days: vec![5],
}
})
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ the match scores must sum to the constraint's score: before initialization,
after it, and across mutations. Shared grouped nodes report matches for every
terminal they carry, scaled by each terminal's weight multiplier.

The entities implement only `Debug`: explaining a match copies nothing.

Roster: nurse 0 works shifts 0 and 1, nurse 1 works shift 2, shift 3 is
unassigned, nurse 2 works nothing.
*/
Expand All @@ -22,20 +24,19 @@ use crate::stream::ConstraintFactory;

const UNASSIGNED: usize = usize::MAX;

#[derive(Clone, Debug)]
#[derive(Debug)]
struct Nurse {
id: usize,
}

#[derive(Clone, Debug)]
#[derive(Debug)]
struct Shift {
// Read only through `Debug`: it tells the shifts apart in justifications.
#[allow(dead_code)]
id: usize,
nurse: Option<usize>,
}

#[derive(Clone)]
struct Roster {
shifts: Vec<Shift>,
nurses: Vec<Nurse>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ macro_rules! impl_nary_arity_stream_common {
impl<S, A, K, E, KE, Sc> $stream<S, A, K, E, KE, super::filter::TrueFilter, Sc>
where
S: Send + Sync + 'static,
A: Clone + std::hash::Hash + PartialEq + Send + Sync + 'static,
A: std::hash::Hash + PartialEq + Send + Sync + 'static,
K: Eq + std::hash::Hash + Clone + Send + Sync,
E: super::collection_extract::CollectionExtract<S, Item = A>,
KE: super::key_extract::KeyExtract<S, A, K>,
Expand All @@ -95,7 +95,7 @@ macro_rules! impl_nary_arity_stream_common {
impl<S, A, K, E, KE, F, Sc> $stream<S, A, K, E, KE, F, Sc>
where
S: Send + Sync + 'static,
A: Clone + std::hash::Hash + PartialEq + Send + Sync + 'static,
A: std::hash::Hash + PartialEq + Send + Sync + 'static,
K: Eq + std::hash::Hash + Clone + Send + Sync,
E: super::collection_extract::CollectionExtract<S, Item = A>,
KE: super::key_extract::KeyExtract<S, A, K>,
Expand Down Expand Up @@ -358,7 +358,7 @@ macro_rules! impl_nary_arity_stream_common {
impl<S, A, K, E, KE, F, W, Sc> $builder<S, A, K, E, KE, F, W, Sc>
where
S: Send + Sync + 'static,
A: Clone + Send + Sync + 'static,
A: Send + Sync + 'static,
K: Eq + std::hash::Hash + Clone + Send + Sync,
E: super::collection_extract::CollectionExtract<S, Item = A>,
KE: super::key_extract::KeyExtract<S, A, K>,
Expand Down
4 changes: 2 additions & 2 deletions crates/solverforge-scoring/src/stream/balance_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ where
impl<S, A, K, E, F, KF, Sc> BalanceConstraintStream<S, A, K, E, F, KF, Sc>
where
S: Send + Sync + 'static,
A: Clone + Send + Sync + 'static,
A: Send + Sync + 'static,
K: Clone + Eq + Hash + Send + Sync + 'static,
E: CollectionExtract<S, Item = A>,
F: UniFilter<S, A>,
Expand Down Expand Up @@ -167,7 +167,7 @@ where
impl<S, A, K, E, F, KF, Sc> BalanceConstraintBuilder<S, A, K, E, F, KF, Sc>
where
S: Send + Sync + 'static,
A: Clone + Send + Sync + 'static,
A: Send + Sync + 'static,
K: Clone + Eq + Hash + Send + Sync + 'static,
E: CollectionExtract<S, Item = A>,
F: UniFilter<S, A>,
Expand Down
2 changes: 1 addition & 1 deletion crates/solverforge-scoring/src/stream/bi_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ super::arity_stream_macros::impl_arity_stream!(bi, BiConstraintStream, BiConstra
impl<S, A, K, E, KE, F, Sc> BiConstraintStream<S, A, K, E, KE, F, Sc>
where
S: Send + Sync + 'static,
A: Clone + Hash + PartialEq + Send + Sync + 'static,
A: Hash + PartialEq + Send + Sync + 'static,
K: Eq + Hash + Clone + Send + Sync,
E: super::collection_extract::CollectionExtract<S, Item = A>,
KE: super::key_extract::KeyExtract<S, A, K>,
Expand Down
2 changes: 1 addition & 1 deletion crates/solverforge-scoring/src/stream/chain_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ where
target: (EB, P),
) -> Chain<S, JoinNode<S, O, CollectionNodeAlias<S, EB>, P::Plan>, Sc>
where
B: Clone + Send + Sync + 'static,
B: Send + Sync + 'static,
EB: CollectionExtract<S, Item = B> + 'static,
P: CompileCondition + 'static,
P::Plan: IndexedPlan,
Expand Down
8 changes: 4 additions & 4 deletions crates/solverforge-scoring/src/stream/complemented_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,8 @@ impl<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, Sc>
ComplementedConstraintStream<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, Sc>
where
S: Send + Sync + 'static,
A: Clone + Send + Sync + 'static,
B: Clone + Send + Sync + 'static,
A: Send + Sync + 'static,
B: Send + Sync + 'static,
K: Clone + Eq + Hash + Send + Sync + 'static,
EA: CollectionExtract<S, Item = A>,
EB: CollectionExtract<S, Item = B>,
Expand Down Expand Up @@ -303,8 +303,8 @@ impl<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, W, Sc>
ComplementedConstraintBuilder<S, A, B, K, EA, EB, KA, KB, C, V, R, Acc, D, W, Sc>
where
S: Send + Sync + 'static,
A: Clone + std::fmt::Debug + Send + Sync + 'static,
B: Clone + std::fmt::Debug + Send + Sync + 'static,
A: std::fmt::Debug + Send + Sync + 'static,
B: std::fmt::Debug + Send + Sync + 'static,
K: Clone + Eq + Hash + Send + Sync + 'static,
EA: CollectionExtract<S, Item = A> + 'static,
EB: CollectionExtract<S, Item = B> + 'static,
Expand Down
Loading
Loading