Repository navigation
feat(config): add arrayFunctionResultOverwritesData opt-in overwrite flag (HF-305) - #1714
marcin-kordas-hoc wants to merge 23 commits into
Conversation
✅ Deploy Preview for hyperformula-dev-docs ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
9009463 to
b2da92e
Compare
Performance comparison of head (927d211) vs base (867d3fb) |
|
bugbot run |
4c02791 to
d2a2671
Compare
|
bugbot run |
d2a2671 to
5e397d1
Compare
|
bugbot run |
5e397d1 to
2f48fba
Compare
2f48fba to
b877ed4
Compare
|
bugbot run |
b877ed4 to
467c186
Compare
|
bugbot run |
Deploying with
|
| Status | Name | Latest Commit | Preview URL | Updated (UTC) |
|---|---|---|---|---|
| ✅ Deployment successful! View logs |
hyperformula-docs | 927d211 | Commit Preview URL Branch Preview URL |
Dec 02 2026, 03:41 PM |
…flag (HF-305) Adds a public boolean Config option `arrayFunctionResultOverwritesData` (default `false`). When `false`, behavior is unchanged: an array spill onto an occupied cell yields `#SPILL!` and leaves the occupant intact. When `true`, the spill overwrites the occupied cells (clears occupants, spills the array, reroutes dependents) instead of emitting `#SPILL!`. Implementation reuses the existing spill-placement exchange primitive: - ConfigParams/Config: new option, mirrored on `useArrayArithmetic`. - DependencyGraph gains `config` + two guarded early-returns in exchangeOrAddFormulaVertex / setAddressMappingForArrayVertex. - Evaluator: recompute no longer emits `#SPILL!` when overwrite is allowed. Array-vs-array safety: a spill colliding with ANOTHER array always keeps `#SPILL!` and leaves that array intact, even in overwrite mode (canOverwriteArrayResult / overwriteWouldHitArray). This matches Excel and avoids corrupting a pre-existing array; overwrite only clears static data. Default `false` guarantees no existing embedder loses data silently. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The 53 cases now live in hyperformula-tests on the same-name branch (feat/hf-305-overwrite-flag), which is what test/fetch-tests.sh pairs on. They arrived here as test/hf-305-overwrite.spec.ts, and #1612 took every spec out of this repository: on develop, test/ carries only the setup files, fetch-tests.sh and smoke.spec.ts. Jest's testMatch (test/**/*spec.(ts|js)) did pick the file up, so the suite was running - it was running from the wrong repository, where it is invisible to reviewers of the tests repo and ships in the public tree. Coverage is not lost by the move: measured against this commit, every executable line this PR adds to Operations.ts (29) and DependencyGraph.ts (17) is exercised by the ported spec alone, which is what the red codecov/patch was about. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The rebase onto develop surfaced this: the entry was written when the branch's base still had 3.4.0 open, so replaying it landed the line inside the released 3.4.0 section. Moved to [Unreleased], and given the PR link every neighbouring entry carries. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
f051ab3 to
63e2137
Compare
The overwrite snapshot guarded on `width * height <= 1`, but placement (FormulaVertex.fromAst) treats every ref-flavored size as a non-spilling scalar via ArraySize.isScalar(). A bare range formula such as =C1:C3 therefore snapshotted neighbours it never overwrites, and undoing that edit spuriously restored them (re-entering formulas, re-rolling volatiles). Guard on size.isScalar() so the snapshot scope matches the placement scope, as the JSDoc already described. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This morning's develop merge landed the TEXT/numberFormat entry inside the already-published 3.4.0 Fixed list, putting CHANGELOG.md out of sync with docs/guide/release-notes.md for that released version. The fix is unreleased, so the entry belongs under [Unreleased]; the 3.4.0 lists in the two files match again. Same correction as 63e2137 on #1714. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
… re-checking it canOverwriteArrayResult already returns false for an unrepresentable range, so the second undefined check in overwriteWouldHitArray could never be reached. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ns are undone With arrayFunctionResultOverwritesData on, an array that grows because rows or columns were added inside the range it reads overwrites the cells it reaches. Undo now restores them: the add operation snapshots those cells, maps them back to the coordinates and references from before the added span, and undo writes them back right after removing the span. Undo of one setCellContents call now reverts its writes in reverse order, so a write into the spill range of an array entered earlier in the same call no longer brings that array formula back. This also applies with the option off. Row and column moves no longer overwrite data: a move adds the moved rows or columns before it removes them, and the array that grew for that moment cleared cells it does not cover once the move ends. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…cupied cells Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 7aecb9f. Configure here.
| */ | ||
| private restoreCellsOverwrittenBySpan(overwrittenCells: [SimpleCellAddress, ClipboardCell][] = []) { | ||
| for (const [address, clipboardCell] of overwrittenCells) { | ||
| this.operations.restoreCell(address, clipboardCell) |
There was a problem hiding this comment.
Undo leaves stale column-index values
Medium Severity
Undoing addRows or addColumns that grew an array over a cell restores the occupant, but the vacated spill value can stay in the column index. With useColumnIndex on, MATCH and VLOOKUP can still hit that spill after undo().
Additional Locations (2)
Reviewed by Cursor Bugbot for commit 7aecb9f. Configure here.
There was a problem hiding this comment.
Reproduced at b35339d with useColumnIndex: true: after the undo the column index still holds the vacated spill value, so =MATCH(20,A3:A4,0) returns 1 and =VLOOKUP(20,A3:A4,1,FALSE()) returns 99, where both return #N/A with the index off. It does not come from this option: on develop, adding a column inside the range an array reads leaves the same stale entry, before and after the undo. I filed it as HF-607 instead of fixing it in this PR.
There was a problem hiding this comment.
Warning
High risk: Touches core engine paths (dependency graph array placement, structural operations, undo/redo) and changes shared undo ordering for setCellContents, so miscalculations or data loss could affect wide behavior even beyond the opt-in flag.
Full review: 2 potential issue(s).
hyperformula/src/UndoRedo.ts:598
Undo of removeRows/removeColumns discards overwrite snapshots
Medium severity
undoRemoveRows/undoRemoveColumns call this.operations.addRows(...)/addColumns(...), which (with the new option on) re-grows arrays and can overwrite cells, returning a snapshot of the overwritten occupants — but the return value is discarded. If the user placed data in the area freed by the removal and then undoes the removal, that data is silently destroyed with no snapshot, so it cannot be restored by any later undo/redo. The same discard happens in redoAddRows/redoAddColumns, though there the state matches the original snapshot.
Suggestion: Capture the overwritten cells returned by addRows/addColumns during undoRemoveRows/undoRemoveColumns and restore them in the corresponding redo, or suspend overwriting during these undo/redo re-adds via withoutOverwritingData.
Want a deeper review? Comment /review improve on its own line: a full review of the latest commit with an extra fix-oriented pass (about 2x the cost).
| const oldContent = this.operations.setCellContent(address, newContent) | ||
| const {oldContent, overwrittenCells: overwritten} = this.operations.setCellContent(address, newContent) | ||
| oldContents.push({address, newContent, oldContent}) | ||
| overwrittenCells.push(...overwritten) |
There was a problem hiding this comment.
Spread push of overwritten cells can overflow the call stack
Low severity
overwrittenCells.push(...overwritten) spreads the per-cell snapshot array into push. With the overwrite option on, a large array spilling over a big occupied region (spills up to hundreds of thousands of cells are allowed by maxRows/maxColumns) produces an overwritten array large enough that the spread exceeds the engine's argument-count limit and throws a RangeError, aborting setCellContents mid-way with cells already mutated and no undo entry saved.
Suggestion: Replace with a loop: for (const cell of overwritten) { overwrittenCells.push(cell) }.
Tobiadefami
left a comment
There was a problem hiding this comment.
Two blocking points: undo with the option on, and the AI assistance section. One suggestion on the option-off column-index change.
blocking: The description is missing the template's ### AI assistance section. Please name the tool and the parts it wrote.
| // gone and the overwritten addresses are free to restore. | ||
| for (const [address, clipboardCell] of operation.overwrittenCells) { | ||
| this.operations.restoreCell(address, clipboardCell) | ||
| } |
There was a problem hiding this comment.
blocking: With arrayFunctionResultOverwritesData: true, undo can overwrite the cell that blocked an array. Repro: build [[null, null, 1, 2, 3]] with the option on, setCellContents(A1, '=TRANSPOSE(C1:E1)'), setCellContents(A2, 'y') (A1 shows #SPILL!), setCellContents(A1, null), then undo(). A2 is now 2 instead of 'y', and redo doesn't bring it back. With the option off, A2 stays 'y'.
Undo should restore the earlier state, so the undo entries probably need to run without overwriting, for example inside withoutOverwritingData. Could you fix it and add a spec for this sequence?
There was a problem hiding this comment.
Fixed in 9f8bfcd: undo now runs inside withoutOverwritingData. With your sequence, A1 is #SPILL! and A2 is 'y' after the undo, A2 stays 'y' after redo, and a second undo gives the same state; tests#45 covers that sequence, a batch() variant and the column index.
| case ClipboardCellType.FORMULA: { | ||
| this.setFormulaToCellFromAst(clipboardCell.ast, address) | ||
| // Apply the resulting content changes to the column index so that when an array | ||
| // formula shrinks on restore (e.g. undoing an overwrite-expand), the vacated spill | ||
| // values are dropped from the index. The removeRows / version-restore | ||
| // callers deliberately ignore the return value and keep their own index bookkeeping. | ||
| const changes = this.setFormulaToCellFromAst(clipboardCell.ast, address) | ||
| this.columnSearch.applyChanges(changes.getChanges()) | ||
| break |
There was a problem hiding this comment.
suggestion: This also changes results with the option off. With useColumnIndex: true: A1 =TRANSPOSE(D1:E1), D1:F1 10, 20, 30, H1 =MATCH(30,A1:A3,0). Set A1 to =TRANSPOSE(D1:F1), then undo(). On develop H1 returns 3 (a stale index entry for A3); here it returns #N/A, as it does with the column index off.
That's a fix, but the description says results don't change with the option off, and there's no changelog line or spec for it. Could you add both and adjust the description?
There was a problem hiding this comment.
64bc21d adds a changelog line under Fixed, and tests#45 adds a spec with your sequence and the option off, where H1 is #N/A. On develop the same sequence gives 3. The description now describes this fix and no longer says that results don't change with the option off.
…ite-flag # Conflicts: # CHANGELOG.md
Undo restores a state where an array either owned its whole spill range or returned #SPILL!. With arrayFunctionResultOverwritesData on, restoring such an array claimed the cell that had blocked it, and redo could not bring that cell back. Undo now runs with overwriting suspended, as row and column moves do. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Undoing the replacement of an array formula by a larger one no longer leaves the vacated spill value in the column index, with or without the option. The overwritten-cells snapshot is appended with a loop, so a very large spill does not exceed the argument-count limit of push. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Note
Medium risk: Touches core undo/calculation paths (undoEntry overwriting suspension, setCellContents snapshot accumulation), but the behavioural change is gated behind the opt-in arrayFunctionResultOverwritesData flag, so default behaviour is unchanged.
Incremental review: 1 potential issue(s).
hyperformula/src/ConfigParams.ts:109
Unrelated TEXT-function doc changes mixed into this PR
Low severity
The incremental diff adds documentation for a different feature to four options that have nothing to do with arrayFunctionResultOverwritesData: decimalSeparator (L109) and thousandSeparator (L350) gain TEXT-mask semantics, and stringifyDateTime (L300-303) and stringifyDuration (L313-316) gain TEXT color-tag/rejection caveats, all referencing a 'TEXT function formats' guide section. The PR title, description and CHANGELOG are solely about the array overwrite flag, so these hunks look like stray content from another change, violating the repository's 'One pull request, one change' rule (dev-docs/DEFINITION-OF-DONE.md, AGENTS.md failure item 2). If the described TEXT behaviour does not actually exist on this branch, the docs are also factually wrong for users.
Suggestion: Move the TEXT-mask documentation hunks (L109, L300-303, L313-316, L350) to the pull request that implements the TEXT format changes, or confirm with the maintainer that they belong here.
Want a deeper review? Comment /review improve on its own line: a full review of the latest commit with an extra fix-oriented pass (about 2x the cost).
A spread push with one argument per overwritten cell can exceed the argument-count limit when a large array grows over many occupied cells. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
The |
Tobiadefami
left a comment
There was a problem hiding this comment.
My earlier points are fixed: undo with the option on, the option-off column-index fix (changelog and spec), and the AI assistance section. Three new blockers with the option on, each a case where data is lost or undo() throws.
hyperformula/src/CrudOperations.ts:178
blocking: With the option on, paste() can clear cells that undo() never brings back. Repro: [[1, 2, '=TRANSPOSE($A$1:A1)', null], [null, null, null, 'x']], copy(C1), paste(D1). D1 becomes =TRANSPOSE($A$1:B1) and spills over D2, so 'x' becomes 2; after undo(), D2 is empty. PasteUndoEntry snapshots only the target range, and the paste path isn't wrapped in withoutOverwritingData. With the option off, D1 is #SPILL! and D2 keeps 'x'.
Could paste run inside withoutOverwritingData (as moves do, and listed in the guide's never-overwrite cases), or snapshot the occupants of pasted arrays? A spec for this sequence either way.
| public canOverwriteArrayResult(arrayVertex: ArrayFormulaVertex): boolean { | ||
| const range = arrayVertex.getRangeOrUndef() | ||
| return range !== undefined && this.isOverwritingDataAllowed() && !this.overwriteWouldHitArray(arrayVertex, range) | ||
| } |
There was a problem hiding this comment.
blocking: With the option on, a spill past maxRows clears its occupant, still returns #SPILL!, and the next undo() throws. Repro with {arrayFunctionResultOverwritesData: true, maxRows: 5}: [[null, null, 1, 2, 3], [], [], [], ['x']], setCellContents(A4, '=TRANSPOSE(C1:E1)'). A5's 'x' becomes #SPILL!, the sheet height is 6, and undo() throws Unknown node. With the option off, A5 keeps 'x' and the height stays 4.
canOverwriteArrayResult doesn't check exceedsSheetSizeLimits, which isThereSpaceForArray does. Could it return false for a range over the limits (and overwrittenOccupantAddresses return none), with specs for both limits plus undo()?
|
|
||
| if (vertex instanceof ArrayFormulaVertex) { | ||
| // The array currently anchored at `anchorAddress` is the one being replaced/expanded. | ||
| // Its cells (corner + internal) are re-created when the old anchor formula is restored | ||
| // on undo, so they must be neither snapshotted nor treated as a blocking collision. | ||
| // A DIFFERENT pre-existing array still blocks the overwrite (the spill stays #SPILL! | ||
| // and overwrites nothing), matching DependencyGraph.canOverwriteArrayResult / | ||
| // overwriteWouldHitArray. | ||
| if (!vertex.isLeftCorner(anchorAddress)) { | ||
| return [] | ||
| } | ||
| continue | ||
| } | ||
|
|
||
| if (equalSimpleCellAddress(occupantAddress, anchorAddress) || vertex === undefined || vertex instanceof EmptyCellVertex) { | ||
| continue | ||
| } | ||
|
|
||
| occupants.push(occupantAddress) | ||
| } |
There was a problem hiding this comment.
blocking: An array entered into another array's spill cell overwrites the cells below, but they aren't snapshotted, so undo() loses them. Repro with the option on: [['=TRANSPOSE(D1:E1)', null, null, 10, 20], [], ['q']], setCellContents(A2, '=TRANSPOSE(D1:E1)'). A1 turns #SPILL! and A2:A3 show 10, 20, so 'q' is cleared; after undo(), A3 is empty. With the option off, A3 keeps 'q'. The one-call form setCellContents(A1, [['=TRANSPOSE(D1:E1)'], ['=TRANSPOSE(D1:E1)']]) over p/q loses 'q' the same way.
overwrittenOccupantAddresses returns [] when it meets the other array's cell, but writing the anchor breaks that array first. Could it skip that array's cells instead, with both sequences plus undo() in the spec?
…ite-flag # Conflicts: # CHANGELOG.md
…lets arrays overwrite With arrayFunctionResultOverwritesData on, the cells an array spill clears are now recorded by the dependency graph at the moment it clears them, instead of being predicted before the write. Only setCellContents, paste, addRows and addColumns (and their redo) run inside that recording and may overwrite; they save the recorded cells in their undo entries, and undo restores them right after it removes the array, last overwritten first. Every other operation, including undo, moves and setRowOrder/setColumnOrder, keeps #SPILL! as with the option off. This fixes three cases where data was lost or undo threw: - a spill range reaching past maxRows or maxColumns cleared its occupants and grew the sheet past the limit; it now yields #SPILL! and clears nothing, - an array entered into another array's spill cleared the cells below that spill without saving them, - a pasted array cleared the cells of its spill without saving them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… forget an array whose anchor is replaced When an array formula shrinks to its anchor (it is cleared, replaced or undone), the ranges that read its spill cells are reconnected to those cells. The reconnection assumed that a range reads only its last row directly whenever the range one row shorter exists, but a range created before that shorter range reads all its cells directly. Its other cells stayed disconnected, so a SUM over the longer range kept a stale value, or undo threw "Value of the formula cell is not computed". The reconnection now uses the check the range's dependency query and its evaluation already use: only the last row, and only when the shorter range feeds this range. Replacing the anchor of an array with a value removed the array from the array mapping, but clearing the anchor or replacing it with a formula or a parsing error did not. A range over the anchor created later was then wired to the removed vertex: the formula returned #ERROR!, and undo threw "Unknown node" and broke every later call. The array is now removed from the mapping wherever its anchor is replaced. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ite-flag Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tobiadefami
left a comment
There was a problem hiding this comment.
My three blockers are fixed: after paste, a spill past maxRows and an array entered into another spill, undo() brings the cleared cell back. Left: follow-up tasks for the items under Out of scope, and a description that matches this head.
blocking: Three items under "Out of scope and follow-ups" say "No follow-up ticket yet": moves never overwrite; a #SPILL! array keeps it after a removal or an undo gives it room; and undoing a row move rewrites =TRANSPOSE(A3:A5) to =TRANSPOSE(A4:A5). The definition of done asks for a task for each. Could you file them and link them in the description?
| private* rangeDirectDependenciesToArray(vertex: RangeVertex, array: ArrayFormulaVertex): IterableIterator<[SimpleCellAddress, CellVertex]> { | ||
| const {restRange: range} = this.rangeMapping.findSmallerRange(vertex.range) | ||
| // A range reads only its last row directly when it is built on the range one row shorter. A range | ||
| // created before that shorter range reads all its cells directly, so all of them must be reconnected. | ||
| const {smallerRangeVertex, restRange} = this.rangeMapping.findSmallerRange(vertex.range) | ||
| const range = smallerRangeVertex !== undefined && this.graph.existsEdge(smallerRangeVertex, vertex) ? restRange : vertex.range |
There was a problem hiding this comment.
suggestion: e745ad9 adds a third fix that changes results with the option off (the CHANGELOG line for range formulas such as =SUM(A1:A3)), but "Also fixed here" and the compatibility section still list two. "How did you test" also gives 81 tests and one new undo-redo.spec.ts test; the overwrite spec now has 110. Could you bring the description up to this head?
An array keeps its size when rows or columns are added inside it: it takes back the added cells and leaves as many cells past its end. The array was fixed up after the ranges, but fixing a range that spans the added cells creates empty cells there, so taking them back threw "Cannot move cell. Destination already occupied." The array now takes back the added cells first, so the range fix-up finds the array there and reads it. The cells the array leaves past its end belonged to it, so the ranges and formulas that read them depended only on the array and were not updated when those cells later got content. Each such cell that is read now gets an empty cell vertex connected to its readers once the formulas are transformed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Filed HF-639 (overwriting during moves and reorders), HF-640 (undo of a row or column move changes an array function's range) and HF-641 (an |
Tobiadefami
left a comment
There was a problem hiding this comment.
Thanks for filing the follow-ups and updating the description. One blocker left: a slowdown in addRows/addColumns across an array, with the option off too.
| public connectCellsVacatedByArrays(): void { | ||
| const cellsVacatedByArrays = this.cellsVacatedByArrays | ||
| this.cellsVacatedByArrays = new Map() | ||
| for (const [array, vacated] of cellsVacatedByArrays) { | ||
| const formulas = Array.from(this.adjacentArrayVertices(array)).filter((vertex): vertex is FormulaVertex => vertex instanceof FormulaVertex) | ||
| for (const address of vacated) { | ||
| const readers: Vertex[] = [] | ||
| for (const rangeVertex of this.rangeMapping.rangesInSheet(address.sheet)) { | ||
| if (this.rangeReadDirectly(rangeVertex).addressInRange(address)) { | ||
| readers.push(rangeVertex) | ||
| } | ||
| } | ||
| for (const formula of formulas) { | ||
| const [, dependencies] = this.formulaDependencyQuery(formula) ?? [] | ||
| if (dependencies?.some(dependency => !(dependency instanceof NamedExpressionDependency) && !(dependency instanceof AbsoluteCellRange) && equalSimpleCellAddress(dependency, address))) { | ||
| readers.push(formula) | ||
| } | ||
| } | ||
| if (readers.length === 0) { | ||
| continue | ||
| } | ||
| const {vertex, id} = this.fetchCellOrCreateEmpty(address) | ||
| for (const reader of readers) { | ||
| this.graph.addEdge(id ?? vertex, reader) | ||
| } | ||
| this.graph.markNodeAsDirty(vertex) | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
blocking: For each cell an array leaves, this goes through every range in the sheet and recomputes formulaDependencyQuery for each dependent formula, so addRows/addColumns across an array costs vacated cells × ranges in the sheet. It runs with the option off too. With a 200×10 =TRANSPOSE(...) in A1, 20,000 unrelated =SUM(...) ranges and addRows(0, [5, 50]), the call takes about 1.9 s here against 44 ms on develop; with no ranges both take 22 ms.
Going through rangesInSheet once per array and checking each range against the vacated block's bounding box, then visiting only the cells in the overlap, should bring it back. formulaDependencyQuery can move out of the address loop too. Could you add the npm run test:performance result to the description?
…rwrite-flag # Conflicts: # CHANGELOG.md
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #1714 +/- ##
===========================================
- Coverage 97.76% 97.54% -0.23%
===========================================
Files 212 212
Lines 19312 19418 +106
Branches 4596 4622 +26
===========================================
+ Hits 18881 18941 +60
- Misses 423 466 +43
- Partials 8 11 +3
🚀 New features to boost your workflow:
|


Context
Adds the opt-in configuration option
arrayFunctionResultOverwritesData(defaultfalse). When it istrue, an array whose result spills onto occupied cells overwrites them instead of returning#SPILL!. When it isfalse, spills behave as before.The overwrite reuses the step that places every spill: when the array formula is placed, it claims its whole spill range in the dependency graph, drops the occupants, and records their old values so the column index forgets them. A spill that would reach another array keeps
#SPILL!and leaves that array intact, whatever the option says.Only four operations, and their redo, may overwrite:
setCellContents, paste,addRowsandaddColumns. Each records the cells a spill clears at the moment it clears them, andundo()restores them:setCellContentsand paste, undo writes the cells back right after it removes the array, last overwritten first;=E1*2comes back as=E1*2, not=F1*2), and written back right after undo removes the span.undo()itself never overwrites. It returns to a state where an array either owned its whole spill range or returned#SPILL!, so undo does not run inside the recording: it removes the array, then writes back the recorded cells, and an array it brings back next to an occupied cell shows#SPILL!. Moves and reorders also run outside the recording and keep#SPILL!, as with the option off. Before, undoing the clear of an array that a cell had blocked overwrote that cell, and redo did not bring it back.The option does not overwrite in these cases, on purpose:
maxRowsormaxColumns: it keeps#SPILL!and clears nothing;buildFromArraycall as the array: the build path keeps#SPILL!, because claiming cells there would leave nothing to undo;moveRowsandmoveColumns: a move adds the moved rows or columns before it removes them, so an array that reads them grows for a moment. Overwriting in that moment cleared the cell next to the spill for good, even when the array ended at its old size. A move that makes an array grow now leaves the occupant in place and the array shows#SPILL!.setRowOrderandsetColumnOrder: a reorder moves cells as a move does, so an array that a reorder makes larger also leaves the occupant in place and shows#SPILL!.Also fixed here, because the option made it reachable more often: undoing one
setCellContentscall that enters an array formula and also writes a cell of its spill range brought the array formula back. This happened with the option off too. Undo now reverts the writes of one call in reverse order. It has its own CHANGELOG line under Fixed.Also fixed here, with the option off too: with
useColumnIndex: true, undoing the replacement of an array formula by a larger one left the vacated spill value in the column index. In the example from review,=MATCH(30,A1:A3,0)returned3ondevelopand returns#N/Ahere, as it does without the column index. It has its own CHANGELOG line under Fixed. HF-559 (a stale entry after undoing oneaddColumnscall with two spans) is not fixed here: its repro gives the same result on this head as ondevelop.Also fixed here, with the option off too: a range formula kept a stale value, or returned an error, after an array formula that spilled into its cells was replaced, cleared or undone. With
=SUM(E1:E3)in A1,=SUM(E1:E2)in C4 and 1, 2, 3 in G1:I1, entering=TRANSPOSE($G$1:$I$1)in E1, undoing it and setting E2 to 5 left A1 at 0 ondevelop; it is 5 here. After an array formula in A1 is cleared,=SUM(A1:A1)returned#ERROR!when A1 got 4 ondevelop; it returns 4 here. It has its own CHANGELOG line under Fixed.Also fixed here, with the option off too:
addRowsandaddColumnsacross a spilled array that a range reads threwCannot move cell. Destination already occupied.With=TRANSPOSE(C1:E1)in A1,=SUM(A1:A3)in B1 and 1, 2, 3 in C1:E1,addRows(0, [2, 1])threw ondevelop; here the array keeps its size and B1 is 6. Also, a formula that reads a cell the array leaves past its end did not update when that cell got content: with=A3in B1, the sameaddRowsturns it into=A4, and setting A4 to 100 left B1 empty ondevelop; it is 100 here. It has its own CHANGELOG line under Fixed.How did you test your changes?
Paired tests: handsontable/hyperformula-tests#45, branch
feat/hf-305-overwrite-flag.unit/array-function-result-overwrites-data.spec.ts: 113 tests (configuration, the default, overwriting, array-vs-array collisions, undo and redo, undo that brings back a blocked array, undo of one call that writes an array and a cell of its spill, undo of structural operations, adding rows or columns across an array, column index, structural operations including row moves,setRowOrderandsetColumnOrder, cycles, unrepresentable spill ranges, spill ranges past the sheet size limits, an array entered into another array's spill, paste, ranges that read overwritten cells).unit/undo-redo.spec.ts: 4 new tests, with the option off: undoing one call that writes an array formula and a cell of its spill range, and 3 for range formulas after undo of an array over their cells.unit/arrays.spec.ts: 3 new tests, a range over the anchor of an array that was replaced, cleared, or replaced by a formula with a parsing error.unit/cruds/adding-row.spec.tsandunit/cruds/adding-columns.spec.ts: 5 and 4 new tests, adding rows or columns across an array that a range or a reference reads, and undo.3ondevelopinstead of#N/A. The row-move tests fail when a move may overwrite: 3 failures. Dropping the coordinate and reference mapping of the snapshot fails 2 tests. 11 of the range-formula tests fail on bd4f5ac, before that fix. Reverting theaddRows/addColumnsfix fails the 12 tests it adds; keeping the new order but not connecting the vacated cells fails 5.AI assistance
Claude Code wrote most of the engine code, the paired tests, the docs changes and this description. I reviewed the diff and ran the tests.
Compatibility with Excel and Google Sheets
With the option off, results change in the four fixes above: undo of one
setCellContentscall that writes an array and a cell of its spill range; the column-index undo, after whichuseColumnIndex: truegives the same result as the default search; range formulas over the cells of an array that was replaced, cleared or undone; andaddRows/addColumnsacross an array, which no longer throw and update the formulas that read the cells the array leaves. The option is opt-in and changes only what happens to cells an array spills onto.Public API changes
arrayFunctionResultOverwritesData: boolean, defaultfalse.undo()of onesetCellContentscall reverts its writes in reverse order. The result differs only when a later write in the call lands in the spill range of an array an earlier write entered.Out of scope and follow-ups
moveRows,moveColumns,setRowOrderandsetColumnOrder, with undo, is not implemented: moves and reorders never overwrite. Follow-up: HF-639.developwith the option off, not changed here:#SPILL!keeps it after removing a row or column, or undoing anaddColumnscall that made it grow, gives it room again. Follow-up: HF-212.=TRANSPOSE(A3:A5)becomes=TRANSPOSE(A4:A5)). Follow-up: HF-640.addColumnsinside an array built over the spill range of an array built before it throwsCannot move cell. No cell with such address.Follow-up: HF-641.Types of changes
Related issues
Checklist
dev-docs/pages this change affects – or none needed it.Note
Medium Risk
Opt-in destructive cell clearing on array spill affects dependency graph, evaluation, structural ops, and undo; default
falsepreserves Excel-compatible behavior.Overview
Adds an opt-in engine flag
arrayFunctionResultOverwritesData(defaultfalse). When enabled, array formulas that would normally hit#SPILL!on occupied non-array cells clear those occupants and spill instead; collisions with another array still return#SPILL!.DependencyGraphwires the config in, gates overwrite viacanOverwriteArrayResult/isOverwritingDataAllowed, suspends overwriting during row/column moves (withoutOverwritingData), and records content changes for cleared spill cells so the column index stays consistent. InitialbuildFromArrayplacement is unchanged—occupants declared in the same build still win.Operationssnapshots spill victims before placing formulas, returns them fromsetCellContentand fromaddRows/addColumnswhen arrays grow over static data, and updates column search on formula restore.Undo/redo restores snapshotted cells after reverting anchors or undoing row/column inserts that triggered growth overwrites;
setCellContentsundo order is fixed so a formula plus writes into its spill range no longer leaves a stray array.Docs and changelog document the option and the “Spilling onto occupied cells” behavior.
Reviewed by Cursor Bugbot for commit 7aecb9f. Bugbot is set up for automated code reviews on this repo. Configure here.