Skip to content

Commit 633c261

Browse files
fix(architecture): make fcose layout deterministic via architecture.seed
The cytoscape-fcose layout calls Math.random() internally in its constraint solver regardless of randomize:false, so the visual test 'should render a deterministic layout for a complex deeply-nested diagram' failed on every CI run (and was disabled in #7728 pending this fix). Adds an `architecture.seed` config field (default 1) that temporarily swaps Math.random for a mulberry32 seeded generator around the two layout.run() invocations and restores it in a finally block. The non-zero default makes every architecture diagram render with the same layout on every render; setting `architecture.seed: 0` opts out of the swap and restores the pre-fix non-deterministic behavior for callers who want layout variety. Re-enables the previously skipped cypress test, injects `architecture.seed = 1` from the test helper alongside handDrawnSeed=1, and adds a new test that exercises an explicit seed override. Resolves #7729
1 parent d02833c commit 633c261

10 files changed

Lines changed: 165 additions & 23 deletions

File tree

‎.changeset/architecture-seed.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'mermaid': patch
3+
---
4+
5+
fix: add `architecture.seed` config option to make architecture diagrams render deterministically. The underlying `cytoscape-fcose` layout calls `Math.random()` internally even with `randomize: false`, so visual regression tests failed on every CI run. The renderer now temporarily seeds `Math.random` with a mulberry32 seeded generator while `fcose` runs and restores it immediately after. Default seed is `1`, making architecture layouts deterministic by default — set `architecture.seed: 0` to opt out of seeding and recover the pre-fix non-deterministic behavior. Resolves #7729.

‎cypress/helpers/util.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ export const mermaidUrl = (
3131
api: boolean
3232
): string => {
3333
options.handDrawnSeed = 1;
34+
// Make the architecture fcose layout deterministic. Tests can still override
35+
// by passing { architecture: { seed: N } } in their own options.
36+
options.architecture = { seed: 1, ...(options.architecture ?? {}) };
3437
const codeObject: CodeObject = {
3538
code: graphStr,
3639
mermaid: options,

‎cypress/integration/rendering/architecture/architecture.spec.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ describe('architecture diagram', () => {
242242
`
243243
);
244244
});
245-
it.skip('should render a deterministic layout for a complex deeply-nested diagram', () => {
245+
it('should render a deterministic layout for a complex deeply-nested diagram', () => {
246246
imgSnapshotTest(
247247
`architecture-beta
248248
group sub1(cloud)[Subscription A]
@@ -284,6 +284,26 @@ describe('architecture diagram', () => {
284284
{ architecture: { randomize: false } }
285285
);
286286
});
287+
it('should render a deterministic layout with an explicit seed override', () => {
288+
// Exercises the architecture.seed config knob added for #7729. The default
289+
// helper-injected seed is 1; using a different value here proves the config
290+
// plumbing reaches the layout RNG.
291+
imgSnapshotTest(
292+
`architecture-beta
293+
group sub1(cloud)[Subscription A]
294+
group vnet1(cloud)[VNet A] in sub1
295+
service vm1(server)[VM] in vnet1
296+
297+
group sub2(cloud)[Subscription B]
298+
service web(server)[Web App] in sub2
299+
service db(database)[Registry] in sub2
300+
301+
vm1:R --> L:web
302+
web:R --> L:db
303+
`,
304+
{ architecture: { seed: 42 } }
305+
);
306+
});
287307
it('should render edges at correct length', () => {
288308
imgSnapshotTest(`
289309
architecture-beta

‎docs/syntax/architecture.md‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -195,9 +195,9 @@ architecture-beta
195195

196196
### `randomize` (v11.14.0+)
197197

198-
By default, architecture diagrams produce a deterministic layout: the same diagram source always renders with the same node positions. This is because the `randomize` option defaults to `false`.
198+
By default, architecture diagrams start nodes at deterministic seed positions (`randomize: false`). Setting `randomize` to `true` randomizes initial node positions before running the layout algorithm, which may produce varied but potentially better-spaced layouts on each render.
199199

200-
Setting `randomize` to `true` randomizes initial node positions before running the layout algorithm, which may produce varied but potentially better-spaced layouts on each render.
200+
> Note: `randomize: false` alone is not enough to guarantee identical renders — the underlying fcose layout still calls `Math.random()` during its constraint solver. Use the `seed` option (described below) to lock the layout fully.
201201
202202
Via frontmatter:
203203

@@ -228,12 +228,13 @@ mermaid.initialize({
228228

229229
The following options pass through to the underlying [fcose](https://github.com/iVis-at-Bilkent/cytoscape.js-fcose) layout so you can adjust spacing and density without changing your diagram source:
230230

231-
| Option | Type | Default | Description |
232-
| --------------------------- | ------ | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
233-
| `nodeSeparation` | number | `75` | Minimum separation, in pixels, between sibling nodes in the same group. Pass-through to fcose. |
234-
| `idealEdgeLengthMultiplier` | number | `1.5` | Multiplier applied to `iconSize` to compute the ideal length of edges between nodes within the same group. Increase for breathing room, decrease to pack tighter. Cross-group edges are not affected. |
235-
| `edgeElasticity` | number | `0.45` | Spring elasticity (0–1) on same-group edges. Higher pulls connected nodes closer; lower lets them spread out. Cross-group edges are not affected. |
236-
| `numIter` | number | `2500` | Maximum fcose iterations. Increase for higher-quality layouts on large diagrams at the cost of render time. |
231+
| Option | Type | Default | Description |
232+
| --------------------------- | ------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
233+
| `nodeSeparation` | number | `75` | Minimum separation, in pixels, between sibling nodes in the same group. Pass-through to fcose. |
234+
| `idealEdgeLengthMultiplier` | number | `1.5` | Multiplier applied to `iconSize` to compute the ideal length of edges between nodes within the same group. Increase for breathing room, decrease to pack tighter. Cross-group edges are not affected. |
235+
| `edgeElasticity` | number | `0.45` | Spring elasticity (0–1) on same-group edges. Higher pulls connected nodes closer; lower lets them spread out. Cross-group edges are not affected. |
236+
| `numIter` | number | `2500` | Maximum fcose iterations. Increase for higher-quality layouts on large diagrams at the cost of render time. |
237+
| `seed` | number | `1` | Deterministic seed for fcose. Defaults to `1` so the same diagram always renders with the same layout. Set to `0` to opt out and use native (non-deterministic) `Math.random`. Any other number selects a different reproducible layout variant. |
237238

238239
Example — bumping `idealEdgeLengthMultiplier` stretches the spacing between connected nodes in a chain:
239240

‎packages/mermaid/src/config.type.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1120,8 +1120,11 @@ export interface ArchitectureDiagramConfig extends BaseDiagramConfig {
11201120
fontSize?: number;
11211121
/**
11221122
* Whether to randomize initial node positions before running the layout algorithm.
1123-
* When false (default), the layout is deterministic and produces identical results on every render.
1124-
* When true, nodes start at random positions, which may produce varied but potentially better-spaced layouts.
1123+
* When false (default), nodes start at deterministic seed positions. When true, nodes
1124+
* start at random positions, which may produce varied but potentially better-spaced
1125+
* layouts. Note: `randomize: false` alone does NOT guarantee identical renders, because
1126+
* the underlying fcose layout still uses `Math.random()` internally during its
1127+
* constraint solver — use the `seed` option for full determinism.
11251128
*
11261129
*/
11271130
randomize?: boolean;
@@ -1152,6 +1155,15 @@ export interface ArchitectureDiagramConfig extends BaseDiagramConfig {
11521155
*
11531156
*/
11541157
numIter?: number;
1158+
/**
1159+
* Deterministic seed for the fcose layout. Defaults to 1, which makes every render of the
1160+
* same diagram produce the same layout — required for visual regression tests to be stable.
1161+
* Set to 0 to opt out and use the unstubbed Math.random (the layout will still differ
1162+
* slightly between renders, matching pre-fix behavior). Any other number selects a
1163+
* different reproducible layout variant.
1164+
*
1165+
*/
1166+
seed?: number;
11551167
}
11561168
/**
11571169
* The object containing configurations specific for mindmap diagrams

‎packages/mermaid/src/diagrams/architecture/architectureRenderer.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { LayoutOptions, Position } from 'cytoscape';
22
import cytoscape from 'cytoscape';
33
import fcose from 'cytoscape-fcose';
4+
import { withSeededRandom } from './architectureSeed.js';
45
import { select } from 'd3';
56
import type { DrawDefinition, SVG } from '../../diagram-api/types.js';
67
import type { Diagram } from '../../Diagram.js';
@@ -410,6 +411,9 @@ function layoutArchitecture(
410411
const sameGroupIdealLength = db.getConfigField('idealEdgeLengthMultiplier') * iconSize;
411412
const crossGroupIdealLength = 0.5 * iconSize;
412413
const sameGroupElasticity = db.getConfigField('edgeElasticity');
414+
// Wrap each layout.run() with withSeededRandom so fcose's internal
415+
// Math.random() calls produce reproducible results. See architectureSeed.ts.
416+
const seed = db.getConfigField('seed');
413417

414418
const layout = cy.layout({
415419
name: 'fcose',
@@ -506,9 +510,9 @@ function layoutArchitecture(
506510
}
507511
}
508512
cy.endBatch();
509-
layout.run();
513+
withSeededRandom(seed, () => layout.run());
510514
});
511-
layout.run();
515+
withSeededRandom(seed, () => layout.run());
512516

513517
cy.ready((e) => {
514518
log.info('Ready', e);
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import { describe, it, expect } from 'vitest';
2+
import { withSeededRandom } from './architectureSeed.js';
3+
4+
describe('withSeededRandom', () => {
5+
it('produces identical Math.random sequences for the same seed', () => {
6+
const draw = () => [Math.random(), Math.random(), Math.random(), Math.random()];
7+
const a = withSeededRandom(42, draw);
8+
const b = withSeededRandom(42, draw);
9+
expect(a).toEqual(b);
10+
});
11+
12+
it('produces different sequences for different seeds', () => {
13+
const draw = () => [Math.random(), Math.random(), Math.random()];
14+
expect(withSeededRandom(1, draw)).not.toEqual(withSeededRandom(2, draw));
15+
});
16+
17+
it('returns Math.random values in [0, 1)', () => {
18+
const values = withSeededRandom(123, () => Array.from({ length: 32 }, () => Math.random()));
19+
for (const v of values) {
20+
expect(v).toBeGreaterThanOrEqual(0);
21+
expect(v).toBeLessThan(1);
22+
}
23+
});
24+
25+
it('restores the original Math.random after the callback returns', () => {
26+
const original = Math.random;
27+
withSeededRandom(7, () => Math.random());
28+
expect(Math.random).toBe(original);
29+
});
30+
31+
it('restores the original Math.random even when the callback throws', () => {
32+
const original = Math.random;
33+
expect(() =>
34+
withSeededRandom(7, () => {
35+
throw new Error('boom');
36+
})
37+
).toThrow('boom');
38+
expect(Math.random).toBe(original);
39+
});
40+
41+
it('returns the callback result', () => {
42+
expect(withSeededRandom(1, () => 'hello')).toBe('hello');
43+
expect(withSeededRandom(1, () => 42)).toBe(42);
44+
});
45+
46+
it('does not stub Math.random when seed is 0 (opt-out into native randomness)', () => {
47+
const original = Math.random;
48+
const observed = withSeededRandom(0, () => Math.random);
49+
expect(observed).toBe(original);
50+
expect(Math.random).toBe(original);
51+
});
52+
});
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Temporarily replace `Math.random` with a mulberry32-seeded PRNG for the
3+
* duration of `fn`, then restore the original. Used to make the
4+
* cytoscape-fcose layout deterministic — fcose calls `Math.random` internally
5+
* in its constraint solver and exposes no `seed` option of its own, so the
6+
* only reliable way to get repeatable layouts is to swap the global at the
7+
* narrowest possible scope.
8+
*
9+
* A seed of `0` is treated as "opt out": the global is left alone and `fn`
10+
* runs against the real `Math.random`. This preserves the pre-fix behavior
11+
* for any caller that explicitly wants layout variety per render.
12+
*/
13+
export function withSeededRandom<T>(seed: number, fn: () => T): T {
14+
if (seed === 0) {
15+
return fn();
16+
}
17+
const original = Math.random;
18+
let state = seed >>> 0;
19+
Math.random = function () {
20+
state = (state + 0x6d2b79f5) >>> 0;
21+
let t = state;
22+
t = Math.imul(t ^ (t >>> 15), t | 1);
23+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
24+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
25+
};
26+
try {
27+
return fn();
28+
} finally {
29+
Math.random = original;
30+
}
31+
}

‎packages/mermaid/src/docs/syntax/architecture.md‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -157,9 +157,9 @@ architecture-beta
157157

158158
### `randomize` (v11.14.0+)
159159

160-
By default, architecture diagrams produce a deterministic layout: the same diagram source always renders with the same node positions. This is because the `randomize` option defaults to `false`.
160+
By default, architecture diagrams start nodes at deterministic seed positions (`randomize: false`). Setting `randomize` to `true` randomizes initial node positions before running the layout algorithm, which may produce varied but potentially better-spaced layouts on each render.
161161

162-
Setting `randomize` to `true` randomizes initial node positions before running the layout algorithm, which may produce varied but potentially better-spaced layouts on each render.
162+
> Note: `randomize: false` alone is not enough to guarantee identical renders — the underlying fcose layout still calls `Math.random()` during its constraint solver. Use the `seed` option (described below) to lock the layout fully.
163163
164164
Via frontmatter:
165165

@@ -190,12 +190,13 @@ mermaid.initialize({
190190

191191
The following options pass through to the underlying [fcose](https://github.com/iVis-at-Bilkent/cytoscape.js-fcose) layout so you can adjust spacing and density without changing your diagram source:
192192

193-
| Option | Type | Default | Description |
194-
| --------------------------- | ------ | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
195-
| `nodeSeparation` | number | `75` | Minimum separation, in pixels, between sibling nodes in the same group. Pass-through to fcose. |
196-
| `idealEdgeLengthMultiplier` | number | `1.5` | Multiplier applied to `iconSize` to compute the ideal length of edges between nodes within the same group. Increase for breathing room, decrease to pack tighter. Cross-group edges are not affected. |
197-
| `edgeElasticity` | number | `0.45` | Spring elasticity (0–1) on same-group edges. Higher pulls connected nodes closer; lower lets them spread out. Cross-group edges are not affected. |
198-
| `numIter` | number | `2500` | Maximum fcose iterations. Increase for higher-quality layouts on large diagrams at the cost of render time. |
193+
| Option | Type | Default | Description |
194+
| --------------------------- | ------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
195+
| `nodeSeparation` | number | `75` | Minimum separation, in pixels, between sibling nodes in the same group. Pass-through to fcose. |
196+
| `idealEdgeLengthMultiplier` | number | `1.5` | Multiplier applied to `iconSize` to compute the ideal length of edges between nodes within the same group. Increase for breathing room, decrease to pack tighter. Cross-group edges are not affected. |
197+
| `edgeElasticity` | number | `0.45` | Spring elasticity (0–1) on same-group edges. Higher pulls connected nodes closer; lower lets them spread out. Cross-group edges are not affected. |
198+
| `numIter` | number | `2500` | Maximum fcose iterations. Increase for higher-quality layouts on large diagrams at the cost of render time. |
199+
| `seed` | number | `1` | Deterministic seed for fcose. Defaults to `1` so the same diagram always renders with the same layout. Set to `0` to opt out and use native (non-deterministic) `Math.random`. Any other number selects a different reproducible layout variant. |
199200

200201
Example — bumping `idealEdgeLengthMultiplier` stretches the spacing between connected nodes in a chain:
201202

‎packages/mermaid/src/schemas/config.schema.yaml‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -990,6 +990,7 @@ $defs: # JSON Schema definition (maybe we should move these to a separate file)
990990
- idealEdgeLengthMultiplier
991991
- edgeElasticity
992992
- numIter
993+
- seed
993994
properties:
994995
padding:
995996
type: number
@@ -1003,8 +1004,11 @@ $defs: # JSON Schema definition (maybe we should move these to a separate file)
10031004
randomize:
10041005
description: |
10051006
Whether to randomize initial node positions before running the layout algorithm.
1006-
When false (default), the layout is deterministic and produces identical results on every render.
1007-
When true, nodes start at random positions, which may produce varied but potentially better-spaced layouts.
1007+
When false (default), nodes start at deterministic seed positions. When true, nodes
1008+
start at random positions, which may produce varied but potentially better-spaced
1009+
layouts. Note: `randomize: false` alone does NOT guarantee identical renders, because
1010+
the underlying fcose layout still uses `Math.random()` internally during its
1011+
constraint solver — use the `seed` option for full determinism.
10081012
type: boolean
10091013
default: false
10101014
nodeSeparation:
@@ -1034,6 +1038,15 @@ $defs: # JSON Schema definition (maybe we should move these to a separate file)
10341038
quality on large or densely-connected diagrams at the cost of render time.
10351039
type: number
10361040
default: 2500
1041+
seed:
1042+
description: |
1043+
Deterministic seed for the fcose layout. Defaults to 1, which makes every render of the
1044+
same diagram produce the same layout — required for visual regression tests to be stable.
1045+
Set to 0 to opt out and use the unstubbed Math.random (the layout will still differ
1046+
slightly between renders, matching pre-fix behavior). Any other number selects a
1047+
different reproducible layout variant.
1048+
type: number
1049+
default: 1
10371050

10381051
MindmapDiagramConfig:
10391052
title: Mindmap Diagram Config

0 commit comments

Comments
 (0)