1
//! Compact's structural work estimate for Minion's collection representations.
2
//!
3
//! One primitive variable and one estimated expanded structural AST node each cost one unit.
4
//! Domain bits break ties. These are work counts, not fitted coefficients or predicted seconds.
5
//! Matrix/tuple children use their ordinary component layouts; unknown layouts, large probes
6
//! and unsupported domains decline the entire comparison, falling back to domain cardinality.
7
//! User constraints and search behaviour are deliberately not predicted by this estimate.
8

            
9
use conjure_cp::ast::comprehension::ComprehensionQualifier;
10
use conjure_cp::ast::{DeclarationPtr, DomainPtr, Expression, GroundDomain, Name};
11
use conjure_cp::representation::{ReprRulePtr, get_repr_rules};
12
use conjure_cp::settings::{Channelling, SolverFamily, channelling, try_current_solver_family};
13
use std::collections::HashMap;
14
use uniplate::Uniplate;
15

            
16
// Resource bounds, not scoring weights. Refuse lookahead rather than partially rank candidates.
17
const MAX_EXTENT: u64 = 256;
18
const MAX_DEPTH: usize = 8;
19
const MAX_VISITS: usize = 16_384;
20

            
21
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
22
struct Cost {
23
    variables: u64,
24
    structural_nodes: u64,
25
    domain_bits: u64,
26
}
27

            
28
impl Cost {
29
2643
    fn add(self, other: Self) -> Option<Self> {
30
        Some(Self {
31
2643
            variables: self.variables.checked_add(other.variables)?,
32
2643
            structural_nodes: self.structural_nodes.checked_add(other.structural_nodes)?,
33
2643
            domain_bits: self.domain_bits.checked_add(other.domain_bits)?,
34
        })
35
2643
    }
36

            
37
336
    fn times(self, count: u64) -> Option<Self> {
38
        Some(Self {
39
336
            variables: self.variables.checked_mul(count)?,
40
336
            structural_nodes: self.structural_nodes.checked_mul(count)?,
41
336
            domain_bits: self.domain_bits.checked_mul(count)?,
42
        })
43
336
    }
44

            
45
1350
    fn key(self) -> (u64, u64) {
46
1350
        (
47
1350
            self.variables.saturating_add(self.structural_nodes),
48
1350
            self.domain_bits,
49
1350
        )
50
1350
    }
51
}
52

            
53
49280
pub(super) fn choose(
54
49280
    declaration: &DeclarationPtr,
55
49280
    candidates: &[(ReprRulePtr, usize)],
56
49280
) -> Option<ReprRulePtr> {
57
49280
    if try_current_solver_family() != Some(SolverFamily::Minion) || channelling() != Channelling::No
58
    {
59
49070
        return None;
60
210
    }
61
210
    let domain = declaration.domain()?;
62
210
    if !(declaration.as_find().is_some() || declaration.is_find_auxiliary())
63
210
        || !is_collection(&domain)
64
    {
65
        return None;
66
210
    }
67
210
    let mut estimates = Vec::new();
68
210
    for &(rule, old_score) in candidates {
69
630
        let mut estimator = Estimator::default();
70
630
        let Some(cost) = estimator.representation(declaration, rule, 0) else {
71
            tracing::info!(declaration = %declaration.name(), representation = rule.name(),
72
                "compact structural cost unavailable; using domain cardinality for this choice");
73
            return None;
74
        };
75
630
        tracing::info!(declaration = %declaration.name(), representation = rule.name(),
76
252
            variables = cost.variables, structural_nodes = cost.structural_nodes,
77
252
            domain_bits = cost.domain_bits, units = cost.key().0, domain_score = old_score,
78
252
            "compact representation cost");
79
630
        estimates.push((rule, cost, old_score));
80
    }
81
630
    let &(selected, _, _) = estimates.iter().min_by_key(|(rule, cost, old_score)| {
82
630
        (
83
630
            cost.key(),
84
630
            rule.short_name() == "packed",
85
630
            *old_score,
86
630
            super::representation::representation_fallback_rank(*rule),
87
630
            rule.name(),
88
630
        )
89
630
    })?;
90
210
    tracing::info!(declaration = %declaration.name(), representation = selected.name(),
91
84
        "compact selected representation");
92
210
    Some(selected)
93
49280
}
94

            
95
336
fn is_collection(domain: &DomainPtr) -> bool {
96
336
    domain.resolve().is_ok_and(|domain| {
97
336
        matches!(
98
336
            domain.as_ref(),
99
            GroundDomain::Function(..) | GroundDomain::Set(..) | GroundDomain::Relation(..)
100
        )
101
336
    })
102
336
}
103

            
104
struct Estimator {
105
    remaining: usize,
106
    domains: HashMap<DomainPtr, Option<Cost>>,
107
}
108

            
109
impl Default for Estimator {
110
630
    fn default() -> Self {
111
630
        Self {
112
630
            remaining: MAX_VISITS,
113
630
            domains: HashMap::new(),
114
630
        }
115
630
    }
116
}
117

            
118
impl Estimator {
119
3969
    fn visit(&mut self, depth: usize) -> Option<()> {
120
3969
        if depth > MAX_DEPTH {
121
            return None;
122
3969
        }
123
3969
        self.remaining = self.remaining.checked_sub(1)?;
124
3969
        Some(())
125
3969
    }
126

            
127
990
    fn representation(
128
990
        &mut self,
129
990
        decl: &DeclarationPtr,
130
990
        rule: ReprRulePtr,
131
990
        depth: usize,
132
990
    ) -> Option<Cost> {
133
990
        self.visit(depth)?;
134
990
        let domain = decl.domain()?.resolve().ok()?;
135
        // Check physical extents before asking initialisers to allocate variables or constraints.
136
990
        bounded_extent(domain.as_ref())?;
137
990
        let probe = rule.probe_structure_for(decl).ok()?;
138
990
        let mut cost = Cost::default();
139
990
        for constraint in &probe.constraints {
140
3222
            cost.structural_nodes = cost
141
3222
                .structural_nodes
142
3222
                .checked_add(self.expression(constraint)?)?;
143
        }
144
990
        for child in probe.domains {
145
2517
            cost = cost.add(self.domain(&child, depth + 1)?)?;
146
        }
147
990
        Some(cost)
148
990
    }
149

            
150
2979
    fn domain(&mut self, domain: &DomainPtr, depth: usize) -> Option<Cost> {
151
2979
        self.visit(depth)?;
152
2979
        if let Some(cost) = self.domains.get(domain) {
153
1602
            return *cost;
154
1377
        }
155
        // Also stops a representation that accidentally introduces its own domain again.
156
1377
        self.domains.insert(domain.clone(), None);
157
1377
        let ground = domain.resolve().ok()?;
158
1377
        let cost = match ground.as_ref() {
159
            GroundDomain::Bool | GroundDomain::Int(..) => {
160
852
                let cardinality = ground.length().ok()?;
161
852
                Cost {
162
852
                    variables: 1,
163
852
                    structural_nodes: 0,
164
852
                    domain_bits: u64::from(
165
852
                        u64::BITS - cardinality.saturating_sub(1).leading_zeros(),
166
852
                    ),
167
852
                }
168
            }
169
            GroundDomain::Matrix(inner, indices, preference) => {
170
336
                if preference.as_deref().is_some_and(|p| p != "components") {
171
                    return None;
172
336
                }
173
399
                let cells = product_lengths(indices.iter().map(|d| d.as_ref()))?;
174
336
                if cells > MAX_EXTENT {
175
                    return None;
176
336
                }
177
336
                self.domain(&inner.clone().into(), depth + 1)?
178
336
                    .times(cells)?
179
            }
180
            GroundDomain::Tuple(fields, preference) => {
181
63
                if preference.as_deref().is_some_and(|p| p != "components") {
182
                    return None;
183
63
                }
184
63
                let mut cost = Cost::default();
185
63
                for field in fields {
186
126
                    cost = cost.add(self.domain(&field.clone().into(), depth + 1)?)?;
187
                }
188
63
                cost
189
            }
190
126
            _ if is_collection(domain) => {
191
                let decl =
192
126
                    DeclarationPtr::new_find(Name::user("__compact_cost_probe"), domain.clone());
193
126
                let preference = domain.representation_preference();
194
126
                let mut rules: Vec<_> = get_repr_rules()
195
4662
                    .filter(|rule| {
196
4662
                        !rule.is_integer_encoding()
197
3654
                            && rule.applies_to(SolverFamily::Minion)
198
3402
                            && preference.is_none_or(|pref| rule.short_name() == pref)
199
4662
                    })
200
                    .collect();
201
31500
                rules.sort_by_key(|rule| rule.name());
202
126
                let mut best: Option<Cost> = None;
203
126
                for rule in rules {
204
3402
                    if rule.probe_for(&decl).is_err() {
205
3042
                        continue;
206
360
                    }
207
                    // Do not silently treat an applicable but unestimated layout as expensive.
208
360
                    let candidate = self.representation(&decl, rule, depth + 1)?;
209
360
                    if best.is_none_or(|cost| candidate.key() < cost.key()) {
210
189
                        best = Some(candidate);
211
171
                    }
212
                }
213
126
                best?
214
            }
215
            _ => return None,
216
        };
217
1377
        self.domains.insert(domain.clone(), Some(cost));
218
1377
        Some(cost)
219
2979
    }
220

            
221
63141
    fn expression(&mut self, expression: &Expression) -> Option<u64> {
222
63141
        self.remaining = self.remaining.checked_sub(1)?;
223
63141
        if let Expression::Comprehension(_, comprehension) = expression {
224
180
            let mut iterations = 1u64;
225
180
            let mut body = self.expression(&comprehension.return_expression)?;
226
180
            for qualifier in &comprehension.qualifiers {
227
360
                match qualifier {
228
                    ComprehensionQualifier::Generator { ptr } => {
229
126
                        iterations = iterations.checked_mul(ptr.domain()?.length().ok()?)?;
230
                    }
231
                    ComprehensionQualifier::ExpressionGenerator { ptr } => {
232
234
                        let source = ptr.as_quantified_expr()?;
233
234
                        let ground = source.domain_of()?.resolve().ok()?;
234
234
                        iterations = iterations.checked_mul(collection_extent(ground.as_ref())?)?;
235
                    }
236
                    ComprehensionQualifier::Condition(condition) => {
237
                        body = body.checked_add(self.expression(condition)?)?;
238
                    }
239
                }
240
            }
241
            // Guards may prune iterations; this deliberately uses the full upper bound.
242
180
            return 1u64.checked_add(iterations.checked_mul(body)?);
243
62961
        }
244
62961
        expression.children().iter().try_fold(1u64, |nodes, child| {
245
59739
            nodes.checked_add(self.expression(child)?)
246
59739
        })
247
63141
    }
248
}
249

            
250
750
fn product_lengths<'a>(mut domains: impl Iterator<Item = &'a GroundDomain>) -> Option<u64> {
251
1227
    domains.try_fold(1u64, |product, domain| {
252
1227
        product.checked_mul(domain.length().ok()?)
253
1227
    })
254
750
}
255

            
256
234
fn collection_extent(domain: &GroundDomain) -> Option<u64> {
257
234
    let extent = match domain {
258
        GroundDomain::Matrix(_, indices, _) => product_lengths(indices.iter().map(|d| d.as_ref()))?,
259
        GroundDomain::Set(attributes, inner) => attributes
260
            .size
261
            .high()
262
            .copied()
263
            .map(u64::try_from)
264
            .transpose()
265
            .ok()?
266
            .unwrap_or(inner.length().ok()?)
267
            .min(inner.length().ok()?),
268
        GroundDomain::Relation(attributes, fields) => {
269
468
            let universe = product_lengths(fields.iter().map(|d| d.as_ref()))?;
270
234
            attributes
271
234
                .size
272
234
                .high()
273
234
                .copied()
274
234
                .map(u64::try_from)
275
234
                .transpose()
276
234
                .ok()?
277
234
                .unwrap_or(universe)
278
234
                .min(universe)
279
        }
280
        _ => return None,
281
    };
282
234
    (extent <= MAX_EXTENT).then_some(extent)
283
234
}
284

            
285
990
fn bounded_extent(domain: &GroundDomain) -> Option<()> {
286
990
    let extent = match domain {
287
        GroundDomain::Function(_, keys, values) => {
288
189
            keys.length().ok()?.checked_mul(values.length().ok()?)?
289
        }
290
621
        GroundDomain::Set(_, inner) => inner.length().ok()?,
291
360
        GroundDomain::Relation(_, fields) => product_lengths(fields.iter().map(|d| d.as_ref()))?,
292
        _ => return None,
293
    };
294
990
    (extent <= MAX_EXTENT).then_some(())
295
990
}