diff --git a/core/engine/src/compiled/graph/data.rs b/core/engine/src/compiled/graph/data.rs index 471b9f06..1d08f25c 100644 --- a/core/engine/src/compiled/graph/data.rs +++ b/core/engine/src/compiled/graph/data.rs @@ -101,7 +101,7 @@ impl<'a> Layer<'a> { let mut map = VariableMap::with_capacity(self.keys.len()); for (i, (key, column)) in self.keys.iter().zip(self.columns.iter()).enumerate() { if self.has(i, row) { - map.insert(key.clone(), column.get(row)); + map.insert(key.clone(), column.shared(row)); } } Variable::from_object(map) @@ -118,7 +118,7 @@ impl<'a> Layer<'a> { self.segments.iter().zip(self.columns.iter()).enumerate() { if self.has(i, row) { - Self::insert(&object, segments, column.get(row)); + Self::insert(&object, segments, column.shared(row)); } } object @@ -136,7 +136,7 @@ impl<'a> Layer<'a> { match node { Nest::Leaf(key, index) => { if self.has(*index, row) { - put(key, self.columns[*index].get(row)); + put(key, self.columns[*index].shared(row)); } } Nest::Branch(key, children) => { @@ -200,7 +200,9 @@ impl<'a> Layer<'a> { fn object_key(&self, row: usize, top: &str, under: &[usize]) -> Option { if let [index] = under { if self.paths[*index].as_ref() == top { - return self.has(*index, row).then(|| self.columns[*index].get(row)); + return self + .has(*index, row) + .then(|| self.columns[*index].shared(row)); } } if let Some(nest) = &self.nest { @@ -216,7 +218,7 @@ impl<'a> Layer<'a> { let mut any = false; for &i in under { if self.has(i, row) { - Self::insert(&object, &self.segments[i], self.columns[i].get(row)); + Self::insert(&object, &self.segments[i], self.columns[i].shared(row)); any = true; } } @@ -233,7 +235,7 @@ impl<'a> Layer<'a> { true => { for (i, (key, column)) in self.keys.iter().zip(self.columns.iter()).enumerate() { if self.has(i, row) { - Self::put(current, key, &column.get(row)); + Self::put(current, key, &column.shared(row)); } } } @@ -705,7 +707,7 @@ impl<'a> Data<'a> { match &self.shape { Shape::Plain(values) => Self::lookup(&values[row], path).unwrap_or(Variable::Null), Shape::Patched { base, leaves, .. } => match Self::read(leaves, path) { - Read::Leaf(index) => leaves[index].1.get(row), + Read::Leaf(index) => leaves[index].1.shared(row), Read::Base => base .as_ref() .and_then(|b| Self::lookup(&b[row], path)) @@ -968,7 +970,7 @@ impl<'a> Data<'a> { (true, None) => { let leaf = Leaf::Any( (0..count) - .map(|row| match (has(row), column.get(row)) { + .map(|row| match (has(row), column.shared(row)) { (false, _) => self.resolve(path, row), (true, value @ Variable::Object(_)) => { match self.resolve(path, row) { @@ -1230,6 +1232,9 @@ impl Keys { if leaf.words(row, &mut self.words) { return Some(true); } + if leaf.listed(row).is_some() { + return None; + } let cell = Cell::scalar(&leaf.get(row))?; let valued = cell != Cell::Null; self.cell(cell)?; @@ -1240,6 +1245,12 @@ impl Keys { if leaf.words(row, &mut self.words) { return Some(()); } + if let Some((records, at)) = leaf.listed(row) { + return match records.range(at) { + Some(_) => self.cell(Cell::Container), + None => None, + }; + } match leaf.get(row) { Variable::Null => None, value => self.cell(Cell::of(&value)?), @@ -1458,12 +1469,63 @@ impl<'a> Data<'a> { .all(|field| match Self::read(leaves, field) { Read::Leaf(index) => { !presence[index].at(&leaves[index].1, row) - || Cell::scalar(&leaves[index].1.get(row)).is_some() + || leaves[index].1.listed(row).is_none() + && Cell::scalar(&leaves[index].1.get(row)).is_some() } _ => false, }) } + pub fn counts(&self, path: &str) -> Option>> { + let Shape::Patched { leaves, .. } = &self.shape else { + return None; + }; + let Read::Leaf(index) = Self::read(leaves, path) else { + return None; + }; + let leaf = &leaves[index].1; + Some( + (0..self.len()) + .map(|row| match leaf.listed(row) { + Some((records, at)) => { + records.range(at).map(|(start, end)| (end - start) as u32) + } + None => leaf + .get(row) + .as_array() + .map(|items| items.borrow().len() as u32), + }) + .collect(), + ) + } + + pub fn lists(&self, row: usize, id: usize, at: usize) -> Option> { + let Shape::Patched { + base: None, + leaves, + presence, + .. + } = &self.shape + else { + return None; + }; + Some( + leaves + .iter() + .enumerate() + .filter(|(_, (path, _))| !path.contains('.')) + .filter(|(index, (_, leaf))| { + leaf.listed(row) + .is_some_and(|(records, found)| records.id() == id && found == at) + && presence + .as_ref() + .is_none_or(|presence| presence[*index].at(leaf, row)) + }) + .map(|(_, (path, _))| &**path) + .collect(), + ) + } + pub fn sparse(&self, row: usize, fields: &[Arc]) -> Option { let Shape::Patched { base: None, @@ -1482,7 +1544,7 @@ impl<'a> Data<'a> { }; if presence[index].at(&leaves[index].1, row) { let segments: SmallVec<[Symbol; 4]> = field.split('.').map(Symbol::from).collect(); - Layer::insert(&object, &segments, leaves[index].1.get(row)); + Layer::insert(&object, &segments, leaves[index].1.shared(row)); } } Some(object) @@ -1535,7 +1597,7 @@ impl<'a> Data<'a> { under, } => { let was = match (exact, under.is_empty()) { - (Some(leaf), _) => match earlier[*leaf].1.get(row) { + (Some(leaf), _) => match earlier[*leaf].1.shared(row) { Variable::Null => return None, value => Some(value), }, @@ -1600,6 +1662,7 @@ impl<'a> Data<'a> { edits: &Edits<'a>, row: usize, emit: &mut dyn FnMut(&str, Option<&Variable>, Option<&Variable>), + list: &mut dyn FnMut(&str, &Leaf<'a>, usize) -> bool, ) -> bool { let Some(layer) = self.extends(input) else { return false; @@ -1608,7 +1671,7 @@ impl<'a> Data<'a> { return false; } let earlier = input.leaves(); - let known = |index: usize| match earlier[index].1.get(row) { + let known = |index: usize| match earlier[index].1.shared(row) { Variable::Null => None, value => Some(value), }; @@ -1638,7 +1701,16 @@ impl<'a> Data<'a> { None => Earlier::Absent, }, }; - let now = column.get(row); + if matches!(was, Earlier::Absent) + && column + .listed(row) + .is_some_and(|(records, at)| records.range(at).is_some()) + && list(&group.pointer, column, row) + { + let _ = index; + continue; + } + let now = column.shared(row); match (&was, &now) { (Earlier::Unknown, _) => false, (Earlier::Value(Variable::Object(_)), Variable::Object(_)) => false, @@ -1698,7 +1770,7 @@ impl<'a> Data<'a> { if !layer.has(field.index, row) { continue; } - let now = field.column.get(row); + let now = field.column.shared(row); let before = match field.before { Some(leaf) => match known(leaf) { Some(value) => Some(value), diff --git a/core/engine/src/compiled/graph/plan/run/assemble.rs b/core/engine/src/compiled/graph/plan/run/assemble.rs index 3e33a9ae..c1a6364b 100644 --- a/core/engine/src/compiled/graph/plan/run/assemble.rs +++ b/core/engine/src/compiled/graph/plan/run/assemble.rs @@ -460,15 +460,14 @@ impl Plan { } ) }); - let rowwise = graph.steps.iter().flatten().any(|step| { - step.nodes || matches!(&step.kind, Kind::Node { transform, .. } if transform.looped) - }) || root.ops.iter().any(|op| { - matches!( - op, - crate::compiled::graph::plan::Op::Rows(_) - | crate::compiled::graph::plan::Op::Child(_) - ) - }); + let hosted_rows = graph.steps.iter().flatten().any(|step| step.nodes) + || root.ops.iter().any(|op| { + matches!( + op, + crate::compiled::graph::plan::Op::Rows(_) + | crate::compiled::graph::plan::Op::Child(_) + ) + }); let mut store = Store::new(root, columns, dated); for (row, error) in failures { store.errors.set(row, error); @@ -490,7 +489,7 @@ impl Plan { iteration: 0, parents: None, trace: traced.map(|_| { - let lazy = !overlapping && !rowwise; + let lazy = !overlapping && !hosted_rows; let source = match (lazy && indexes.is_empty(), indexes.is_empty()) { (true, _) => CompiledGraph::request_data(columns), (false, plain) => super::trace::Source::Rows { diff --git a/core/engine/src/compiled/graph/plan/run/store.rs b/core/engine/src/compiled/graph/plan/run/store.rs index c8824d75..4c7576f7 100644 --- a/core/engine/src/compiled/graph/plan/run/store.rs +++ b/core/engine/src/compiled/graph/plan/run/store.rs @@ -585,7 +585,7 @@ impl<'a> Columned<'a> { pub fn leaf(&self, index: usize) -> (Leaf<'a>, Option>) { let present = &self.present[index]; ( - self.leaves[index].settled(), + self.leaves[index].clone(), (*present != self.wanted).then(|| Rc::from(present.clone())), ) } @@ -601,8 +601,8 @@ impl<'a> Columned<'a> { .leaves .iter() .map(|leaf| match whole { - true => leaf.settled(), - false => leaf.settled().pick(rows), + true => leaf.clone(), + false => leaf.pick(rows), }) .collect(); let present = (!self.full()).then(|| { diff --git a/core/engine/src/compiled/graph/plan/run/trace.rs b/core/engine/src/compiled/graph/plan/run/trace.rs index 6e075744..43a64bc1 100644 --- a/core/engine/src/compiled/graph/plan/run/trace.rs +++ b/core/engine/src/compiled/graph/plan/run/trace.rs @@ -567,8 +567,7 @@ impl<'a> Run<'_, 'a> { let reason = match (looped, body) { (true, _) => match kernel { Some(kernel) => { - let data = Data::plain(rows.clone(), input.materialized()); - let shape = CompiledGraph::node_shape(step, Some(&data)); + let shape = CompiledGraph::node_shape(step, Some(input)); let slot = event.node.index() as Slot; match kernel.facts(self.graph.template(), slot, shape, count) { Ok(facts) => return Some(facts), diff --git a/core/engine/src/compiled/graph/state/trace.rs b/core/engine/src/compiled/graph/state/trace.rs index 9ed4eda0..906cf532 100644 --- a/core/engine/src/compiled/graph/state/trace.rs +++ b/core/engine/src/compiled/graph/state/trace.rs @@ -227,6 +227,14 @@ impl CompiledGraph { .and_then(|(program, _)| program.path())?; let mut spans: Vec<(u32, u32)> = Vec::with_capacity(data.len()); let mut total = 0u32; + if let Some(counts) = data.counts(source) { + for count in counts { + let count = count?; + spans.push((total, count)); + total += count; + } + return Some(spans.into()); + } for list in data.subtree(source).iter() { let count = list.as_array()?.borrow().len() as u32; spans.push((total, count)); diff --git a/core/engine/src/compiled/leaf/column.rs b/core/engine/src/compiled/leaf/column.rs index 547272b1..7047f440 100644 --- a/core/engine/src/compiled/leaf/column.rs +++ b/core/engine/src/compiled/leaf/column.rs @@ -477,6 +477,32 @@ impl<'a> Leaf<'a> { } } + pub fn shared(&self, row: usize) -> Variable { + match self { + Leaf::Records(records) => records.dense().get(row).cloned().unwrap_or(Variable::Null), + Leaf::Templated(templated) => templated + .dense() + .get(row) + .cloned() + .unwrap_or(Variable::Null), + Leaf::Picked(_) | Leaf::Stitched(_) => self + .source(row) + .map_or(Variable::Null, |(leaf, at)| leaf.shared(at)), + _ => self.get(row), + } + } + + pub fn listed(&self, row: usize) -> Option<(&Records<'a>, usize)> { + match self { + Leaf::Records(records) => Some((records, row)), + Leaf::Picked(_) | Leaf::Stitched(_) => { + let (leaf, at) = self.source(row)?; + leaf.listed(at) + } + _ => None, + } + } + pub fn plain(&self) -> Option<(Column<'_>, u8)> { if matches!(self, Leaf::Any(_) | Leaf::Records(_) | Leaf::Templated(_)) { return None; @@ -487,7 +513,12 @@ impl<'a> Leaf<'a> { | Values::Text { .. } | Values::LargeUtf8 { .. } | Values::Strs(_) => 0, - Values::Dict { values, .. } if matches!(values, Dictionary::Text { .. }) => 0, + Values::Dict { values, .. } => match values { + Dictionary::Text { .. } => 0, + Dictionary::Scaled { .. } => 1, + Dictionary::Bool { .. } => 2, + _ => return None, + }, Values::Scaled { .. } | Values::I64(_) | Values::Dec(_) => 1, Values::Bool { .. } => 2, _ => return None, @@ -542,7 +573,14 @@ impl<'a> Leaf<'a> { _ => { let mut next = 1u32 << 30; (0..rows) - .map(|row| match self.get(row) { + .map(|row| match self.listed(row) { + Some((records, at)) => match records.range(at) { + Some(_) => Variable::empty_array(), + None => Variable::Null, + }, + None => self.get(row), + }) + .map(|value| match value { Variable::Null => 0, Variable::Array(_) | Variable::Object(_) => 1, Variable::Dynamic(_) => 2, @@ -603,23 +641,6 @@ impl<'a> Leaf<'a> { } } - pub fn settled(&self) -> Leaf<'a> { - match self { - Leaf::Records(records) => Leaf::Any(records.dense().clone()), - Leaf::Templated(templated) => Leaf::Any(templated.dense().clone()), - Leaf::Picked(picked) => Leaf::Picked(Rc::new(Picked { - source: picked.source.settled(), - positions: picked.positions.clone(), - dense: OnceCell::new(), - })), - Leaf::Stitched(stitched) => Leaf::stitched( - stitched.sources.iter().map(Leaf::settled).collect(), - stitched.located.clone(), - ), - other => other.clone(), - } - } - pub fn pick(&self, positions: &Rc<[usize]>) -> Leaf<'a> { match self { Leaf::Picked(picked) => Leaf::Picked(Rc::new(Picked { diff --git a/core/engine/src/compiled/leaf/records.rs b/core/engine/src/compiled/leaf/records.rs index f491e9f8..1f9f1567 100644 --- a/core/engine/src/compiled/leaf/records.rs +++ b/core/engine/src/compiled/leaf/records.rs @@ -7,6 +7,11 @@ use zen_types::symbol::Symbol; use zen_types::variable::VariableMap; pub(crate) type Field<'a> = (Symbol, Leaf<'a>, Rc<[u64]>); + +pub(crate) struct Listing<'c> { + pub fields: Vec<(&'c str, &'c [u64], Column<'c>, u8)>, + pub nulled: Option<&'c [u64]>, +} type Lanes = (Vec>, Option>); #[derive(Debug)] @@ -92,6 +97,36 @@ impl<'a> Records<'a> { Records::new(rows, offsets, valid, fields, nulled) } + pub fn fresh(&self) -> bool { + self.dense.get().is_none() + } + + pub fn id(&self) -> usize { + self as *const Self as usize + } + + pub fn listing(&self) -> Option> { + if self.fields.len() >= 8 { + return None; + } + let fields = self + .fields + .iter() + .map(|(key, leaf, present)| { + let key = key.as_str(); + if key.starts_with('$') || key.contains('.') { + return None; + } + let (column, kind) = leaf.plain()?; + Some((key, &**present, column, kind)) + }) + .collect::>()?; + Some(Listing { + fields, + nulled: self.nulled.as_deref(), + }) + } + pub(super) fn labels(&self) -> Option<&[Box]> { self.labels .get_or_init(|| { diff --git a/core/engine/src/compiled/trace/batch.rs b/core/engine/src/compiled/trace/batch.rs index 805e33e8..6eb2d78c 100644 --- a/core/engine/src/compiled/trace/batch.rs +++ b/core/engine/src/compiled/trace/batch.rs @@ -15,7 +15,7 @@ pub(crate) enum Cols<'a> { Lazy(Vec>, Option>), } -impl Cols<'_> { +impl<'a> Cols<'a> { pub(crate) fn len(&self) -> usize { match self { Cols::Owned(leaves) => leaves.len(), @@ -23,6 +23,30 @@ impl Cols<'_> { } } + fn listed( + &self, + index: usize, + position: usize, + ) -> Option<(&crate::compiled::leaf::Leaf<'a>, usize)> { + match self { + Cols::Owned(_) => None, + Cols::Lazy(leaves, rows) => { + let row = match rows { + Some(rows) => *rows.get(position)?, + None => position, + }; + let (leaf, present) = leaves.get(index)?; + if present + .as_ref() + .is_some_and(|present| !crate::compiled::leaf::Bits::get(present, row)) + { + return None; + } + Some((leaf, row)) + } + } + } + fn plain(&self, index: usize) -> Option<(zen_expression::lane::Column<'_>, u8)> { match self { Cols::Owned(leaves) => leaves.get(index)?.plain(), @@ -48,7 +72,7 @@ impl Cols<'_> { .is_some_and(|present| !crate::compiled::leaf::Bits::get(present, row)) { true => Variable::Null, - false => leaf.get(row), + false => leaf.shared(row), } } } @@ -279,6 +303,7 @@ struct Hitter { } struct Plan<'a> { + narrow: Vec>, hit_keys: std::cell::RefCell, hitters: Vec>>, heads: Vec>>, @@ -448,6 +473,7 @@ impl<'a> Traces<'a> { }) .collect(); Plan { + narrow: self.events.iter().map(|_| Default::default()).collect(), hit_keys: Default::default(), hitters: self.events.iter().map(|_| OnceCell::new()).collect(), heads, @@ -624,6 +650,120 @@ impl<'a> Traces<'a> { Some(packed) } + fn listed( + &self, + walk: &Walk, + parents: &[Slot], + leaf: &crate::compiled::leaf::Leaf<'a>, + row: usize, + ) -> Option<(String, bool)> { + let (records, at) = leaf.listed(row)?; + let (start, end) = records.range(at)?; + if end - start >= 8 { + let mut inspected = true; + for parent in parents { + let (event, position) = (*walk.ran.get(*parent as usize)?)?; + let keys = match &self.events[event].output { + Some(Value::Data(data)) => data.lists(position, records.id(), at), + _ => None, + }; + match keys.as_deref() { + None => inspected = false, + Some([]) => {} + Some([key]) if inspected || records.fresh() => { + let mut path = self.template.node(*parent)?.source.clone(); + super::core::escape_seg(key, &mut path); + let mut text = String::from("{\"$ref\":"); + super::value::write_str(&path, &mut text); + text.push('}'); + let listing = records.listing()?; + let free = (start..end).all(|item| { + !listing.nulled.is_some_and(|nulled| { + crate::compiled::leaf::Bits::get(nulled, item) + }) && listing.fields.iter().all(|(_, present, column, _)| { + !crate::compiled::leaf::Bits::get(present, item) + || !crate::compiled::leaf::ColumnBuilder::null_at(column, item) + }) + }); + return Some((text, free)); + } + Some(_) => return None, + } + } + if !inspected && !records.fresh() { + return None; + } + } + let listing = records.listing()?; + let labels: SmallVec<[String; 8]> = listing + .fields + .iter() + .map(|(key, ..)| { + let mut text = String::new(); + super::value::write_str(key, &mut text); + text.push(':'); + text + }) + .collect(); + let count = end - start; + let mut text = String::with_capacity(count * 48); + let mut ends: Vec = Vec::with_capacity(count); + let mut marks: Vec = Vec::with_capacity(count); + let mut free = true; + for item in start..end { + let mut mark = 0u64; + if listing + .nulled + .is_some_and(|nulled| crate::compiled::leaf::Bits::get(nulled, item)) + { + free = false; + text.push_str("null"); + ends.push(text.len() as u32); + marks.push(u64::MAX); + continue; + } + text.push('{'); + let mut any = false; + for ((_, present, column, kind), label) in listing.fields.iter().zip(labels.iter()) { + if !crate::compiled::leaf::Bits::get(present, item) { + mark = mark.wrapping_mul(31).wrapping_add(254); + continue; + } + if any { + text.push(','); + } + any = true; + text.push_str(label); + if crate::compiled::leaf::ColumnBuilder::null_at(column, item) { + free = false; + text.push_str("null"); + mark = mark.wrapping_mul(31).wrapping_add(255); + continue; + } + match kind { + 0 => super::value::write_str(column.text(item)?, &mut text), + 1 => { + let number = column.number(item)?; + mark = mark + .wrapping_mul(31) + .wrapping_add(u64::from(number.scale())); + super::value::write_num(&number, &mut text); + } + _ => text.push_str(match column.boolean(item)? { + true => "true", + false => "false", + }), + } + } + text.push('}'); + ends.push(text.len() as u32); + marks.push(mark); + } + let mut out = String::with_capacity(text.len() + 16); + super::rows::list_texts(&text, &ends, &marks, &mut out); + Some((out, free)) + } + #[allow(clippy::too_many_arguments)] fn hits( &self, @@ -994,24 +1134,56 @@ impl<'a> Traces<'a> { match writer.missed() { false => encoded?, true => { - out.truncate(mark); - writer.retry(); - let sources: SmallVec<[(Slot, Variable); 4]> = parents - .iter() - .filter_map(|p| self.value(&mut walk, *p).map(|value| (*p, value))) - .collect(); - writer.sources(request.get(), sources.into_iter()); - self.encode( - plan, - at, - position, - parent, - &mut walk, - request, - owned, - &mut writer, - out, - )?; + let (hit, miss) = plan.narrow[at].get(); + let narrow = match miss <= hit { + false => None, + true => { + out.truncate(mark); + writer.retry(); + writer.sources(request.get(), std::iter::empty()); + super::rows::unresolved(true); + let narrow = self.encode( + plan, + at, + position, + parent, + &mut walk, + request, + owned, + &mut writer, + out, + ); + let resolved = !super::rows::unresolved(true); + plan.narrow[at].set(match resolved { + true => (hit.saturating_add(1), miss), + false => (hit, miss.saturating_add(1)), + }); + resolved.then_some(narrow) + } + }; + match narrow { + Some(narrow) => narrow?, + None => { + out.truncate(mark); + writer.retry(); + let sources: SmallVec<[(Slot, Variable); 4]> = parents + .iter() + .filter_map(|p| self.value(&mut walk, *p).map(|value| (*p, value))) + .collect(); + writer.sources(request.get(), sources.into_iter()); + self.encode( + plan, + at, + position, + parent, + &mut walk, + request, + owned, + &mut writer, + out, + )?; + } + } } } if keyed && !bodies.off { @@ -1096,12 +1268,33 @@ impl<'a> Traces<'a> { Some((start, count)) => self.packed(plan, at, start, count), None => None, }; + let around: SmallVec<[Slot; 4]> = event + .parents + .iter() + .copied() + .filter(|p| walk.ran.get(*p as usize).is_some_and(Option::is_some)) + .collect(); + let mut listed: SmallVec<[Option<(String, bool)>; 8]> = SmallVec::new(); let fetched: SmallVec<[Variable; 8]> = match &event.facts { Facts::Results((_, leaves)) => (0..leaves.len()) - .map(|index| leaves.get(index, position)) + .map(|index| { + let direct = match &event.encoding { + Encoding::Checked(_) => None, + _ => leaves + .listed(index, position) + .and_then(|(leaf, row)| self.listed(walk, &around, leaf, row)), + }; + let value = match direct { + Some(_) => Variable::Bool(true), + None => leaves.get(index, position), + }; + listed.push(direct); + value + }) .collect(), _ => SmallVec::new(), }; + let listed_free = listed.iter().flatten().all(|(_, free)| *free); let mut items = false; match &event.encoding { Encoding::Generic => return Err("generic output"), @@ -1212,7 +1405,9 @@ impl<'a> Traces<'a> { rowed.iter().all(|(_, value)| super::rows::null_free(value)) } (None, Some(packed)) => !packed.nulls, - (None, None) => self.null_free(plan, at, position, &fetched, walk), + (None, None) => { + listed_free && self.null_free(plan, at, position, &fetched, walk) + } }; if results && free { match span { @@ -1230,9 +1425,35 @@ impl<'a> Traces<'a> { (Some(edits), Some(Value::Data(after)), Encoding::Touched(Some(input))) if walk.inputs.get(slot as usize).is_none_or(Option::is_none) => { - after.edit(input, edits, position, &mut |pointer, before, after| { - writer.diff_at(pointer, before, after) - }) + let texts: std::cell::RefCell> = + Default::default(); + let parents: SmallVec<[Slot; 4]> = event + .parents + .iter() + .copied() + .filter(|p| walk.ran.get(*p as usize).is_some_and(Option::is_some)) + .collect(); + let edited = after.edit( + input, + edits, + position, + &mut |pointer, before, after| { + writer.diff_at(pointer, before, after) + }, + &mut |pointer, leaf, row| match self + .listed(walk, &parents, leaf, row) + { + Some((text, _)) => { + texts.borrow_mut().push((pointer.to_string(), text)); + true + } + None => false, + }, + ); + for (pointer, text) in texts.into_inner() { + writer.set_text(&pointer, text); + } + edited } _ => false, }; @@ -1266,10 +1487,13 @@ impl<'a> Traces<'a> { }; writer.results_with( slot, - order - .iter() - .zip(labels.iter()) - .map(|(&i, label)| (&**label, &fetched[i as usize])), + order.iter().zip(labels.iter()).map(|(&i, label)| { + ( + &**label, + &fetched[i as usize], + listed[i as usize].as_ref().map(|(text, _)| text.as_str()), + ) + }), out, ) } diff --git a/core/engine/src/compiled/trace/v1/rows.rs b/core/engine/src/compiled/trace/v1/rows.rs index 64edbbb0..9221e824 100644 --- a/core/engine/src/compiled/trace/v1/rows.rs +++ b/core/engine/src/compiled/trace/v1/rows.rs @@ -12,7 +12,7 @@ pub struct RowWriter<'t> { count: usize, used: SmallVec<[Slot; 8]>, path: String, - sets: Vec<(String, Variable)>, + sets: Vec<(String, Variable, Option>)>, deletes: Vec, partial: bool, missed: std::cell::Cell, @@ -163,6 +163,11 @@ impl<'t> RowWriter<'t> { self.path = path; } + pub fn set_text(&mut self, pointer: &str, text: String) { + self.sets + .push((pointer.to_string(), Variable::Null, Some(text.into()))); + } + pub fn diff_at(&mut self, pointer: &str, before: Option<&Variable>, after: Option<&Variable>) { self.path.clear(); self.path.push_str(pointer); @@ -175,7 +180,7 @@ impl<'t> RowWriter<'t> { match (before, after) { (None, None) => {} (Some(_), None) => self.deletes.push(path.clone()), - (None, Some(b)) => self.sets.push((path.clone(), b.clone())), + (None, Some(b)) => self.sets.push((path.clone(), b.clone(), None)), (Some(a), Some(b)) => { if same_prim(a, b) { return; @@ -201,7 +206,7 @@ impl<'t> RowWriter<'t> { } } _ if veq(a, b) => {} - _ => self.sets.push((path.clone(), b.clone())), + _ => self.sets.push((path.clone(), b.clone(), None)), } } } @@ -238,13 +243,16 @@ impl<'t> RowWriter<'t> { out.push(','); } out.push_str("\"$set\":{"); - for (i, (p, v)) in self.sets.iter().enumerate() { + for (i, (p, v, text)) in self.sets.iter().enumerate() { if i > 0 { out.push(','); } write_str(p, out); out.push(':'); - ok &= self.put(v, out); + match text { + Some(text) => out.push_str(text), + None => ok &= self.put(v, out), + } } out.push('}'); } @@ -325,14 +333,17 @@ impl<'t> RowWriter<'t> { pub fn results_with<'v>( &mut self, slot: Slot, - entries: impl Iterator, + entries: impl Iterator)>, out: &mut String, ) -> bool { out.push_str(",\"results\":{"); let mut ok = true; - for (key, value) in entries { + for (key, value, text) in entries { out.push_str(key); - ok &= self.put(value, out); + match text { + Some(text) => out.push_str(text), + None => ok &= self.put(value, out), + } } out.push('}'); if let Some(at) = self @@ -381,41 +392,7 @@ impl<'t> RowWriter<'t> { out: &mut String, ) -> bool { out.push_str(",\"results\":"); - let count = ends.len(); - let item = |i: usize| { - let start = match i { - 0 => 0, - _ => ends[i - 1] as usize, - }; - &text[start..ends[i] as usize] - }; - let mut packed = false; - if count >= 4 { - let mut seen: super::value::FastMap<(&str, u64), u32> = Default::default(); - let mut firsts: Vec = Vec::new(); - let mut at: Vec = Vec::with_capacity(count); - for i in 0..count { - let next = firsts.len() as u32; - let found = *seen.entry((item(i), marks[i])).or_insert(next); - if found == next { - firsts.push(i); - } - at.push(found); - } - if !(firsts.len() * 2 > count && (1..count).all(|i| at[i] != at[i - 1])) { - packed = emit_packed(&at, firsts.len(), |k| item(firsts[k]), out); - } - } - if !packed { - out.push('['); - for i in 0..count { - if i > 0 { - out.push(','); - } - out.push_str(item(i)); - } - out.push(']'); - } + list_texts(text, ends, marks, out); if let Some(at) = self .template .node(slot) @@ -636,6 +613,44 @@ impl<'t> RowWriter<'t> { } } +pub fn list_texts(text: &str, ends: &[u32], marks: &[u64], out: &mut String) { + let count = ends.len(); + let item = |i: usize| { + let start = match i { + 0 => 0, + _ => ends[i - 1] as usize, + }; + &text[start..ends[i] as usize] + }; + let mut packed = false; + if count >= 4 { + let mut seen: super::value::FastMap<(&str, u64), u32> = Default::default(); + let mut firsts: Vec = Vec::new(); + let mut at: Vec = Vec::with_capacity(count); + for i in 0..count { + let next = firsts.len() as u32; + let found = *seen.entry((item(i), marks[i])).or_insert(next); + if found == next { + firsts.push(i); + } + at.push(found); + } + if !(firsts.len() * 2 > count && (1..count).all(|i| at[i] != at[i - 1])) { + packed = emit_packed(&at, firsts.len(), |k| item(firsts[k]), out); + } + } + if !packed { + out.push('['); + for i in 0..count { + if i > 0 { + out.push(','); + } + out.push_str(item(i)); + } + out.push(']'); + } +} + pub fn perf(ns: u64) -> String { match super::core::duration_perf(std::time::Duration::from_nanos(ns)) { Ok(n) => n.to_string(), @@ -742,14 +757,28 @@ fn reference(sources: &[(&str, Variable)], v: &Variable, out: &mut String) -> bo false } +thread_local! { + static UNRESOLVED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +pub fn unresolved(reset: bool) -> bool { + UNRESOLVED.with(|unresolved| match reset { + true => unresolved.replace(false), + false => unresolved.get(), + }) +} + fn put_value(sources: &[(&str, Variable)], v: &Variable, out: &mut String) -> bool { let big = match v { Variable::Array(a) => a.borrow().len() >= 8, Variable::Object(o) => o.borrow().len() >= 8, _ => false, }; - if big && reference(sources, v, out) { - return true; + if big { + if reference(sources, v, out) { + return true; + } + UNRESOLVED.with(|unresolved| unresolved.set(true)); } match v { Variable::Array(a) => {