mod form;
mod int;
mod lift;
#[cfg(test)]
mod tests;
mod write;
use super::{Marks, PassKind, finish};
use crate::engine::budget::Counter;
use crate::engine::{Fin, Runner, Step, Stop};
use crate::expr::{Context, OpCode};
use crate::hash::IdMap;
const MAX_CONE: usize = 1024;
const MAX_LARGE: u32 = 4096;
const MAX_WORK: u64 = 1 << 26;
const SECOND_SLACK: u64 = 1 << 14;
const MAX_LOST: u64 = 1 << 23;
#[derive(Default)]
pub(crate) struct State {
build: write::Build,
covered: Marks,
asked: IdMap<u32, Fin>,
quiet: IdMap<u32, Fin>,
large: u32,
work: u64,
lost: u64,
sums_at: Option<u32>,
pub(crate) turn: bool,
}
impl State {
pub(crate) fn begin(&mut self) {
self.covered.clear();
self.asked.clear();
self.large = 0;
self.sums_at = None;
}
}
struct Answers {
first: Leg,
values: Option<Leg>,
sums: Option<Leg>,
second: bool,
fin: Fin,
}
impl Answers {
fn atoms(&self) -> Option<(&Leg, u32, u32)> {
let l = match &self.values {
Some(v) if self.second => v,
_ => &self.first,
};
l.found.map(|f| (l, f.0, f.1))
}
fn sums(&self) -> Option<(&Leg, u32, u32)> {
let l = self.sums.as_ref()?;
l.found.map(|f| (l, f.0, f.1))
}
fn least(&self) -> Option<(&Leg, u32, u32)> {
match (self.atoms(), self.sums()) {
(Some(a), Some(s)) => Some(if s.2 <= a.2 { s } else { a }),
(a, s) => s.or(a),
}
}
fn of_sums(&self, l: &Leg) -> bool {
self.sums.as_ref().is_some_and(|s| core::ptr::eq(s, l))
}
}
struct Leg {
build: write::Build,
found: Option<(u32, u32)>,
work: u64,
fin: Fin,
forked: bool,
wordy: bool,
}
#[derive(Default)]
pub(crate) struct Quiet {
kept: std::sync::Mutex<IdMap<Box<[u64]>, std::sync::Arc<Kept>>>,
nodes: std::sync::atomic::AtomicUsize,
#[cfg(test)]
hits: std::sync::atomic::AtomicU64,
#[cfg(test)]
found_hits: std::sync::atomic::AtomicU64,
}
impl core::fmt::Debug for Quiet {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Quiet").finish_non_exhaustive()
}
}
struct Kept {
paid: u64,
consts: Box<[(u16, u128)]>,
work: u64,
forked: bool,
wordy: bool,
found: Option<(write::KeptBuild, u32, Fin)>,
}
const QUIET_KEPT: usize = 1 << 15;
const QUIET_NODES: usize = 1 << 21;
fn quiet_key(
cx: &Context,
lift: &lift::Lift,
nodes: &[u32],
limit: Option<u64>,
) -> Option<Box<[u64]>> {
let mut out: Vec<u64> = Vec::with_capacity(nodes.len() * 6 + 4);
out.push(u64::from(lift.alg.plain) | u64::from(lift.alg.values) << 1);
out.push(limit.unwrap_or(u64::MAX));
out.push(nodes.len() as u64);
let place: IdMap<u32, u32> = nodes
.iter()
.enumerate()
.map(|(i, &n)| (n, i as u32))
.collect();
for &n in nodes {
let node = cx.node(n);
out.push(u64::from(node.op as u8) | u64::from(node.width) << 16);
match node.op {
OpCode::Const => {
let v = cx.const_val(n)?;
out.push(v.limbs().len() as u64);
out.extend_from_slice(v.limbs());
}
OpCode::Sym => match cx.symbol_key(crate::expr::SymbolId(node.a))? {
crate::SymbolKey::U64(k) => out.extend([1, *k]),
crate::SymbolKey::Fresh(k) => out.extend([2, *k]),
crate::SymbolKey::Str(s) => {
out.extend([3, s.len() as u64]);
for c in s.as_bytes().chunks(8) {
let mut w = [0u8; 8];
w[..c.len()].copy_from_slice(c);
out.push(u64::from_le_bytes(w));
}
}
},
_ => {
out.push(u64::from(node.aux));
let arity = node.op.arity();
for (j, x) in [node.a, node.b, node.c].into_iter().enumerate() {
out.push(match j < arity {
true => u64::from(*place.get(&x)?),
false => u64::from(x) | 1 << 40,
});
}
}
}
lift.learned(n, &mut out);
}
Some(out.into_boxed_slice())
}
fn leg(
r: &mut Runner<'_, '_>,
cx: &mut Context,
mut lift: lift::Lift,
mut build: write::Build,
nodes: Vec<u32>,
limit: Option<u64>,
) -> Result<Leg, Stop> {
for &n in &nodes {
lift.learn(r, cx, n)?;
}
let key = quiet_key(cx, &lift, &nodes, limit);
let kept = key.as_ref().and_then(|k| {
let g = r
.inner
.words_quiet
.kept
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
g.get(k).cloned()
});
if let Some(q) = kept
&& r.meter.left_in(|b| b.pass_work) >= q.paid
&& r.meter.left_in(|b| b.new_nodes) >= q.consts.len() as u64
{
for &(w, v) in q.consts.iter() {
let width = crate::Width::new(w).map_err(|e| Stop::Error(e.into()))?;
r.build(cx, |cx| {
cx.mk_const(&crate::BitVec::wrapping_from_u128(width, v))
})?;
}
r.meter.charge(Counter::PassWork, q.paid)?;
r.words.work += q.work;
#[cfg(test)]
r.inner
.words_quiet
.hits
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
#[cfg(test)]
if q.found.is_some() {
r.inner
.words_quiet
.found_hits
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
let (found, fin) = match &q.found {
Some((kept, size, fin)) => {
let root = build.restore(cx, &nodes, kept).map_err(Stop::Error)?;
(Some((root, *size)), *fin)
}
None => (None, lift.fin.unwrap_or(Fin::FINAL)),
};
return Ok(Leg {
build,
found,
work: q.work,
fin,
forked: q.forked,
wordy: q.wordy,
});
}
let cone = key.as_ref().map(|_| nodes.clone());
let mut search = write::Search::new(&mut lift, &mut build, nodes);
if let Some(limit) = limit {
search.limit(limit);
}
let found = search.run(r, cx);
let work = search.work();
let (paid, consts) = search.charged();
r.words.work += work;
let found = found?;
let fin = lift.fin.unwrap_or(Fin::FINAL);
let kept_found = match (found, &cone) {
(None, _) => Some(None),
(Some((root, size)), Some(cone)) => build
.keep(cx, cone, root, &consts)
.map(|kb| Some((kb, size, fin))),
(Some(_), None) => None,
};
if let Some(kept_found) = kept_found
&& let Some(key) = key
{
let mut g = r
.inner
.words_quiet
.kept
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
use std::sync::atomic::Ordering::Relaxed;
let held = &r.inner.words_quiet.nodes;
let size = kept_found.as_ref().map_or(0, |(kb, _, _)| kb.len());
if g.len() >= QUIET_KEPT || held.load(Relaxed) + size > QUIET_NODES {
g.clear();
held.store(0, Relaxed);
}
held.fetch_add(size, Relaxed);
g.insert(
key,
std::sync::Arc::new(Kept {
paid,
consts: consts.into_boxed_slice(),
work,
forked: lift.alg.forked(),
wordy: lift.alg.wordy(),
found: kept_found,
}),
);
}
Ok(Leg {
build,
found,
work,
fin,
forked: lift.alg.forked(),
wordy: lift.alg.wordy(),
})
}
pub(crate) fn asks_first(r: &Runner<'_, '_>, cx: &Context, n: u32) -> bool {
r.words.turn
&& !r.words.covered.contains(n)
&& r.words.large < MAX_LARGE
&& r.words.work < MAX_WORK
&& !matches!(cx.node(n).op, OpCode::Const | OpCode::Sym)
&& !r.quarantined_passes.contains(&PassKind::Words)
}
fn cone(r: &mut Runner<'_, '_>, cx: &Context, n: u32) -> Result<Result<Vec<u32>, bool>, Stop> {
if cx.meta[n as usize].height as usize >= MAX_CONE {
return Ok(Err(false));
}
let mut seen: IdMap<u32, ()> = IdMap::default();
let mut stack = vec![n];
let mut out = Vec::new();
while let Some(i) = stack.pop() {
if seen.insert(i, ()).is_some() {
continue;
}
out.push(i);
if out.len() > MAX_CONE {
r.meter.charge(Counter::PassWork, out.len() as u64)?;
return Ok(Err(true));
}
stack.extend(cx.node(i).children());
}
r.meter.charge(Counter::PassWork, 2 * out.len() as u64)?;
let height = |i: u32| cx.meta[i as usize].height;
out.sort_by(|&a, &b| height(a).cmp(&height(b)).then_with(|| cx.order(a, b)));
Ok(Ok(out))
}
pub(crate) fn first(
r: &mut Runner<'_, '_>,
cx: &mut Context,
n: u32,
) -> Result<Option<(u32, Fin)>, Stop> {
r.words.covered.insert(n);
let nodes = match cone(r, cx, n)? {
Ok(nodes) => nodes,
Err(counted) => {
r.words.large += u32::from(counted);
r.words.asked.insert(n, Fin::FINAL);
return Ok(None);
}
};
for &i in &nodes {
r.words.covered.insert(i);
}
if let Some(&fin) = r.words.quiet.get(&n) {
r.words.asked.insert(n, fin);
return Ok(None);
}
r.stats
.passes
.entry(PassKind::Words.name())
.or_default()
.calls += 1;
let mut build = core::mem::take(&mut r.words.build);
let out = ask(r, cx, &mut build, n, nodes);
r.words.build = build;
let (step, found) = out?;
Ok(match step {
Step::To(e, fin) => {
r.words.covered.remove(e);
Some((e, fin))
}
Step::Normal(fin) => {
if !found {
r.words.quiet.insert(n, fin);
}
r.words.asked.insert(n, fin);
None
}
})
}
fn answers(
r: &mut Runner<'_, '_>,
cx: &mut Context,
build: write::Build,
nodes: Vec<u32>,
with_sums: bool,
) -> Result<Answers, Stop> {
let first = leg(r, cx, lift::Lift::default(), build, nodes.clone(), None)?;
let mut fin = first.fin;
let allow = 2 * first.work + SECOND_SLACK;
let mut forked = first.forked || with_sums;
let mut values = None;
if first.wordy && r.words.lost < MAX_LOST {
let l = leg(
r,
cx,
lift::Lift::values(),
write::Build::default(),
nodes.clone(),
Some(allow),
)?;
fin = fin.and(l.fin);
forked |= l.forked;
values = Some(l);
}
let mut sums = None;
if forked && r.words.lost < MAX_LOST {
let l = leg(
r,
cx,
lift::Lift::plain(),
write::Build::default(),
nodes,
(!with_sums).then_some(allow),
)?;
fin = fin.and(l.fin);
if l.found.is_none() {
r.words.lost += l.work;
}
sums = Some(l);
}
let size = |l: &Leg| l.found.map(|f| f.1);
let second = match (size(&first), values.as_ref().and_then(size)) {
(_, None) => false,
(None, Some(_)) => true,
(Some(a), Some(v)) => v <= a,
};
if let Some(v) = &values
&& !second
{
r.words.lost += v.work;
}
Ok(Answers {
first,
values,
sums,
second,
fin,
})
}
fn chase(
r: &mut Runner<'_, '_>,
cx: &mut Context,
mut e: u32,
alone: bool,
fin: &mut Fin,
) -> Result<u32, Stop> {
let mut with_sums = false;
let mut from: Option<(u32, usize)> = None;
while !matches!(cx.node(e).op, OpCode::Const | OpCode::Sym) {
let nodes = match cone(r, cx, e)? {
Ok(nodes) if from.is_none_or(|(_, size)| nodes.len() < size) => nodes,
_ => {
if let Some((before, _)) = from {
e = before;
}
break;
}
};
if r.words.work >= MAX_WORK {
break;
}
from = Some((e, nodes.len()));
if alone {
let l = leg(
r,
cx,
lift::Lift::plain(),
write::Build::default(),
nodes,
None,
)?;
*fin = fin.and(l.fin);
let Some((root, _)) = l.found else {
break;
};
e = l.build.write(r, cx, root)?;
} else {
let a = answers(r, cx, write::Build::default(), nodes, with_sums)?;
*fin = fin.and(a.fin);
let Some((l, root, _)) = a.least() else {
r.words.quiet.insert(e, a.fin);
break;
};
with_sums = a.of_sums(l);
e = l.build.write(r, cx, root)?;
}
}
Ok(e)
}
fn dag(r: &mut Runner<'_, '_>, cx: &Context, e: u32, or: u32) -> Result<u32, Stop> {
Ok(match cone(r, cx, e)? {
Ok(nodes) => nodes.len() as u32,
Err(_) => or,
})
}
fn unused(r: &mut Runner<'_, '_>, cx: &Context, before: u32, e: u32) -> Result<(), Stop> {
let len = cx.len() as u32;
r.meter
.charge(Counter::PassWork, u64::from(len.saturating_sub(before)))?;
let mut reached: IdMap<u32, ()> = IdMap::default();
let mut stack = vec![e];
while let Some(i) = stack.pop() {
if i >= before && reached.insert(i, ()).is_none() {
stack.extend(cx.node(i).children());
}
}
for i in before..len {
if !reached.contains_key(&i) {
r.retire(cx, i);
}
}
Ok(())
}
fn committed(
r: &mut Runner<'_, '_>,
cx: &mut Context,
n: u32,
e: u32,
before: u32,
fin: Fin,
) -> Result<(Step, bool), Stop> {
if r.inner.strategy.words_proved && e != n && !proved(r, cx, n, e)? {
r.stats
.passes
.entry(PassKind::Words.name())
.or_default()
.noop += 1;
return Ok((Step::Normal(fin), false));
}
Ok((
finish(r, cx, PassKind::Words, n, e, before, &[], fin)?,
true,
))
}
fn ask(
r: &mut Runner<'_, '_>,
cx: &mut Context,
build: &mut write::Build,
n: u32,
nodes: Vec<u32>,
) -> Result<(Step, bool), Stop> {
let before = cx.len() as u32;
let wide = nodes.iter().any(|&i| cx.node(i).width > 64);
let _bounds = form::Wide::set(wide);
let with_sums = r.words.sums_at.take() == Some(n);
let a = answers(r, cx, core::mem::take(build), nodes, with_sums)?;
let mut fin = a.fin;
let out = match (a.atoms(), a.sums()) {
(Some((la, ra, sa)), Some((ls, rs, ss))) if sa < ss => {
let es = ls.build.write(r, cx, rs)?;
let asked = r.words.work;
let es = chase(r, cx, es, true, &mut fin)?;
let of_sums = r.words.work - asked;
let (asked, lost) = (r.words.work, r.words.lost);
let ea = la.build.write(r, cx, ra)?;
let ea = chase(r, cx, ea, false, &mut fin)?;
let e = if dag(r, cx, es, ss)? < dag(r, cx, ea, sa)? {
r.words.lost = lost + (r.words.work - asked);
es
} else {
r.words.lost += ls.work + of_sums;
ea
};
unused(r, cx, before, e)?;
committed(r, cx, n, e, before, fin)?
}
_ => match a.least() {
Some((l, root, _)) => {
let e = l.build.write(r, cx, root)?;
let (step, found) = committed(r, cx, n, e, before, fin)?;
if let Step::To(e, _) = step
&& a.of_sums(l)
{
r.words.sums_at = Some(e);
}
(step, found)
}
None => {
r.stats
.passes
.entry(PassKind::Words.name())
.or_default()
.noop += 1;
(Step::Normal(fin), false)
}
},
};
*build = a.first.build;
Ok(out)
}
#[cfg(feature = "prove")]
const PROOF_NODES: usize = 1 << 18;
#[cfg(feature = "prove")]
const PROOF_PROPAGATIONS: u64 = 1 << 23;
#[cfg(feature = "prove")]
fn proved(r: &mut Runner<'_, '_>, cx: &Context, n: u32, e: u32) -> Result<bool, Stop> {
use crate::engine::oracle::{EqualityCaps, EqualityVerdict};
let mut scx = Context::new();
let both = match scx.import(cx, &[cx.handle(n), cx.handle(e)]) {
Ok(both) => both,
Err(crate::Error::Unsupported(_)) => return Ok(false),
Err(e) => return Err(Stop::Error(e)),
};
let caps = EqualityCaps {
samples: 64,
max_nodes: PROOF_NODES,
max_propagations: PROOF_PROPAGATIONS,
};
let out =
(crate::circuit_equality())(&mut scx, both[0], both[1], &caps).map_err(Stop::Error)?;
let left = r.meter.left_in(|b| b.pass_work);
r.meter
.charge(Counter::PassWork, (out.nodes as u64).min(left))?;
Ok(out.verdict == EqualityVerdict::Proved)
}
#[cfg(not(feature = "prove"))]
fn proved(_: &mut Runner<'_, '_>, _: &Context, _: u32, _: u32) -> Result<bool, Stop> {
Ok(false)
}
pub(super) fn step(r: &mut Runner<'_, '_>, cx: &Context, n: u32) -> Result<Step, Stop> {
let fin = match r.words.asked.get(&n) {
Some(&fin) => fin,
None if matches!(cx.node(n).op, OpCode::Const | OpCode::Sym) => Fin::FINAL,
None => Fin::PROVISIONAL,
};
Ok(Step::Normal(fin))
}