forge
Explore
Log in

Don't you dare go Hollow

🧮 read a page total the planner answered from an index

Browse files at this commit

4889fd9f0702ebbd97f55c16a6c9f037dacfb1a0Ahmet Kaan GümüşParent: 0684656
  • fix
    • 🧮 read a page total the planner answered from an index
Show full message
fix: 🧮 read a page total the planner answered from an index

Asking for the sections with no grade answered 500. SurrealDB rewrites
count() into a count straight off an index or the table when the
predicate is known at plan time, and that plan returns {count: N}
rather than the projected int the page decoder expected — so a filter
on an indexed field broke the count that pages it, while the same
filter with a bound parameter did not.

The total now reads either shape. That is also what the WHERE true
appended to every unfiltered read was working around, one altitude too
low and at the price of a scan where the bare read counts in O(1), so
it goes.

Only the class index was reaching the rewrite; every other paged read
binds its parameter or filters an unindexed field. In-memory tests
cannot see any of this — the mem engine never rewrites the plan, which
is why the container caught it and the suite did not.
src/domain/page.rsmodified+66 -19
@@ -18,6 +18,9 @@
1818 //! emits exactly one statement (no count — the rows in hand *are* the total),
1919 //! so internal callers that just want the list pay nothing.
2020 //!
21+//! The count's result shape is the planner's to choose (see [`total_of`]) —
22+//! both shapes decode to the same `total`.
23+//!
2124 //! Only for lists the database can express whole. A handler that filters rows
2225 //! in Rust after the read (visibility, audience resolution, a schedule window)
2326 //! must keep slicing in the web layer: a DB `LIMIT` in front of a Rust filter
@@ -41,17 +44,8 @@ impl PagedList {
4144 /// `from_where` is a whole-table read (`"term"`) or a filtered one
4245 /// (`"note WHERE user = $usr"`).
4346 pub fn new(from_where: impl Into<String>, order: &'static str) -> Self {
44- let from_where = from_where.into();
4547 Self {
46- // A *bare* `SELECT VALUE count() FROM t GROUP ALL` comes back as an
47- // object rather than the projected int ("Expected int, got object")
48- // — the whole-table read takes a path that drops the `VALUE`. Any
49- // `WHERE`, even a trivial one, keeps it an int, so an unfiltered
50- // list gets one. Cheaper than special-casing the take.
51- from_where: match from_where.contains(" WHERE ") {
52- true => from_where,
53- false => format!("{from_where} WHERE true"),
54- },
48+ from_where: from_where.into(),
5549 order,
5650 bindings: Vec::new(),
5751 }
@@ -104,16 +98,42 @@ impl PagedList {
10498 }
10599 let mut result = query.await?.check()?;
106100 let rows = result.take::<Vec<T>>(0)?;
107- let total = if counted {
108- // `GROUP ALL` yields no row at all when nothing matched.
109- result.take::<Vec<i64>>(1)?.first().copied().unwrap_or(0)
110- } else {
111- rows.len() as i64
101+ let total = match counted {
102+ true => total_of(result.take::<Value>(1)?)?,
103+ false => rows.len() as i64,
112104 };
113105 Ok((rows, total))
114106 }
115107 }
116108
109+/// The count statement's slot, in either shape the planner answers in.
110+///
111+/// `SELECT VALUE count() ... GROUP ALL` normally yields the projected int, but
112+/// whenever the planner can answer the count straight out of an index or the
113+/// table count (`IndexCountScan` — an indexed field compared to a value known
114+/// at plan time, `grade IS NONE` or a *literal*, and any bare table read) it
115+/// returns `{ count: N }` and drops the `SELECT VALUE` projection. Decoding
116+/// only the int is where "Expected int, got object" came from; the number is
117+/// the same either way. The in-memory engine never rewrites the plan, so only
118+/// a real server ever produces the object.
119+fn total_of(count: Value) -> Result<i64, AppError> {
120+ // `GROUP ALL` yields no row at all when nothing matched.
121+ let row = match count {
122+ Value::Array(rows) => rows.into_iter().next().unwrap_or_default(),
123+ other => other,
124+ };
125+ let row = match row {
126+ Value::Object(mut object) => object.remove("count").unwrap_or_default(),
127+ other => other,
128+ };
129+ match row.is_nullish() {
130+ true => Ok(0),
131+ false => row
132+ .into_t::<i64>()
133+ .map_err(|e| AppError::Internal(format!("count decode: {e}"))),
134+ }
135+}
136+
117137 #[cfg(test)]
118138 mod tests {
119139 use super::*;
@@ -136,12 +156,39 @@ mod tests {
136156 assert!(counted);
137157 }
138158
139- /// A whole-table read still gets a `WHERE`, or its count comes back as an
140- /// object instead of an int.
159+ /// A whole-table read counts the table as it stands — no `WHERE true` to
160+ /// force a scan, because [`total_of`] now takes the count-from-index shape
161+ /// that hack existed to avoid.
141162 #[test]
142- fn an_unfiltered_list_still_counts_as_an_int() {
163+ fn an_unfiltered_list_counts_the_bare_table() {
143164 let (sql, _) = PagedList::new("term", "ORDER BY starts_at DESC").statements(Some(5), 0);
144- assert!(sql.contains("SELECT VALUE count() FROM term WHERE true GROUP ALL;"));
165+ assert!(sql.contains("SELECT VALUE count() FROM term GROUP ALL;"));
166+ }
167+
168+ /// Both shapes of the count slot mean the same number. The object is what
169+ /// a real server returns whenever it answers `count()` from an index or the
170+ /// table count; the in-memory engine only ever produces the int, so this is
171+ /// the only place the object arm can be pinned. Drop that arm and the
172+ /// second assert fails with "count decode: Expected int, got object" —
173+ /// which is the 500 `GET /classes?grade=&limit=1` served.
174+ #[test]
175+ fn a_count_decodes_from_either_shape() {
176+ let projected = Value::Array([Value::from_t(7i64)].into_iter().collect());
177+ let from_index = Value::Array(
178+ [Value::Object(
179+ [("count".to_string(), Value::from_t(7i64))]
180+ .into_iter()
181+ .collect(),
182+ )]
183+ .into_iter()
184+ .collect(),
185+ );
186+ assert_eq!(total_of(projected).unwrap(), 7);
187+ assert_eq!(total_of(from_index).unwrap(), 7);
188+ // `GROUP ALL` yields no row at all when nothing matched.
189+ assert_eq!(total_of(Value::Array(Default::default())).unwrap(), 0);
190+ // Any other shape is an error, never a silently wrong `total`.
191+ assert!(total_of(Value::Array([Value::from_t("7")].into_iter().collect())).is_err());
145192 }
146193
147194 /// Unpaged from row zero: the rows in hand are the total, so no count runs.