Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .ai/PERFORMANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,3 +213,21 @@ the run when the per-click cost grows faster than the list (linear is ~3x).
limit) for a component tree nested deeper than ~254. The `deep_nesting`
scenario is capped at 120 to stay clear. Worth remembering before recommending
deeply-recursive layouts.

### 6. Components with `dashChildrenUpdate` scan every changed path [reduced]

`selectDashProps` runs for every mounted component on every store update. For a
component type that sets `dashChildrenUpdate` (`dcc.Tabs`, several DMC types),
`determineChangedProps` walks all of `layoutHashes`, which gains one entry per
path whose props ever changed and never shrinks: O(flagged components x changed
paths) per store update. `callback_fanout_children_update` covers it.

`isFirstLevelPropsChild` used to split both paths for each entry, and was the
top frame of that scenario (with `determineChangedProps`, 51% of CPU with 50
tabs). It now rejects unrelated paths with `isPathOrDescendant` before any
allocation, which brings that down to 9%. It is still a scan, just a cheap one.
The scenario mounts 200 tabs so that going back to the old scan (about 4x
slower there) fails the baseline gate. A prefix index would make
it O(1) per component, but rebuilding it whenever `layoutHashes` changes costs
about twice one scan, so it would slow down the common case of a single
`dcc.Tabs`. An index maintained incrementally in the reducer would avoid that.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).
## [UNRELEASED]

### Fixed
- [#4103](https://github.com/plotly/dash/pull/4103) Speed up components that use `dashChildrenUpdate` (`dcc.Tabs` and others): unrelated paths are now rejected before any allocation on each store update. Addresses [#4032](https://github.com/plotly/dash/issues/4032).
- [#4167](https://github.com/plotly/dash/pull/4167) `dash-generate-components` no longer crashes when generating an R package from a `package.json` whose `author` is an object or includes a URL, and a missing author email now gets the intended error message. Fixes [#1577](https://github.com/plotly/dash/issues/1577).
- [#4169](https://github.com/plotly/dash/pull/4169) Fix the inferred path of a page whose module name contains the pages folder name: `pages/landing_pages.py` no longer gets `/` and `pages/subpages/report.py` no longer gets `/report`. Fixes [#4168](https://github.com/plotly/dash/issues/4168).
- [#4174](https://github.com/plotly/dash/pull/4174) Fix `dcc.Graph` discarding earlier layout changes when multiple `Plotly.relayout` calls run before React delivers the updated figure prop. Fixes [#4172](https://github.com/plotly/dash/issues/4172).
Expand Down
10 changes: 10 additions & 0 deletions benchmarks/baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,16 @@
"growth": 0.87
}
},
"callback_fanout_children_update": {
"fanout_ms": {
"n": 12,
"min": 146.1,
"median": 158.7,
"p90": 164.8,
"max": 174.4,
"growth": 0.94
}
},
"wildcard_all_resolve": {
"wildcard_ms": {
"n": 12,
Expand Down
41 changes: 41 additions & 0 deletions benchmarks/scenarios.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,47 @@ def _drive_fanout(b, params):
)((_build_fanout, _drive_fanout))


# ===========================================================================
# 6b. Callback fan-out with components that listen to descendant updates
# ===========================================================================


def _build_fanout_children_update(params):
app = Dash(__name__)
n = params["n"]
app.layout = html.Div(
[
dcc.Input(id="src", value="0"),
html.Div(
[dcc.Tabs([dcc.Tab(label="a")]) for _ in range(params["tabs"])],
),
html.Div([html.Div(id=f"out-{i}") for i in range(n)], id="content"),
READY,
]
)

@app.callback(
[Output(f"out-{i}", "children") for i in range(n)],
Input("src", "value"),
prevent_initial_call=True,
)
def fan(v):
return [f"{v}-{i}" for i in range(n)]

return app


scenario(
name="callback_fanout_children_update",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No baseline.json entry means only the 5000 ms fail_ms guards this scenario, and it runs at about 33 ms. Going back to the old scan (about 67 ms) would pass. The baseline ratio is normalized for machine speed (see "Updating the baseline" in .ai/PERFORMANCE.md), so a baseline made on your laptop is fine. Can you regenerate it and commit it here?

description="One Input drives 300 Outputs with 200 dcc.Tabs mounted",
params={"n": 300, "tabs": 200},
warn_ms={"fanout_ms": 1000},
fail_ms={"fanout_ms": 5000},
repeats=12,
warmup=2,
)((_build_fanout_children_update, _drive_fanout))


# ===========================================================================
# 7. Wildcard (MATCH) resolution over many pattern-matched components
# ===========================================================================
Expand Down
32 changes: 17 additions & 15 deletions dash/dash-renderer/src/wrapper/selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import {DashLayoutPath, DashComponent, BaseDashProps} from '../types/component';
import {
getComponentLayout,
stringifyPath,
checkDashChildrenUpdate
checkDashChildrenUpdate,
isPathOrDescendant
} from './wrapping';
import {pathOr} from 'ramda';

Expand All @@ -20,22 +21,20 @@ interface Hashes {

const previousHashes: Hashes = {};

const NOT_FIRST_LEVEL_CHILD: [boolean, string[]] = [false, []];

const isFirstLevelPropsChild = (
updatedPath: string,
strPath: string
strPath: string,
descendantPrefix: string
): [boolean, string[]] => {
const updatedSegments = updatedPath.split(',');
const fullSegments = strPath.split(',');

// Check that strPath actually starts with updatedPath
const startsWithPath = fullSegments.every(
(seg, i) => updatedSegments[i] === seg
);

if (!startsWithPath) return [false, []];
if (!isPathOrDescendant(updatedPath, strPath, descendantPrefix)) {
return NOT_FIRST_LEVEL_CHILD;
}

// Get the remaining path after the prefix
const remainingSegments = updatedSegments.slice(fullSegments.length);
const remainingSegments = updatedPath
.slice(descendantPrefix.length)
.split(',');

const propsCount = remainingSegments.filter(s => s === 'props').length;

Expand All @@ -49,12 +48,15 @@ function determineChangedProps(
let combinedHash = 0;
let renderType: any; // Default render type, adjust as needed
const changedProps: Record<string, any> = {};
Object.entries(state.layoutHashes).forEach(([updatedPath, pathHash]) => {
const descendantPrefix = strPath + ',';
Object.keys(state.layoutHashes).forEach(updatedPath => {
const [descendant, remainingSegments] = isFirstLevelPropsChild(
updatedPath,
strPath
strPath,
descendantPrefix
);
if (descendant) {
const pathHash = state.layoutHashes[updatedPath];
const previousHash: any = pathOr({}, [updatedPath], previousHashes);
combinedHash += pathOr(0, ['hash'], pathHash);
if (previousHash !== pathHash) {
Expand Down
8 changes: 6 additions & 2 deletions dash/dash-renderer/src/wrapper/wrapping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,12 @@ export function stringifyPath(layoutPath: DashLayoutPath) {
return join(',', layoutPath);
}

export function isPathOrDescendant(strPath: string, prefix: string) {
return strPath === prefix || strPath.startsWith(prefix + ',');
export function isPathOrDescendant(
strPath: string,
prefix: string,
descendantPrefix = prefix + ','
) {
return strPath === prefix || strPath.startsWith(descendantPrefix);
}

export function getComponentLayout(
Expand Down
91 changes: 91 additions & 0 deletions dash/dash-renderer/tests/selectors.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import {expect} from 'chai';
import {before, describe, it} from 'mocha';
import {selectDashProps} from '../src/wrapper/selectors';

const leaf = {namespace: 'test_ns', type: 'Leaf', props: {}};
const flagged = children => ({
namespace: 'test_ns',
type: 'Listens',
props: {children}
});

// The selector remembers the hashes it has seen in a module-level record, so
// each test uses its own child index to stay independent of the others.
const stateFor = (index, layoutHashes) => {
const children = [];
children[index] = flagged([leaf]);
return {layout: {props: {children}}, layoutHashes};
};

const select = (index, layoutHashes) => {
const path = ['props', 'children', index];
const [, , hash, changedProps, renderType] = selectDashProps(path)(
stateFor(index, layoutHashes)
);
return {hash, changedProps, renderType};
};

describe('selectDashProps with dashChildrenUpdate', () => {
before(() => {
window.test_ns = {Listens: {dashChildrenUpdate: true}, Leaf: {}};
});

it('sums its own hash and those of its first level children', () => {
const self = 'props,children,1';
const {hash} = select(1, {
[self]: {hash: 1},
[`${self},props,children`]: {hash: 10},
[`${self},props,children,0`]: {hash: 100}
});
expect(hash).to.equal(111);
});

it('ignores deeper descendants and unrelated paths', () => {
const self = 'props,children,2';
const {hash} = select(2, {
[self]: {hash: 1},
[`${self},props,children,0,props,children`]: {hash: 10},
'props,children,3': {hash: 100},
props: {hash: 1000}
});
expect(hash).to.equal(1);
});

it('does not mistake a sibling with the same prefix for a child', () => {
const self = 'props,children,4';
const {hash, changedProps} = select(4, {
[self]: {hash: 1},
'props,children,40': {hash: 10},
'props,children,40,props,children': {hash: 100}
});
expect(hash).to.equal(1);
expect(changedProps).to.deep.equal({});
});

it('reports the prop of an updated child only once', () => {
const hashes = {'props,children,5,props,children': {hash: 1}};
expect(select(5, hashes)).to.deep.equal({
hash: 1,
changedProps: {children: true},
renderType: 'components'
});
expect(select(5, hashes)).to.deep.equal({
hash: 1,
changedProps: {},
renderType: undefined
});
});

it('reports its own changed props and render type', () => {
const {hash, changedProps, renderType} = select(6, {
'props,children,6': {
hash: 2,
changedProps: {value: 1},
renderType: 'callback'
}
});
expect(hash).to.equal(2);
expect(changedProps).to.deep.equal({value: 1});
expect(renderType).to.equal('callback');
});
});
Loading