Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

perf(formula): scope iteration settings recalculation (#7869)

wpxp123456f75d89eef5f6
diff --git a/packages/engine-formula/src/basics/common.ts b/packages/engine-formula/src/basics/common.ts
index 64666c1f18..58dc20be56 100644
--- a/packages/engine-formula/src/basics/common.ts
+++ b/packages/engine-formula/src/basics/common.ts
@@ -251,6 +251,8 @@ export interface IUnitRowData {
}
export interface IFormulaDatasetConfig {
+ /** Recalculate iteration-sensitive groups and their dependents in these workbooks. */
+ dirtyIterationUnits?: string[];
/** Snapshot replay limits calculation to affected cycles and their required precedents. */
calculateCircularOnly?: boolean;
/** Finalize replay by calculating ordinary formulas without advancing complete circular caches. */
diff --git a/packages/engine-formula/src/controllers/calculate.controller.ts b/packages/engine-formula/src/controllers/calculate.controller.ts
index b550cb8c4d..d97b852587 100644
--- a/packages/engine-formula/src/controllers/calculate.controller.ts
+++ b/packages/engine-formula/src/controllers/calculate.controller.ts
@@ -105,6 +105,7 @@ export class CalculateController extends Disposable {
private async _calculate(formulaDirtyData: Partial<IFormulaDirtyData>) {
const {
+ dirtyIterationUnits,
forceCalculation: forceCalculate = false,
dirtyRanges = [],
dirtyNameMap = {},
@@ -125,6 +126,7 @@ export class CalculateController extends Disposable {
const arrayFormulaRange = this._formulaDataModel.getArrayFormulaRange();
this._calculateFormulaService.execute({
+ dirtyIterationUnits,
formulaData,
arrayFormulaCellData,
arrayFormulaRange,
diff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
index 3fad4633cb..830b249bf8 100644
--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts
+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts
@@ -1232,6 +1232,7 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
private _includeTreeFeature(tree: FormulaDependencyTree) {
const unitId = tree.unitId;
const subUnitId = tree.subUnitId;
+
/**
* Perform active dirty detection for the feature.
*/
@@ -1298,6 +1299,11 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe
const unitId = tree.unitId;
const subUnitId = tree.subUnitId;
+ // The base engine retains workbook-wide invalidation without a cycle-group selector.
+ if (this._currentConfigService.getDirtyData().dirtyIterationUnits?.includes(unitId)) {
+ return true;
+ }
+
/**
* RAND, RANDBETWEEN, NOW, TODAY are volatile functions that are marked dirty and recalculated every time a calculation occurs.
*/
diff --git a/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.ts b/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.ts
index 584e62b031..23cb6f5eb3 100644
--- a/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.ts
@@ -69,6 +69,34 @@ describe('FormulaCalculationTriggerService', () => {
vi.restoreAllMocks();
});
+ it('batches iteration settings changes and preserves them when restarting an active calculation', async () => {
+ const bed = createTestBed();
+ bed.conversions.set('iteration-settings', {
+ commandId: 'iteration-settings',
+ getDirtyData: (command) => command.params as ReturnType<IDirtyConversionManagerParams['getDirtyData']>,
+ });
+ try {
+ bed.emit({ id: 'iteration-settings', params: { dirtyIterationUnits: ['first'] } });
+ bed.emit({ id: 'iteration-settings', params: { dirtyIterationUnits: ['first', 'second'] } });
+ await vi.advanceTimersByTimeAsync(10);
+ expect(bed.executed[0].params).toMatchObject({ dirtyIterationUnits: ['first', 'second'], dirtyRanges: [] });
+ bed.emit({ id: SetTriggerFormulaCalculationStartMutation.id, params: { dirtyRanges: [{
+ unitId: 'first',
+ sheetId: 'sheet',
+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ }] } });
+ await vi.advanceTimersByTimeAsync(10);
+ expect(bed.executed[1].id).toBe(SetFormulaCalculationStopMutation.id);
+ bed.emit({ id: SetFormulaCalculationNotificationMutation.id, params: {
+ functionsExecutedState: FormulaExecutedStateType.STOP_EXECUTION,
+ } });
+ await vi.advanceTimersByTimeAsync(10);
+ expect(bed.executed[2].params).toMatchObject({ dirtyIterationUnits: ['first', 'second'] });
+ } finally {
+ bed.service.dispose();
+ }
+ });
+
it('does not debounce reconstructed snapshot inputs and resumes for subsequent local edits', async () => {
const testBed = createTestBed();
try {
diff --git a/packages/engine-formula/src/services/active-dirty-manager.service.ts b/packages/engine-formula/src/services/active-dirty-manager.service.ts
index 398e046298..a9aaee0fda 100644
--- a/packages/engine-formula/src/services/active-dirty-manager.service.ts
+++ b/packages/engine-formula/src/services/active-dirty-manager.service.ts
@@ -28,6 +28,7 @@ export interface IDirtyConversionManagerParams {
commandId: string;
shouldTrigger?: (command: ICommandInfo, options?: IExecutionOptions) => boolean;
getDirtyData: (command: ICommandInfo) => {
+ dirtyIterationUnits?: string[];
forceCalculation?: boolean;
dirtyRanges?: IUnitRange[];
dirtyNameMap?: IDirtyUnitSheetNameMap;
diff --git a/packages/engine-formula/src/services/current-data.service.ts b/packages/engine-formula/src/services/current-data.service.ts
index 31ca13dcee..4794567423 100644
--- a/packages/engine-formula/src/services/current-data.service.ts
+++ b/packages/engine-formula/src/services/current-data.service.ts
@@ -49,6 +49,7 @@ import { FormulaDataModel } from '../models/formula-data.model';
import { ISheetRowFilteredService } from './sheet-row-filtered.service';
export interface IFormulaDirtyData {
+ dirtyIterationUnits?: string[];
forceCalculation: boolean;
dirtyRanges: IUnitRange[];
dirtyNameMap: IDirtyUnitSheetNameMap;
@@ -143,6 +144,7 @@ export interface IFormulaCurrentConfigService {
}
export class FormulaCurrentConfigService extends Disposable implements IFormulaCurrentConfigService {
+ private _dirtyIterationUnits: string[] = [];
private _unitData: IUnitData = Object.create(null);
private _unitStylesData: IUnitStylesData = Object.create(null);
@@ -399,6 +401,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
}
this._formulaData = config.formulaData;
+ this._dirtyIterationUnits = config.dirtyIterationUnits ?? [];
this._arrayFormulaCellData = convertUnitDataToRuntime(config.arrayFormulaCellData);
@@ -448,6 +451,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
getDirtyData(): IFormulaDirtyData {
return {
+ dirtyIterationUnits: this._dirtyIterationUnits,
forceCalculation: this._forceCalculate,
dirtyRanges: this._dirtyRanges,
dirtyNameMap: this._dirtyNameMap,
@@ -461,6 +465,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC
}
loadDirtyRangesAndExcludedCell(dirtyRanges: IUnitRange[], excludedCell?: IUnitExcludedCell) {
+ this._dirtyIterationUnits = [];
this._dirtyRanges = dirtyRanges;
this._excludedCell = excludedCell;
diff --git a/packages/engine-formula/src/services/formula-calculation-trigger.service.ts b/packages/engine-formula/src/services/formula-calculation-trigger.service.ts
index 09f48ed44a..a4a49c965f 100644
--- a/packages/engine-formula/src/services/formula-calculation-trigger.service.ts
+++ b/packages/engine-formula/src/services/formula-calculation-trigger.service.ts
@@ -235,6 +235,9 @@ export function mergeDirtyData(left: Partial<IFormulaDirtyData>, right: Partial<
// The accumulator owns its nested maps; command payloads and running sessions stay unchanged.
function appendDirtyData(target: IFormulaDirtyData, source: Partial<IFormulaDirtyData>, rangeKeys: Set<string>): void {
+ if (source.dirtyIterationUnits?.length) {
+ target.dirtyIterationUnits = Array.from(new Set([...(target.dirtyIterationUnits ?? []), ...source.dirtyIterationUnits]));
+ }
mergeDirtyRanges(target.dirtyRanges, source.dirtyRanges ?? [], rangeKeys);
mergeDirtyUnitStringMap(target.dirtyNameMap, source.dirtyNameMap);
mergeDirtyUnitStringMap(target.dirtyDefinedNameMap, source.dirtyDefinedNameMap);
@@ -276,6 +279,7 @@ function mergeDirtyUnitNestedMap(target: IDirtyUnitFeatureMap, right?: IDirtyUni
function hasDirtyData(dirtyData: IFormulaDirtyData): boolean {
return dirtyData.forceCalculation ||
+ Boolean(dirtyData.dirtyIterationUnits?.length) ||
dirtyData.dirtyRanges.length > 0 ||
hasNestedValue(dirtyData.dirtyNameMap) ||
hasNestedValue(dirtyData.dirtyDefinedNameMap) ||
@@ -296,7 +300,7 @@ function hasNestedValue(value: unknown): boolean {
}
function dirtyDataIntersects(left: IFormulaDirtyData, right: IFormulaDirtyData): boolean {
- if (left.forceCalculation || right.forceCalculation) {
+ if (left.forceCalculation || right.forceCalculation || left.dirtyIterationUnits?.length || right.dirtyIterationUnits?.length) {
return true;
}
diff --git a/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts
index 7676c6ea21..8e7f8ff716 100644
--- a/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts
+++ b/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts
@@ -36,6 +36,7 @@ import {
SetRangeValuesMutation,
SetRowHiddenMutation,
SetStyleCommand,
+ SetWorkbookCalculationSettingsMutation,
} from '@univerjs/sheets';
import { afterEach, describe, expect, it } from 'vitest';
import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';
@@ -92,6 +93,17 @@ describe('ActiveDirtyController', () => {
testBed?.univer.dispose();
});
+ it('marks iteration-sensitive workbooks without making every sheet dirty', () => {
+ testBed = createControllerTestBed();
+ testBed.injector.get(ActiveDirtyController);
+ const dirty = getDirtyData(testBed, {
+ id: SetWorkbookCalculationSettingsMutation.id,
+ params: { unitId: 'test', settings: { iterativeCalculation: true, maxIterations: 3, maxChange: 0.001 } },
+ });
+ expect(dirty.dirtyIterationUnits).toEqual(['test']);
+ expect(dirty.dirtyRanges ?? []).toEqual([]);
+ });
+
it.each(['__proto__', 'constructor', 'prototype', 'toString'])('keeps dirty sheet names local for special unit identifiers (%s)', (key) => {
testBed = createControllerTestBed();
testBed.injector.get(ActiveDirtyController);
diff --git a/packages/sheets-formula/src/controllers/active-dirty.controller.ts b/packages/sheets-formula/src/controllers/active-dirty.controller.ts
index f85fdb6edd..4b3fcb9c09 100644
--- a/packages/sheets-formula/src/controllers/active-dirty.controller.ts
+++ b/packages/sheets-formula/src/controllers/active-dirty.controller.ts
@@ -96,13 +96,8 @@ export class ActiveDirtyController extends Disposable {
commandId: SetWorkbookCalculationSettingsMutation.id,
getDirtyData: (command: ICommandInfo) => {
const { unitId } = command.params as { unitId: string };
- const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
return {
- dirtyRanges: workbook?.getSheets().map((sheet) => ({
- unitId,
- sheetId: sheet.getSheetId(),
- range: { startRow: 0, startColumn: 0, endRow: sheet.getRowCount() - 1, endColumn: sheet.getColumnCount() - 1 },
- })) ?? [],
+ dirtyIterationUnits: [unitId],
};
},
});
diff --git a/packages/sheets/src/commands/commands/set-workbook-calculation-settings.command.ts b/packages/sheets/src/commands/commands/set-workbook-calculation-settings.command.ts
index 45bfd2cb16..e70a60ac33 100644
--- a/packages/sheets/src/commands/commands/set-workbook-calculation-settings.command.ts
+++ b/packages/sheets/src/commands/commands/set-workbook-calculation-settings.command.ts
@@ -22,6 +22,7 @@ import {
IPermissionService,
IUndoRedoService,
IUniverInstanceService,
+ normalizeWorkbookCalculationSettings,
} from '@univerjs/core';
import { WorkbookEditablePermission } from '../../services/permission/permission-point/workbook/editable';
import { SetWorkbookCalculationSettingsMutation } from '../mutations/set-workbook-calculation-settings.mutation';
@@ -53,9 +54,15 @@ export const SetWorkbookCalculationSettingsCommand: ICommand<ISetWorkbookCalcula
};
const redoParams = {
unitId: params.unitId,
- settings: { ...params.settings },
+ settings: normalizeWorkbookCalculationSettings(params.settings),
};
+ if (undoParams.settings.iterativeCalculation === redoParams.settings.iterativeCalculation &&
+ undoParams.settings.maxIterations === redoParams.settings.maxIterations &&
+ undoParams.settings.maxChange === redoParams.settings.maxChange) {
+ return true;
+ }
+
const result = accessor.get(ICommandService).syncExecuteCommand<ISetWorkbookCalculationSettingsMutationParams>(SetWorkbookCalculationSettingsMutation.id, redoParams);
if (result) {