From 9160a543d028843998d81ab9f8e47110137e9904 Mon Sep 17 00:00:00 2001 From: James Briggs <35938317+jamescalam@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:35:36 +0800 Subject: [PATCH] Sheets: a formula whose ranges add up past the budget stops before it reads a cell =SUMPRODUCT(A1:T10000, ...) with 16 ranges of 200,000 cells read each range before SUMPRODUCT ran. The budget charged each read, so it ended in #CALC! only at the 16th range, after 3 million cell reads: about 2 s on a laptop, and over 3 s on CI's runners, where the hostile test timed out. A person's sheet with such a formula froze for as long. Now, before a formula is worked out, the engine adds up the cells of every range it is sure to read (all of them, except the parts of IF, IFERROR, IFNA and IFS past the first, which may never be worked out). Each of those reads would be charged its cells anyway, so a total past the budget ends in #CALC! at once, with no cell read. A highlight's test gets the same check. refRange's span moves into refSpan, which both use. Co-authored-by: Pointman Co-authored-by: Claude --- sheets/references/sheet-template.html | 31 +++++++++++++++++++++------ tests/hostile.js | 19 ++++++++++++++++ 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/sheets/references/sheet-template.html b/sheets/references/sheet-template.html index 81ac251..2d69c23 100644 --- a/sheets/references/sheet-template.html +++ b/sheets/references/sheet-template.html @@ -394,7 +394,7 @@

SHEET TITLE

if (!inp) v = null; else if (inp.formula !== undefined) { this.busy[key] = true; - try { v = ++this.steps > LIMIT.steps ? ERR("#CALC!") : this.evaluate(parse(inp.formula), tabName, 0, 0); } catch (e) { v = ERR(typeof e === "string" ? e : "#ERROR!"); } + try { var tree = parse(inp.formula); v = ++this.steps + this.sureReads(tree, tabName, 0, 0) > LIMIT.steps ? ERR("#CALC!") : this.evaluate(tree, tabName, 0, 0); } catch (e) { v = ERR(typeof e === "string" ? e : "#ERROR!"); } if (isRange(v)) v = v.rows[0][0]; if (v === undefined) v = ERR("#VALUE!"); // a function given too few arguments if (typeof v === "number" && !isFinite(v)) v = ERR("#NUM!"); @@ -403,9 +403,10 @@

SHEET TITLE

} else v = inp.value; this.memo[key] = v; return v; }; - Book.prototype.refRange = function (tok, here, dr, dc) { + // A reference's cells: a span, or null where refRange gives #REF! (no such tab, or a range off the sheet). + Book.prototype.refSpan = function (tok, here, dr, dc) { var tabName = tok.tab || here; - if (!this.raw[String(tabName).toLowerCase()]) return ERR("#REF!"); + if (!this.raw[String(tabName).toLowerCase()]) return null; var parts = tok.v.split(":"), self = this; function cell(s, isEnd) { var colOnly = /^\$?([A-Z]{1,3})$/.exec(s); @@ -413,10 +414,28 @@

SHEET TITLE

var m = /^(\$?)([A-Z]{1,3})(\$?)(\d+)$/.exec(s); if (!m) return null; return { c: colNum(m[2]) + (m[1] ? 0 : dc), r: +m[4] + (m[3] ? 0 : dr) }; } - var s = span(cell(parts[0], false), parts[1] ? cell(parts[1], true) : cell(parts[0], false)); + return span(cell(parts[0], false), parts[1] ? cell(parts[1], true) : cell(parts[0], false)); + }; + Book.prototype.refRange = function (tok, here, dr, dc) { + var tabName = tok.tab || here, s = this.refSpan(tok, here, dr, dc), self = this; if (!s) return ERR("#REF!"); var got = mk(s.r1 - s.r0 + 1, s.c1 - s.c0 + 1, function (r, c) { return self.value(tabName, addr(s.r0 + r, s.c0 + c)); }); - return parts[1] ? got : got.rows[0][0]; + return tok.v.indexOf(":") >= 0 ? got : got.rows[0][0]; + }; + // The cells a formula is sure to read: every range it names, except in the parts of IF, IFERROR, IFNA and IFS + // past their first, which may never be worked out. Each read is charged its cells (mk), so a formula whose sure + // reads are past the budget ends in #CALC! without reading a cell, where it once read millions first. + var LAZY = map({ IF: 1, IFERROR: 1, IFNA: 1, IFS: 1 }); + Book.prototype.sureReads = function (n, here, dr, dc) { + var self = this, s, f, a; + switch (n.k) { + case "ref": s = this.refSpan(n, here, dr, dc); return s ? s.n : 0; + case "neg": case "pct": return this.sureReads(n.x, here, dr, dc); + case "bin": return this.sureReads(n.l, here, dr, dc) + this.sureReads(n.r, here, dr, dc); + case "call": f = n.f.replace(/^_XLFN\./, ""); a = LAZY[f] ? n.a.slice(0, 1) : F[f] ? n.a : []; + return a.reduce(function (t, x) { return t + self.sureReads(x, here, dr, dc); }, 0); + } + return 0; }; var KEEP_RANGE = null; Book.prototype.evaluate = function (n, here, dr, dc) { @@ -493,7 +512,7 @@

SHEET TITLE

// A rule's formula is written for the top-left cell of its range; dr/dc move it to another cell. Book.prototype.ruleAt = function (formula, tabName, dr, dc) { if (++this.steps > LIMIT.steps) return false; - try { var v = this.evaluate(parse(String(formula).replace(/^=/, "")), tabName, dr, dc); if (isRange(v)) v = v.rows[0][0]; var b = bool(v); return isErr(b) ? false : b; } catch (e) { return false; } + try { var tree = parse(String(formula).replace(/^=/, "")); if (this.steps + this.sureReads(tree, tabName, dr, dc) > LIMIT.steps) return false; var v = this.evaluate(tree, tabName, dr, dc); if (isRange(v)) v = v.rows[0][0]; var b = bool(v); return isErr(b) ? false : b; } catch (e) { return false; } }; function expand(range) { // "A2:C9" -> list of {r,c} var p = String(range).toUpperCase().replace(/\$/g, "").split(":"), s = span(parseAddr(p[0]), parseAddr(p[1] || p[0])), out = []; diff --git a/tests/hostile.js b/tests/hostile.js index 2779ac5..cfb3f81 100644 --- a/tests/hostile.js +++ b/tests/hostile.js @@ -89,6 +89,25 @@ module.exports = function ({ E, test, script, within, ROOT }) { assert.strictEqual(one("=SUMPRODUCT((A1:A20=0)*(A1:T1=0))"), 400); // a small one still works assert.ok(Date.now() - t0 < 4000, `took ${Date.now() - t0} ms`); }); + test("a formula whose ranges add up past the budget ends in #CALC! before it reads a cell of them", () => { + const passes = Math.ceil(E.LIMIT.steps / 200000) + 1, big = "SUMPRODUCT(" + Array(passes).fill("A1:T10000").join(",") + ")"; + const counted = (cells) => { + const book = new E.Book({ tabs: [{ name: "T", cells: Object.assign({ A1: 1 }, cells) }] }), value = book.value; + book.reads = []; book.value = function (t, a) { this.reads.push(a); return value.call(this, t, a); }; + return book; + }; + let b = counted({ Z1: "=" + big }); + assert.strictEqual(errOf(within(3000, () => b.value("T", "Z1"))), "#CALC!"); + assert.strictEqual(b.reads.length, 1, `read ${b.reads.length} cells`); // the cell itself, and none of its 3.2 million + b = counted({ Z1: "=SUM(A1:A3)+A1" }); + assert.strictEqual(b.value("T", "Z1"), 2); // within the budget, it reads what it names + assert.deepStrictEqual(b.reads, ["Z1", "A1", "A2", "A3", "A1"]); + b = counted({ Z1: "=IF(A1=1, 5, " + big + ")", Z2: "=IFERROR(A1, " + big + ")", Z3: "=IFS(A1=1, 7, TRUE, " + big + ")" }); + assert.deepStrictEqual(["Z1", "Z2", "Z3"].map((a) => b.value("T", a)), [5, 1, 7]); // a part that may never be worked out isn't counted + b = counted({}); + assert.strictEqual(within(3000, () => b.ruleAt("=" + big + ">0", "T", 0, 0)), false); // a highlight's test, the same + assert.strictEqual(b.reads.length, 0, `read ${b.reads.length} cells`); + }); test("text a formula makes is charged by its length, not only by its cells", () => { const t = (b1) => within(3000, () => new E.Book({ tabs: [{ name: "T", cells: { B1: b1, C1: "=SUMPRODUCT(LEN(UPPER(A1:A2000&B1)))" } }] }).value("T", "C1")); assert.strictEqual(t("x"), 2000);