Skip to content

feat(config): add arrayFunctionResultOverwritesData opt-in overwrite flag (HF-305) - #1714

Open
marcin-kordas-hoc wants to merge 23 commits into
developfrom
feat/hf-305-overwrite-flag
Open

marcin-kordas-hoc wants to merge 23 commits into
developfrom
feat/hf-305-overwrite-flag

Conversation

@marcin-kordas-hoc

@marcin-kordas-hoc marcin-kordas-hoc commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

Context

Adds the opt-in configuration option arrayFunctionResultOverwritesData (default false). When it is true, an array whose result spills onto occupied cells overwrites them instead of returning #SPILL!. When it is false, 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, addRows and addColumns. Each records the cells a spill clears at the moment it clears them, and undo() restores them:

  • for setCellContents and paste, undo writes the cells back right after it removes the array, last overwritten first;
  • adding rows or columns inside the range an array reads makes the array grow; the cells it reaches are recorded, mapped back to their coordinates and references from before the added span (a formula =E1*2 comes 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:

  • a spill range that reaches past maxRows or maxColumns: it keeps #SPILL! and clears nothing;
  • data declared in the same buildFromArray call as the array: the build path keeps #SPILL!, because claiming cells there would leave nothing to undo;
  • moveRows and moveColumns: 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!.
  • setRowOrder and setColumnOrder: 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 setCellContents call 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) returned 3 on develop and returns #N/A here, as it does without the column index. It has its own CHANGELOG line under Fixed. HF-559 (a stale entry after undoing one addColumns call with two spans) is not fixed here: its repro gives the same result on this head as on develop.

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 on develop; it is 5 here. After an array formula in A1 is cleared, =SUM(A1:A1) returned #ERROR! when A1 got 4 on develop; it returns 4 here. It has its own CHANGELOG line under Fixed.

Also fixed here, with the option off too: addRows and addColumns across a spilled array that a range reads threw Cannot 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 on develop; 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 =A3 in B1, the same addRows turns it into =A4, and setting A4 to 100 left B1 empty on develop; 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, setRowOrder and setColumnOrder, 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.ts and unit/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.
  • 5 of the 6 tests for undo that brings back a blocked array fail on b35339d, before the undo fix. The option-off column-index sequence returns 3 on develop instead 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 the addRows/addColumns fix fails the 12 tests it adds; keeping the new order but not connecting the vacated cells fails 5.
  • Full local Jest run on this head with the paired tests: 590 suites passed, 17120 tests passed, 3 skipped.

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 setCellContents call that writes an array and a cell of its spill range; the column-index undo, after which useColumnIndex: true gives the same result as the default search; range formulas over the cells of an array that was replaced, cleared or undone; and addRows/addColumns across 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

  • New configuration option arrayFunctionResultOverwritesData: boolean, default false.
  • undo() of one setCellContents call 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

  • Overwriting during moveRows, moveColumns, setRowOrder and setColumnOrder, with undo, is not implemented: moves and reorders never overwrite. Follow-up: HF-639.
  • Already on develop with the option off, not changed here:
    • an array that shows #SPILL! keeps it after removing a row or column, or undoing an addColumns call that made it grow, gives it room again. Follow-up: HF-212.
    • undoing a row or column move inside the range an array reads changes that range (=TRANSPOSE(A3:A5) becomes =TRANSPOSE(A4:A5)). Follow-up: HF-640.
    • addColumns inside an array built over the spill range of an array built before it throws Cannot move cell. No cell with such address. Follow-up: HF-641.

Types of changes

  • Breaking change (existing functionality no longer works as before) – agreed with the maintainers
  • New feature or improvement (a non-breaking change that adds functionality)
  • Bug fix (a non-breaking change that fixes an issue)
  • Additional language file, or a change to an existing language file (translations)
  • Change to the documentation

Related issues

  1. HF-305. No public issue.

Checklist


Note

Medium Risk
Opt-in destructive cell clearing on array spill affects dependency graph, evaluation, structural ops, and undo; default false preserves Excel-compatible behavior.

Overview
Adds an opt-in engine flag arrayFunctionResultOverwritesData (default false). 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!.

DependencyGraph wires the config in, gates overwrite via canOverwriteArrayResult / isOverwritingDataAllowed, suspends overwriting during row/column moves (withoutOverwritingData), and records content changes for cleared spill cells so the column index stays consistent. Initial buildFromArray placement is unchanged—occupants declared in the same build still win.

Operations snapshots spill victims before placing formulas, returns them from setCellContent and from addRows / addColumns when 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; setCellContents undo 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.

@qunabu

qunabu commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

@netlify

netlify Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for hyperformula-dev-docs ready!

Name Link
🔨 Latest commit 467c186
🔍 Latest deploy log https://app.netlify.com/projects/hyperformula-dev-docs/deploys/6a6602deeedd020008331aa9
😎 Deploy Preview https://deploy-preview-1714--hyperformula-dev-docs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@marcin-kordas-hoc
marcin-kordas-hoc force-pushed the feat/hf-305-overwrite-flag branch from 9009463 to b2da92e Compare July 22, 2026 16:18
@github-actions

github-actions Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

Performance comparison of head (927d211) vs base (867d3fb)

                                     testName |    base |    head | change
--------------------------------------------------------------------------
                                      Sheet A |  401.51 |  394.62 | -1.72%
                                      Sheet B |  133.02 |  133.45 | +0.32%
                                      Sheet T |  118.84 |  115.28 | -3.00%
                                Column ranges |  423.18 |  421.46 | -0.41%
                                Sorted lookup | 12742.2 | 13008.6 | +2.09%
Sheet A:  change value, add/remove row/column |   14.48 |    14.9 | +2.90%
 Sheet B: change value, add/remove row/column |  122.97 |  121.43 | -1.25%
                   Column ranges - add column |  136.09 |  137.13 | +0.76%
                Column ranges - without batch |  429.62 |  432.67 | +0.71%
                        Column ranges - batch |  103.55 |   103.9 | +0.34%

@marcin-kordas-hoc

Copy link
Copy Markdown
Collaborator Author

bugbot run

@marcin-kordas-hoc
marcin-kordas-hoc force-pushed the feat/hf-305-overwrite-flag branch 2 times, most recently from 4c02791 to d2a2671 Compare July 23, 2026 03:53
@marcin-kordas-hoc

Copy link
Copy Markdown
Collaborator Author

bugbot run

Comment thread hyperformula/src/Operations.ts Resolved
Comment thread src/DependencyGraph/DependencyGraph.ts Resolved
@marcin-kordas-hoc
marcin-kordas-hoc force-pushed the feat/hf-305-overwrite-flag branch from d2a2671 to 5e397d1 Compare July 24, 2026 11:14
@marcin-kordas-hoc

Copy link
Copy Markdown
Collaborator Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@marcin-kordas-hoc
marcin-kordas-hoc marked this pull request as ready for review July 25, 2026 10:58
@marcin-kordas-hoc
marcin-kordas-hoc force-pushed the feat/hf-305-overwrite-flag branch from 5e397d1 to 2f48fba Compare July 26, 2026 02:31
Comment thread hyperformula/src/UndoRedo.ts Resolved
@marcin-kordas-hoc
marcin-kordas-hoc force-pushed the feat/hf-305-overwrite-flag branch from 2f48fba to b877ed4 Compare July 26, 2026 02:43
@marcin-kordas-hoc

Copy link
Copy Markdown
Collaborator Author

bugbot run

Comment thread hyperformula/src/Operations.ts Resolved
@marcin-kordas-hoc
marcin-kordas-hoc force-pushed the feat/hf-305-overwrite-flag branch from b877ed4 to 467c186 Compare July 26, 2026 12:51
@marcin-kordas-hoc

Copy link
Copy Markdown
Collaborator Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

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

marcin-kordas-hoc and others added 3 commits August 28, 2026 06:23
…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>
@marcin-kordas-hoc
marcin-kordas-hoc force-pushed the feat/hf-305-overwrite-flag branch from f051ab3 to 63e2137 Compare August 28, 2026 06:27
Comment thread hyperformula/src/Operations.ts Resolved
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>
marcin-kordas-hoc added a commit that referenced this pull request Aug 28, 2026
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>

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread hyperformula/src/UndoRedo.ts Resolved
marcin-kordas-hoc and others added 3 commits October 22, 2026 17:52
… 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>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 7aecb9f. Configure here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@handsontable-pr-review handsontable-pr-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread hyperformula/src/CrudOperations.ts Outdated
const oldContent = this.operations.setCellContent(address, newContent)
const {oldContent, overwrittenCells: overwritten} = this.operations.setCellContent(address, newContent)
oldContents.push({address, newContent, oldContent})
overwrittenCells.push(...overwritten)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) }.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replaced with a loop in 64bc21d, and the same spread on the addRows/addColumns path in 367f75c.

@marcin-kordas-hoc

Copy link
Copy Markdown
Collaborator Author

Fixed in f90c5c6: undoing a column insertion now restores the overwritten cells. With your example, A3 is 99 again after the undo and the formula is back to =TRANSPOSE(D1:E1), and the paired tests branch has a spec for it. develop is merged in b35339d and the full Jest suite passes.

@Tobiadefami Tobiadefami left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines 548 to 555
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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

marcin-kordas-hoc and others added 3 commits November 24, 2026 08:18
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>

@handsontable-pr-review handsontable-pr-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

marcin-kordas-hoc and others added 2 commits November 25, 2026 08:32
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>
@marcin-kordas-hoc

Copy link
Copy Markdown
Collaborator Author

The TEXT lines in ConfigParams.ts come from develop, merged into this branch; the diff against develop changes only the new option there.

@Tobiadefami Tobiadefami left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +497 to +500
public canOverwriteArrayResult(arrayVertex: ArrayFormulaVertex): boolean {
const range = arrayVertex.getRangeOrUndef()
return range !== undefined && this.isOverwritingDataAllowed() && !this.overwriteWouldHitArray(arrayVertex, range)
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()?

Comment thread hyperformula/src/Operations.ts Outdated
Comment on lines +717 to +736

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)
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

marcin-kordas-hoc and others added 2 commits November 29, 2026 14:56
…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>
marcin-kordas-hoc and others added 2 commits November 30, 2026 03:48
… 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 Tobiadefami left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment on lines +1048 to +1052
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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@marcin-kordas-hoc

Copy link
Copy Markdown
Collaborator Author

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 addColumns throw found by fuzzing, also on develop), and added the removal and undo cases to HF-212, which already covers #SPILL! that stays after its range is cleared; all are listed under "Out of scope and follow-ups". The description now lists the four fixes that change results with the option off and the test counts at this head.

@Tobiadefami Tobiadefami left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +483 to +511
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)
}
}
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

@codecov

codecov Bot commented Dec 2, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.34211% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 97.54%. Comparing base (867d3fb) to head (927d211).

Files with missing lines Patch % Lines
hyperformula/src/Operations.ts 97.91% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             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     
Files with missing lines Coverage Δ
hyperformula/src/Config.ts 94.78% <100.00%> (+0.04%) ⬆️
hyperformula/src/CrudOperations.ts 99.20% <100.00%> (+<0.01%) ⬆️
...yperformula/src/DependencyGraph/DependencyGraph.ts 98.90% <100.00%> (+0.08%) ⬆️
hyperformula/src/Evaluator.ts 100.00% <ø> (ø)
hyperformula/src/UndoRedo.ts 100.00% <100.00%> (ø)
hyperformula/src/Operations.ts 98.99% <97.91%> (-0.13%) ⬇️

... and 4 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants