ferroplan 0.9.0

A fast, data-parallel PDDL planner in Rust — FF heuristic with ADL, numeric, derived axioms, PDDL3 preferences, PDDL2.1 temporal, and a goal decomposer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! FF relaxed-plan heuristic over the packed task, allocation-free on the hot
//! path: all working buffers live in a reusable `Scratch` that a worker thread
//! creates once and resets per evaluation (cleared, never re-allocated). This
//! removes the per-state allocation churn — and the global-allocator contention
//! it caused across worker threads — which was the main limit on both raw speed
//! and parallel scaling.
//!
//! Same algorithm as the (oracle-verified) metricff heuristic: a delete-relaxed
//! planning graph with monotone numeric interval bounds, two-phase layering,
//! lowest-layer achiever selection, and numeric repetition counting. The
//! best-first engine only needs `h`, so the helpful-action set is not computed.

use crate::bitset;
use crate::packed::PackedTask;
use crate::types::{eval_numpre, AssignOp, CompOp, NExpr, NumEff, NumPre};

const LAYER_CAP: u32 = 2000;
const INF: u32 = u32::MAX;

/// Reusable per-worker working memory for `relaxed`.
pub struct Scratch {
    reached: Vec<bool>,
    fact_layer: Vec<u32>,
    op_layer: Vec<u32>,
    /// Generation stamp for `op_layer` / `selected` / `need_fact` membership: a
    /// cell is "set this evaluation" iff its stamp == `gen`. Lets `reset()` bump
    /// `gen` in O(1) instead of clearing these arrays every evaluation.
    gen: u32,
    op_stamp: Vec<u32>,
    applicable: Vec<u32>,
    lb: Vec<f64>,
    ub: Vec<f64>,
    selected: Vec<u32>,
    need_fact: Vec<u32>,
    queue: Vec<u32>,
    /// applied ops with ≥1 relevant numeric effect (re-widened each layer).
    num_applied: Vec<u32>,
    /// applied ops with ≥1 conditional effect (re-checked each layer; their
    /// conditional adds fire once the condition becomes relaxed-reached).
    cond_ops: Vec<u32>,
    /// FF helpful actions: relaxed-plan ops applicable in the current state
    /// (op_layer 0). Populated during extraction; read by EHC.
    helpful: Vec<u32>,
}

impl Scratch {
    pub fn new(task: &PackedTask) -> Self {
        let nfl = task.fv0.len();
        Scratch {
            reached: vec![false; task.n_facts],
            fact_layer: vec![INF; task.n_facts],
            op_layer: vec![INF; task.n_ops],
            gen: 0,
            op_stamp: vec![0; task.n_ops],
            applicable: Vec::with_capacity(task.n_ops),
            lb: vec![0.0; nfl],
            ub: vec![0.0; nfl],
            selected: vec![0; task.n_ops],
            need_fact: vec![0; task.n_facts],
            queue: Vec::with_capacity(task.n_facts),
            num_applied: Vec::with_capacity(task.n_ops),
            cond_ops: Vec::new(),
            helpful: Vec::new(),
        }
    }

    fn reset(&mut self, task: &PackedTask, bits: &[u64], fv: &[f64]) {
        for f in 0..task.n_facts {
            self.reached[f] = bitset::test(bits, f);
        }
        self.fact_layer.iter_mut().enumerate().for_each(|(f, l)| {
            *l = if self.reached[f] { 0 } else { INF };
        });
        // Bump the generation instead of clearing op_layer/selected/need_fact —
        // their stale values are unobservable because every read is stamp-gated
        // (== gen). This removes 2*n_ops + n_facts dense writes per evaluation.
        self.gen = self.gen.wrapping_add(1);
        if self.gen == 0 {
            // wrapped after ~4e9 evals: hard-clear once so stamps can't collide.
            self.op_stamp.fill(0);
            self.selected.fill(0);
            self.need_fact.fill(0);
            self.gen = 1;
        }
        self.lb.copy_from_slice(fv);
        self.ub.copy_from_slice(fv);
        self.queue.clear();
        self.num_applied.clear();
        self.cond_ops.clear();
        self.helpful.clear();
    }
}

/// Widen monotone bounds from op `oi`'s numeric effects on RELEVANT fluents
/// (effects on fluents that no precondition/goal reads cannot change the
/// heuristic, so skipping them is exact and also stops irrelevant unbounded
/// growth). Returns whether any relevant bound changed.
fn widen(
    neffs: &[NumEff],
    relevant: &[bool],
    lb: &mut [f64],
    ub: &mut [f64],
    def: &[bool],
) -> bool {
    let mut changed = false;
    for ne in neffs {
        let t = ne.target as usize;
        if !relevant[t] {
            continue;
        }
        if let Some((vl, vu)) = eval_iv(&ne.value, lb, ub, def) {
            let before = (lb[t], ub[t]);
            match ne.op {
                AssignOp::Increase => {
                    ub[t] += vu.max(0.0);
                    lb[t] += vl.min(0.0);
                }
                AssignOp::Decrease => {
                    lb[t] -= vu.max(0.0);
                    ub[t] -= vl.min(0.0);
                }
                AssignOp::Assign => {
                    lb[t] = lb[t].min(vl);
                    ub[t] = ub[t].max(vu);
                }
                AssignOp::ScaleUp => ub[t] *= vu.max(1.0),
                AssignOp::ScaleDown => lb[t] /= vu.max(1.0),
            }
            if (lb[t], ub[t]) != before {
                changed = true;
            }
        }
    }
    changed
}

fn op_has_relevant_neff(task: &PackedTask, oi: usize) -> bool {
    task.num_eff
        .slice(oi)
        .iter()
        .any(|ne| task.relevant_fluent[ne.target as usize])
}

fn eval_iv(e: &NExpr, lb: &[f64], ub: &[f64], def: &[bool]) -> Option<(f64, f64)> {
    Some(match e {
        NExpr::Num(n) => (*n, *n),
        NExpr::Fluent(i) => {
            let i = *i as usize;
            if !def[i] {
                return None;
            }
            (lb[i], ub[i])
        }
        NExpr::Neg(a) => {
            let (l, u) = eval_iv(a, lb, ub, def)?;
            (-u, -l)
        }
        NExpr::Add(a, b) => {
            let (al, au) = eval_iv(a, lb, ub, def)?;
            let (bl, bu) = eval_iv(b, lb, ub, def)?;
            (al + bl, au + bu)
        }
        NExpr::Sub(a, b) => {
            let (al, au) = eval_iv(a, lb, ub, def)?;
            let (bl, bu) = eval_iv(b, lb, ub, def)?;
            (al - bu, au - bl)
        }
        NExpr::Mul(a, b) => {
            let (al, au) = eval_iv(a, lb, ub, def)?;
            let (bl, bu) = eval_iv(b, lb, ub, def)?;
            let c = [al * bl, al * bu, au * bl, au * bu];
            (
                c.iter().cloned().fold(f64::INFINITY, f64::min),
                c.iter().cloned().fold(f64::NEG_INFINITY, f64::max),
            )
        }
        NExpr::Div(a, b) => {
            let (al, au) = eval_iv(a, lb, ub, def)?;
            let (bl, bu) = eval_iv(b, lb, ub, def)?;
            if bl <= 0.0 && bu >= 0.0 {
                (f64::NEG_INFINITY, f64::INFINITY)
            } else {
                let c = [al / bl, al / bu, au / bl, au / bu];
                (
                    c.iter().cloned().fold(f64::INFINITY, f64::min),
                    c.iter().cloned().fold(f64::NEG_INFINITY, f64::max),
                )
            }
        }
    })
}

fn num_sat(np: &NumPre, lb: &[f64], ub: &[f64], def: &[bool]) -> bool {
    let l = match eval_iv(&np.lhs, lb, ub, def) {
        Some(x) => x,
        None => return false,
    };
    let r = match eval_iv(&np.rhs, lb, ub, def) {
        Some(x) => x,
        None => return false,
    };
    match np.op {
        CompOp::Lt => l.0 < r.1,
        CompOp::Le => l.0 <= r.1,
        CompOp::Gt => l.1 > r.0,
        CompOp::Ge => l.1 >= r.0,
        CompOp::Eq => l.0 <= r.1 && r.0 <= l.1,
    }
}

fn goal_done(
    goal_pos: &[u32],
    goal_num: &[NumPre],
    reached: &[bool],
    lb: &[f64],
    ub: &[f64],
    def: &[bool],
) -> bool {
    goal_pos.iter().all(|&f| reached[f as usize])
        && goal_num.iter().all(|np| num_sat(np, lb, ub, def))
}

/// Build the delete-relaxed planning graph into `sc` (op_layer / reached /
/// bounds). With `to_fixpoint` it ignores the goal and runs to a fixpoint
/// (so every reachable op gets a layer); otherwise it stops once the goal is
/// relaxed-reached. `sc` must be reset first.
fn build_rpg(
    task: &PackedTask,
    sc: &mut Scratch,
    goal_pos: &[u32],
    goal_num: &[NumPre],
    def: &[bool],
    to_fixpoint: bool,
) {
    // ---- build the relaxed planning graph (two-phase, incremental) ----
    // Only UNAPPLIED ops are re-scanned each layer; applied ops never lose
    // applicability (delete-relaxed), so they are skipped — except those with
    // relevant numeric effects, which are re-widened each layer from
    // `num_applied` so monotone fluents (e.g. consumed-resources) can grow to
    // reach numeric goals.
    let mut layer: u32 = 0;
    loop {
        if !to_fixpoint && goal_done(goal_pos, goal_num, &sc.reached, &sc.lb, &sc.ub, def) {
            break;
        }
        let mut changed = false;

        // (a) re-widen bounds from previously-applied relevant-numeric ops
        for idx in 0..sc.num_applied.len() {
            let oi = sc.num_applied[idx] as usize;
            if widen(
                task.num_eff.slice(oi),
                &task.relevant_fluent,
                &mut sc.lb,
                &mut sc.ub,
                def,
            ) {
                changed = true;
            }
        }

        // (a2) conditional effects of applied ops: fire those whose condition is
        // now relaxed-reached (positive facts reached + numeric satisfied;
        // negative conditions are dropped by the delete-relaxation).
        for idx in 0..sc.cond_ops.len() {
            let oi = sc.cond_ops[idx] as usize;
            for ce in task.cond_effs(oi) {
                let pos_ok = ce.cond_pos.iter().all(|&c| sc.reached[c as usize]);
                let num_ok = ce
                    .cond_num
                    .iter()
                    .all(|np| num_sat(np, &sc.lb, &sc.ub, def));
                if pos_ok && num_ok {
                    for &f in &ce.add {
                        let f = f as usize;
                        if !sc.reached[f] {
                            sc.reached[f] = true;
                            sc.fact_layer[f] = layer + 1;
                            changed = true;
                        }
                    }
                    if !ce.num.is_empty()
                        && widen(&ce.num, &task.relevant_fluent, &mut sc.lb, &mut sc.ub, def)
                    {
                        changed = true;
                    }
                }
            }
        }

        // (b) scan only unapplied ops for new applicability
        sc.applicable.clear();
        for oi in 0..task.n_ops {
            if sc.op_stamp[oi] == sc.gen {
                continue; // already applied this evaluation
            }
            let ok = task
                .pre_pos
                .slice(oi)
                .iter()
                .all(|&f| sc.reached[f as usize])
                && task
                    .pre_num
                    .slice(oi)
                    .iter()
                    .all(|np| num_sat(np, &sc.lb, &sc.ub, def));
            if ok {
                sc.op_stamp[oi] = sc.gen;
                sc.op_layer[oi] = layer;
                sc.applicable.push(oi as u32);
                changed = true;
            }
        }

        // (c) apply newly-applicable ops: reach their adds, widen + register
        for k in 0..sc.applicable.len() {
            let oi = sc.applicable[k] as usize;
            for &f in task.add.slice(oi) {
                let f = f as usize;
                if !sc.reached[f] {
                    sc.reached[f] = true;
                    sc.fact_layer[f] = layer + 1;
                    changed = true;
                }
            }
            if op_has_relevant_neff(task, oi) {
                if widen(
                    task.num_eff.slice(oi),
                    &task.relevant_fluent,
                    &mut sc.lb,
                    &mut sc.ub,
                    def,
                ) {
                    changed = true;
                }
                sc.num_applied.push(oi as u32);
            }
            if task.n_cond_effs(oi) > 0 {
                sc.cond_ops.push(oi as u32);
            }
        }

        layer += 1;
        if !changed || layer > LAYER_CAP {
            break;
        }
    }
}

/// Goal-blind relaxed reachability to a FIXPOINT: returns `(fact_layer,
/// op_layer)` with `u32::MAX` for unreached entries. One RPG build; used by
/// landmark extraction ([`crate::landmarks`]), which needs every reachable
/// op's layer, not just enough layers to touch a goal.
pub fn reachability_layers(
    task: &PackedTask,
    sc: &mut Scratch,
    bits: &[u64],
    fv: &[f64],
    def: &[bool],
) -> (Vec<u32>, Vec<u32>) {
    sc.reset(task, bits, fv);
    build_rpg(task, sc, &[], &[], def, true);
    let op_layer: Vec<u32> = (0..task.n_ops)
        .map(|oi| {
            if sc.op_stamp[oi] == sc.gen {
                sc.op_layer[oi]
            } else {
                u32::MAX
            }
        })
        .collect();
    (sc.fact_layer.clone(), op_layer)
}

/// Relaxed-plan heuristic toward an ARBITRARY (sub)goal, using reusable `sc`.
/// None == dead end. This is the subplanner heuristic SGPlan-style partitioning
/// drives with per-subproblem goals.
pub fn relaxed_to(
    task: &PackedTask,
    sc: &mut Scratch,
    bits: &[u64],
    fv: &[f64],
    def: &[bool],
    goal_pos: &[u32],
    goal_num: &[NumPre],
) -> Option<i32> {
    sc.reset(task, bits, fv);

    build_rpg(task, sc, goal_pos, goal_num, def, false);

    if !goal_done(goal_pos, goal_num, &sc.reached, &sc.lb, &sc.ub, def) {
        return None;
    }

    // ---- relaxed-plan extraction (count actions) ----
    let mut count: i32 = 0;
    let mut head = 0usize;
    for &g in goal_pos {
        let f = g as usize;
        if sc.need_fact[f] != sc.gen {
            sc.need_fact[f] = sc.gen;
            sc.queue.push(g);
        }
    }

    while head < sc.queue.len() {
        let f = sc.queue[head] as usize;
        head += 1;
        if bitset::test(bits, f) {
            continue;
        }
        if let Some(oi) = achiever(task, &sc.op_layer, &sc.op_stamp, sc.gen, &sc.fact_layer, f) {
            select(task, sc, oi, 1, &mut count);
            queue_cond_for(task, sc, oi, f);
        }
    }

    for np in goal_num {
        if eval_numpre(np, fv, def).unwrap_or(false) {
            continue;
        }
        if let Some((oi, reps)) = numeric_achiever(task, np, fv, def, &sc.op_stamp, sc.gen) {
            select(task, sc, oi, reps, &mut count);
            while head < sc.queue.len() {
                let f = sc.queue[head] as usize;
                head += 1;
                if bitset::test(bits, f) {
                    continue;
                }
                if let Some(o2) =
                    achiever(task, &sc.op_layer, &sc.op_stamp, sc.gen, &sc.fact_layer, f)
                {
                    select(task, sc, o2, 1, &mut count);
                    queue_cond_for(task, sc, o2, f);
                }
            }
        }
    }

    Some(count)
}

/// Convenience: relaxed-plan heuristic toward the task's own goal.
pub fn relaxed(
    task: &PackedTask,
    sc: &mut Scratch,
    bits: &[u64],
    fv: &[f64],
    def: &[bool],
) -> Option<i32> {
    relaxed_to(task, sc, bits, fv, def, &task.goal_pos, &task.goal_num)
}

/// Relaxed-plan heuristic plus the FF helpful-action set (relaxed-plan ops
/// applicable in this state). Used by enforced hill-climbing to restrict
/// expansion. None == relaxed dead end. The returned op ids are in a
/// deterministic order (relaxed-plan selection order).
pub fn relaxed_helpful(
    task: &PackedTask,
    sc: &mut Scratch,
    bits: &[u64],
    fv: &[f64],
    def: &[bool],
    goal_pos: &[u32],
    goal_num: &[NumPre],
) -> Option<(i32, Vec<u32>)> {
    let h = relaxed_to(task, sc, bits, fv, def, goal_pos, goal_num)?;
    // really applicable in THIS state (op_layer 0 is only relaxed-applicable —
    // numeric interval bounds are optimistic, so re-check exactly).
    let applicable = |oi: usize| {
        task.pre_pos
            .slice(oi)
            .iter()
            .all(|&f| bitset::test(bits, f as usize))
            && task
                .pre_num
                .slice(oi)
                .iter()
                .all(|np| eval_numpre(np, fv, def) == Some(true))
    };
    // helpful = the relaxed plan's applicable-now ops. Filter for REAL
    // applicability: on numeric domains a selected op can be relaxed-applicable
    // (op_layer 0) yet not actually applicable.
    let mut helpful: Vec<u32> = sc
        .helpful
        .iter()
        .copied()
        .filter(|&oi| applicable(oi as usize))
        .collect();
    // If that leaves nothing (typical when the relaxed plan is gated by numeric
    // preconditions), fall back to numeric subgoals: applicable ops whose numeric
    // effects touch a fluent an unsatisfied numeric precondition of a relaxed-plan
    // op reads.
    if helpful.is_empty() && h > 0 {
        let mut wanted = vec![false; fv.len()];
        let mut any = false;
        let mut tmp = Vec::new();
        for oi in 0..task.n_ops {
            if sc.selected[oi] != sc.gen {
                continue;
            }
            for np in task.pre_num.slice(oi) {
                if eval_numpre(np, fv, def) == Some(true) {
                    continue;
                }
                tmp.clear();
                np.lhs.collect_fluents(&mut tmp);
                np.rhs.collect_fluents(&mut tmp);
                for &fl in &tmp {
                    wanted[fl as usize] = true;
                    any = true;
                }
            }
        }
        if any {
            for oi in 0..task.n_ops {
                if applicable(oi)
                    && task
                        .num_eff
                        .slice(oi)
                        .iter()
                        .any(|ne| wanted[ne.target as usize])
                {
                    helpful.push(oi as u32);
                }
            }
        }
        // last resort: every really-applicable op, so EHC can act rather than
        // instantly failing (still h-guided, just unpruned for this state).
        if helpful.is_empty() {
            for oi in 0..task.n_ops {
                if applicable(oi) {
                    helpful.push(oi as u32);
                }
            }
        }
    }
    Some((h, helpful))
}

/// Relaxed completion COST of a subgoal from this state: run the relaxed-plan
/// extraction toward `goal_pos`/`goal_num`, then sum the SELECTED ops'
/// `increase` effects on `cost_fluent`, each evaluated against this state's
/// fluent values — exact when the increase amounts read only static fluents
/// (the IPC numeric-metric shape, e.g. rovers' traverse costs). Ops are
/// counted once (set semantics), so this UNDERestimates a plan that must
/// repeat an op — the safe direction for the forgo-aware seed (an
/// underestimate never prices a cheap preference out). None == relaxed dead
/// end (the subgoal is unreachable even ignoring deletes).
#[allow(clippy::too_many_arguments)]
pub fn relaxed_plan_cost(
    task: &PackedTask,
    sc: &mut Scratch,
    bits: &[u64],
    fv: &[f64],
    def: &[bool],
    goal_pos: &[u32],
    goal_num: &[NumPre],
    cost_fluent: usize,
) -> Option<f64> {
    relaxed_to(task, sc, bits, fv, def, goal_pos, goal_num)?;
    Some(selected_increase_sum(task, sc, fv, def, cost_fluent))
}

/// Summed `increase cost_fluent` amounts of the ops SELECTED by the last
/// relaxed-plan extraction left in `sc` (valid until the next reset), each
/// evaluated against this state's fluent values. Ops count once (set
/// semantics) — an underestimate when a plan must repeat an op.
fn selected_increase_sum(
    task: &PackedTask,
    sc: &Scratch,
    fv: &[f64],
    def: &[bool],
    cost_fluent: usize,
) -> f64 {
    let mut cost = 0.0;
    for oi in 0..task.n_ops {
        if sc.selected[oi] != sc.gen {
            continue;
        }
        for ne in task.num_eff.slice(oi) {
            if ne.target as usize == cost_fluent && ne.op == AssignOp::Increase {
                if let Some(v) = ne.value.eval(fv, def) {
                    cost += v.max(0.0);
                }
            }
        }
    }
    cost
}

/// Cost-augmented relaxed-plan heuristic: relaxed-plan LENGTH plus the summed
/// `increase cost_fluent` of the selected ops — the "cost + 1 per action"
/// shape, so search guided by it prefers cheap achievers while zero-cost
/// regions still keep a distance gradient (a pure-cost h flatlines wherever
/// remaining actions are free). Units are cost+steps; callers weight it like
/// any h. None == relaxed dead end.
#[allow(clippy::too_many_arguments)]
pub fn relaxed_costed(
    task: &PackedTask,
    sc: &mut Scratch,
    bits: &[u64],
    fv: &[f64],
    def: &[bool],
    goal_pos: &[u32],
    goal_num: &[NumPre],
    cost_fluent: usize,
) -> Option<i32> {
    let count = relaxed_to(task, sc, bits, fv, def, goal_pos, goal_num)?;
    let cost = selected_increase_sum(task, sc, fv, def, cost_fluent);
    Some(count.saturating_add(cost.min(1e9).round() as i32))
}

/// Lowest-layer op that adds fact `f` (FF prefers earliest achievers).
/// Uses the precomputed add-by-fact index instead of scanning all ops.
fn achiever(
    task: &PackedTask,
    op_layer: &[u32],
    op_stamp: &[u32],
    gen: u32,
    fact_layer: &[u32],
    f: usize,
) -> Option<usize> {
    let fl = fact_layer[f];
    if fl == INF || fl == 0 {
        return None;
    }
    let mut best = None;
    let mut best_layer = INF;
    for &oi in task.add_by_fact.slice(f) {
        let oi = oi as usize;
        if op_stamp[oi] == gen && op_layer[oi] < fl && op_layer[oi] < best_layer {
            best_layer = op_layer[oi];
            best = Some(oi);
        }
    }
    best
}

/// When fact `f` is achieved by op `oi` through a CONDITIONAL effect (not an
/// unconditional add), queue that effect's positive condition facts as extra
/// subgoals so the relaxed plan accounts for establishing the condition.
fn queue_cond_for(task: &PackedTask, sc: &mut Scratch, oi: usize, f: usize) {
    if task.add.slice(oi).iter().any(|&x| x as usize == f) {
        return; // unconditional add — nothing extra
    }
    let mut best_layer = INF;
    let mut best: Option<&crate::packed::CondEff> = None;
    for ce in task.cond_effs(oi) {
        if ce.add.iter().any(|&x| x as usize == f) {
            let cl = ce
                .cond_pos
                .iter()
                .map(|&c| sc.fact_layer[c as usize])
                .max()
                .unwrap_or(0);
            if cl != INF && cl < best_layer {
                best_layer = cl;
                best = Some(ce);
            }
        }
    }
    if let Some(ce) = best {
        for &cf in &ce.cond_pos {
            let c = cf as usize;
            if sc.need_fact[c] != sc.gen {
                sc.need_fact[c] = sc.gen;
                sc.queue.push(cf);
            }
        }
    }
}

/// Select op `oi` (×`reps`) into the relaxed plan and queue its preconditions.
fn select(task: &PackedTask, sc: &mut Scratch, oi: usize, reps: i32, count: &mut i32) {
    if sc.selected[oi] == sc.gen {
        return;
    }
    sc.selected[oi] = sc.gen;
    // a selected op applicable in the current state (layer 0) is a helpful action.
    if sc.op_stamp[oi] == sc.gen && sc.op_layer[oi] == 0 {
        sc.helpful.push(oi as u32);
    }
    *count += reps.max(1);
    for &pf in task.pre_pos.slice(oi) {
        let f = pf as usize;
        if sc.need_fact[f] != sc.gen {
            sc.need_fact[f] = sc.gen;
            sc.queue.push(pf);
        }
    }
}

fn numeric_achiever(
    task: &PackedTask,
    np: &NumPre,
    fv: &[f64],
    def: &[bool],
    op_stamp: &[u32],
    gen: u32,
) -> Option<(usize, i32)> {
    let target = match &np.lhs {
        NExpr::Fluent(i) => *i,
        _ => return None,
    };
    let want = match &np.rhs {
        NExpr::Num(n) => *n,
        _ => return None,
    };
    let cur = if def[target as usize] {
        fv[target as usize]
    } else {
        0.0
    };
    let need_raise = cur < want;
    let mut best: Option<(usize, i32)> = None;
    // only ops with a numeric effect on `target` can help (op-id order preserved,
    // so the min-reps tie-break is identical to the former full scan)
    for &oi in task.neff_by_fluent.slice(target as usize) {
        let oi = oi as usize;
        if op_stamp[oi] != gen {
            continue;
        }
        for ne in task.num_eff.slice(oi) {
            if ne.target != target {
                continue;
            }
            let delta = match ne.value.eval(fv, def) {
                Some(v) => v,
                None => continue,
            };
            let helps = match ne.op {
                AssignOp::Increase => need_raise && delta > 0.0,
                AssignOp::Decrease => !need_raise && delta > 0.0,
                _ => false,
            };
            if helps {
                let reps = (((want - cur).abs() / delta.abs().max(1e-9)).ceil() as i32).max(1);
                if best.map(|(_, r)| reps < r).unwrap_or(true) {
                    best = Some((oi, reps));
                }
            }
        }
    }
    best
}