Skip to content

Commit a34b9d9

Browse files
authored
Merge pull request #4103 from maoxor/renderer-children-update-index
Reject unrelated paths early in determineChangedProps
2 parents b21bd47 + bec9371 commit a34b9d9

7 files changed

Lines changed: 184 additions & 17 deletions

File tree

‎.ai/PERFORMANCE.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,3 +213,21 @@ the run when the per-click cost grows faster than the list (linear is ~3x).
213213
limit) for a component tree nested deeper than ~254. The `deep_nesting`
214214
scenario is capped at 120 to stay clear. Worth remembering before recommending
215215
deeply-recursive layouts.
216+
217+
### 6. Components with `dashChildrenUpdate` scan every changed path [reduced]
218+
219+
`selectDashProps` runs for every mounted component on every store update. For a
220+
component type that sets `dashChildrenUpdate` (`dcc.Tabs`, several DMC types),
221+
`determineChangedProps` walks all of `layoutHashes`, which gains one entry per
222+
path whose props ever changed and never shrinks: O(flagged components x changed
223+
paths) per store update. `callback_fanout_children_update` covers it.
224+
225+
`isFirstLevelPropsChild` used to split both paths for each entry, and was the
226+
top frame of that scenario (with `determineChangedProps`, 51% of CPU with 50
227+
tabs). It now rejects unrelated paths with `isPathOrDescendant` before any
228+
allocation, which brings that down to 9%. It is still a scan, just a cheap one.
229+
The scenario mounts 200 tabs so that going back to the old scan (about 4x
230+
slower there) fails the baseline gate. A prefix index would make
231+
it O(1) per component, but rebuilding it whenever `layoutHashes` changes costs
232+
about twice one scan, so it would slow down the common case of a single
233+
`dcc.Tabs`. An index maintained incrementally in the reducer would avoid that.

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).
55
## [UNRELEASED]
66

77
### Fixed
8+
- [#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).
89
- [#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).
910
- [#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).
1011
- [#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).

‎benchmarks/baseline.json‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,16 @@
8989
"growth": 0.87
9090
}
9191
},
92+
"callback_fanout_children_update": {
93+
"fanout_ms": {
94+
"n": 12,
95+
"min": 146.1,
96+
"median": 158.7,
97+
"p90": 164.8,
98+
"max": 174.4,
99+
"growth": 0.94
100+
}
101+
},
92102
"wildcard_all_resolve": {
93103
"wildcard_ms": {
94104
"n": 12,

‎benchmarks/scenarios.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,47 @@ def _drive_fanout(b, params):
416416
)((_build_fanout, _drive_fanout))
417417

418418

419+
# ===========================================================================
420+
# 6b. Callback fan-out with components that listen to descendant updates
421+
# ===========================================================================
422+
423+
424+
def _build_fanout_children_update(params):
425+
app = Dash(__name__)
426+
n = params["n"]
427+
app.layout = html.Div(
428+
[
429+
dcc.Input(id="src", value="0"),
430+
html.Div(
431+
[dcc.Tabs([dcc.Tab(label="a")]) for _ in range(params["tabs"])],
432+
),
433+
html.Div([html.Div(id=f"out-{i}") for i in range(n)], id="content"),
434+
READY,
435+
]
436+
)
437+
438+
@app.callback(
439+
[Output(f"out-{i}", "children") for i in range(n)],
440+
Input("src", "value"),
441+
prevent_initial_call=True,
442+
)
443+
def fan(v):
444+
return [f"{v}-{i}" for i in range(n)]
445+
446+
return app
447+
448+
449+
scenario(
450+
name="callback_fanout_children_update",
451+
description="One Input drives 300 Outputs with 200 dcc.Tabs mounted",
452+
params={"n": 300, "tabs": 200},
453+
warn_ms={"fanout_ms": 1000},
454+
fail_ms={"fanout_ms": 5000},
455+
repeats=12,
456+
warmup=2,
457+
)((_build_fanout_children_update, _drive_fanout))
458+
459+
419460
# ===========================================================================
420461
# 7. Wildcard (MATCH) resolution over many pattern-matched components
421462
# ===========================================================================

‎dash/dash-renderer/src/wrapper/selectors.ts‎

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ import {DashLayoutPath, DashComponent, BaseDashProps} from '../types/component';
22
import {
33
getComponentLayout,
44
stringifyPath,
5-
checkDashChildrenUpdate
5+
checkDashChildrenUpdate,
6+
isPathOrDescendant
67
} from './wrapping';
78
import {pathOr} from 'ramda';
89

@@ -20,22 +21,20 @@ interface Hashes {
2021

2122
const previousHashes: Hashes = {};
2223

24+
const NOT_FIRST_LEVEL_CHILD: [boolean, string[]] = [false, []];
25+
2326
const isFirstLevelPropsChild = (
2427
updatedPath: string,
25-
strPath: string
28+
strPath: string,
29+
descendantPrefix: string
2630
): [boolean, string[]] => {
27-
const updatedSegments = updatedPath.split(',');
28-
const fullSegments = strPath.split(',');
29-
30-
// Check that strPath actually starts with updatedPath
31-
const startsWithPath = fullSegments.every(
32-
(seg, i) => updatedSegments[i] === seg
33-
);
34-
35-
if (!startsWithPath) return [false, []];
31+
if (!isPathOrDescendant(updatedPath, strPath, descendantPrefix)) {
32+
return NOT_FIRST_LEVEL_CHILD;
33+
}
3634

37-
// Get the remaining path after the prefix
38-
const remainingSegments = updatedSegments.slice(fullSegments.length);
35+
const remainingSegments = updatedPath
36+
.slice(descendantPrefix.length)
37+
.split(',');
3938

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

@@ -49,12 +48,15 @@ function determineChangedProps(
4948
let combinedHash = 0;
5049
let renderType: any; // Default render type, adjust as needed
5150
const changedProps: Record<string, any> = {};
52-
Object.entries(state.layoutHashes).forEach(([updatedPath, pathHash]) => {
51+
const descendantPrefix = strPath + ',';
52+
Object.keys(state.layoutHashes).forEach(updatedPath => {
5353
const [descendant, remainingSegments] = isFirstLevelPropsChild(
5454
updatedPath,
55-
strPath
55+
strPath,
56+
descendantPrefix
5657
);
5758
if (descendant) {
59+
const pathHash = state.layoutHashes[updatedPath];
5860
const previousHash: any = pathOr({}, [updatedPath], previousHashes);
5961
combinedHash += pathOr(0, ['hash'], pathHash);
6062
if (previousHash !== pathHash) {

‎dash/dash-renderer/src/wrapper/wrapping.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,12 @@ export function stringifyPath(layoutPath: DashLayoutPath) {
5555
return join(',', layoutPath);
5656
}
5757

58-
export function isPathOrDescendant(strPath: string, prefix: string) {
59-
return strPath === prefix || strPath.startsWith(prefix + ',');
58+
export function isPathOrDescendant(
59+
strPath: string,
60+
prefix: string,
61+
descendantPrefix = prefix + ','
62+
) {
63+
return strPath === prefix || strPath.startsWith(descendantPrefix);
6064
}
6165

6266
export function getComponentLayout(
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import {expect} from 'chai';
2+
import {before, describe, it} from 'mocha';
3+
import {selectDashProps} from '../src/wrapper/selectors';
4+
5+
const leaf = {namespace: 'test_ns', type: 'Leaf', props: {}};
6+
const flagged = children => ({
7+
namespace: 'test_ns',
8+
type: 'Listens',
9+
props: {children}
10+
});
11+
12+
// The selector remembers the hashes it has seen in a module-level record, so
13+
// each test uses its own child index to stay independent of the others.
14+
const stateFor = (index, layoutHashes) => {
15+
const children = [];
16+
children[index] = flagged([leaf]);
17+
return {layout: {props: {children}}, layoutHashes};
18+
};
19+
20+
const select = (index, layoutHashes) => {
21+
const path = ['props', 'children', index];
22+
const [, , hash, changedProps, renderType] = selectDashProps(path)(
23+
stateFor(index, layoutHashes)
24+
);
25+
return {hash, changedProps, renderType};
26+
};
27+
28+
describe('selectDashProps with dashChildrenUpdate', () => {
29+
before(() => {
30+
window.test_ns = {Listens: {dashChildrenUpdate: true}, Leaf: {}};
31+
});
32+
33+
it('sums its own hash and those of its first level children', () => {
34+
const self = 'props,children,1';
35+
const {hash} = select(1, {
36+
[self]: {hash: 1},
37+
[`${self},props,children`]: {hash: 10},
38+
[`${self},props,children,0`]: {hash: 100}
39+
});
40+
expect(hash).to.equal(111);
41+
});
42+
43+
it('ignores deeper descendants and unrelated paths', () => {
44+
const self = 'props,children,2';
45+
const {hash} = select(2, {
46+
[self]: {hash: 1},
47+
[`${self},props,children,0,props,children`]: {hash: 10},
48+
'props,children,3': {hash: 100},
49+
props: {hash: 1000}
50+
});
51+
expect(hash).to.equal(1);
52+
});
53+
54+
it('does not mistake a sibling with the same prefix for a child', () => {
55+
const self = 'props,children,4';
56+
const {hash, changedProps} = select(4, {
57+
[self]: {hash: 1},
58+
'props,children,40': {hash: 10},
59+
'props,children,40,props,children': {hash: 100}
60+
});
61+
expect(hash).to.equal(1);
62+
expect(changedProps).to.deep.equal({});
63+
});
64+
65+
it('reports the prop of an updated child only once', () => {
66+
const hashes = {'props,children,5,props,children': {hash: 1}};
67+
expect(select(5, hashes)).to.deep.equal({
68+
hash: 1,
69+
changedProps: {children: true},
70+
renderType: 'components'
71+
});
72+
expect(select(5, hashes)).to.deep.equal({
73+
hash: 1,
74+
changedProps: {},
75+
renderType: undefined
76+
});
77+
});
78+
79+
it('reports its own changed props and render type', () => {
80+
const {hash, changedProps, renderType} = select(6, {
81+
'props,children,6': {
82+
hash: 2,
83+
changedProps: {value: 1},
84+
renderType: 'callback'
85+
}
86+
});
87+
expect(hash).to.equal(2);
88+
expect(changedProps).to.deep.equal({value: 1});
89+
expect(renderType).to.equal('callback');
90+
});
91+
});

0 commit comments

Comments
 (0)