Skip to content

Commit eff6a4e

Browse files
[9.0] [embeddable] fix race condition in useBatchedPublishingSubjects (elastic#216399) (elastic#216527)
# Backport This will backport the following commits from `main` to `9.0`: - [[embeddable] fix race condition in useBatchedPublishingSubjects (elastic#216399)](elastic#216399) <!--- Backport version: 9.6.6 --> ### Questions ? Please refer to the [Backport tool documentation](https://github.com/sorenlouv/backport) <!--BACKPORT [{"author":{"name":"Nathan Reese","email":"[email protected]"},"sourceCommit":{"committedDate":"2025-03-31T17:21:56Z","message":"[embeddable] fix race condition in useBatchedPublishingSubjects (elastic#216399)\n\nCloses elastic#214176 and\nhttps://github.com/elastic/issues/214853\n\n[upgrade from chrome 134 to 135 in functional test\nrunner](elastic#213919) revealed a race\ncondition in `useBatchedPublishingSubjects` where batched observables\ncould emit new values before `useEffect` sets up the subscription. This\nPR resolves this issue by setting up subscription in useRef, which has\nno timing delays.\n\nIn chrome 134, `useBatchedPublishingSubjects` `useEffect` gets called\n(setting up subscription) before lens embeddable emits any changes to\nbatched observables.\n<img width=\"300\" alt=\"chrome134\"\nsrc=\"https://github.com/user-attachments/assets/b0356f74-e0c7-4d93-a23a-ace519194d5d\"\n/>\n\nIn chrome 135, `useBatchedPublishingSubjects` `useEffect` gets called\nafter lens embeddable emits changes to batched observables. This causes\nthe lens embeddable to not render since the `LensEmbeddableComponent`\nhas a stale value for `expressionParams`.\n<img width=\"300\" alt=\"chrome135\"\nsrc=\"https://github.com/user-attachments/assets/320bfb7e-8b3f-4b48-a138-1c47c5ff9961\"\n/>\n\n---------\n\nCo-authored-by: Elastic Machine <[email protected]>\nCo-authored-by: kibanamachine <[email protected]>","sha":"f408a513dd5fdecf5ebbc4e3265e1b998421d39b","branchLabelMapping":{"^v9.1.0$":"main","^v8.19.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:fix","Team:Presentation","backport:version","v8.18.0","v9.1.0","v8.19.0","v9.0.1","v8.17.5","v8.16.7"],"title":"[embeddable] fix race condition in useBatchedPublishingSubjects","number":216399,"url":"https://github.com/elastic/kibana/pull/216399","mergeCommit":{"message":"[embeddable] fix race condition in useBatchedPublishingSubjects (elastic#216399)\n\nCloses elastic#214176 and\nhttps://github.com/elastic/issues/214853\n\n[upgrade from chrome 134 to 135 in functional test\nrunner](elastic#213919) revealed a race\ncondition in `useBatchedPublishingSubjects` where batched observables\ncould emit new values before `useEffect` sets up the subscription. This\nPR resolves this issue by setting up subscription in useRef, which has\nno timing delays.\n\nIn chrome 134, `useBatchedPublishingSubjects` `useEffect` gets called\n(setting up subscription) before lens embeddable emits any changes to\nbatched observables.\n<img width=\"300\" alt=\"chrome134\"\nsrc=\"https://github.com/user-attachments/assets/b0356f74-e0c7-4d93-a23a-ace519194d5d\"\n/>\n\nIn chrome 135, `useBatchedPublishingSubjects` `useEffect` gets called\nafter lens embeddable emits changes to batched observables. This causes\nthe lens embeddable to not render since the `LensEmbeddableComponent`\nhas a stale value for `expressionParams`.\n<img width=\"300\" alt=\"chrome135\"\nsrc=\"https://github.com/user-attachments/assets/320bfb7e-8b3f-4b48-a138-1c47c5ff9961\"\n/>\n\n---------\n\nCo-authored-by: Elastic Machine <[email protected]>\nCo-authored-by: kibanamachine <[email protected]>","sha":"f408a513dd5fdecf5ebbc4e3265e1b998421d39b"}},"sourceBranch":"main","suggestedTargetBranches":["8.18","8.x","9.0","8.17","8.16"],"targetPullRequestStates":[{"branch":"8.18","label":"v8.18.0","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"main","label":"v9.1.0","branchLabelMappingKey":"^v9.1.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/216399","number":216399,"mergeCommit":{"message":"[embeddable] fix race condition in useBatchedPublishingSubjects (elastic#216399)\n\nCloses elastic#214176 and\nhttps://github.com/elastic/issues/214853\n\n[upgrade from chrome 134 to 135 in functional test\nrunner](elastic#213919) revealed a race\ncondition in `useBatchedPublishingSubjects` where batched observables\ncould emit new values before `useEffect` sets up the subscription. This\nPR resolves this issue by setting up subscription in useRef, which has\nno timing delays.\n\nIn chrome 134, `useBatchedPublishingSubjects` `useEffect` gets called\n(setting up subscription) before lens embeddable emits any changes to\nbatched observables.\n<img width=\"300\" alt=\"chrome134\"\nsrc=\"https://github.com/user-attachments/assets/b0356f74-e0c7-4d93-a23a-ace519194d5d\"\n/>\n\nIn chrome 135, `useBatchedPublishingSubjects` `useEffect` gets called\nafter lens embeddable emits changes to batched observables. This causes\nthe lens embeddable to not render since the `LensEmbeddableComponent`\nhas a stale value for `expressionParams`.\n<img width=\"300\" alt=\"chrome135\"\nsrc=\"https://github.com/user-attachments/assets/320bfb7e-8b3f-4b48-a138-1c47c5ff9961\"\n/>\n\n---------\n\nCo-authored-by: Elastic Machine <[email protected]>\nCo-authored-by: kibanamachine <[email protected]>","sha":"f408a513dd5fdecf5ebbc4e3265e1b998421d39b"}},{"branch":"8.x","label":"v8.19.0","branchLabelMappingKey":"^v8.19.0$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"9.0","label":"v9.0.1","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"8.17","label":"v8.17.5","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"8.16","label":"v8.16.7","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"}]}] BACKPORT--> Co-authored-by: Nathan Reese <[email protected]>
1 parent bb3ac40 commit eff6a4e

File tree

2 files changed

+52
-13
lines changed

2 files changed

+52
-13
lines changed

src/platform/packages/shared/presentation/presentation_publishing/publishing_subject/publishing_batcher.ts

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
* License v3.0 only", or the "Server Side Public License, v 1".
88
*/
99

10-
import { useEffect, useRef, useState } from 'react';
10+
import { useEffect, useMemo, useRef, useState } from 'react';
1111
import { combineLatest, debounceTime, skip } from 'rxjs';
1212
import { AnyPublishingSubject, PublishingSubject, UnwrapPublishingSubjectTuple } from './types';
1313

@@ -120,22 +120,37 @@ export const useBatchedPublishingSubjects = <
120120

121121
/**
122122
* Subscribe to all subjects and update the latest values when any of them change.
123+
*
124+
* Can not set up subscription in useEffect.
125+
* useEffect introduces a race condition where subscriptions may emit after values are set with useState
126+
* but before subscription is setup in useEffect.
127+
*
128+
* Can not set up subscription in useRef.
129+
* useRef executes initialization logic every render.
123130
*/
124-
useEffect(() => {
125-
const subscription = combineLatest(subjects)
126-
.pipe(
127-
// When a new observer subscribes to a BehaviorSubject, it immediately receives the current value. Skip this emit.
128-
skip(1),
129-
debounceTime(0)
130-
)
131-
.subscribe((values) => {
132-
setLatestPublishedValues(values as UnwrapPublishingSubjectTuple<SubjectsType>);
133-
});
134-
return () => subscription.unsubscribe();
131+
const subscription = useMemo(
132+
() =>
133+
combineLatest(subjects)
134+
.pipe(
135+
// When a new observer subscribes to a BehaviorSubject, it immediately receives the current value. Skip this emit.
136+
skip(1),
137+
debounceTime(0)
138+
)
139+
.subscribe((values) => {
140+
setLatestPublishedValues(values as UnwrapPublishingSubjectTuple<SubjectsType>);
141+
}),
135142
// 'subjects' gets a new reference on each call because of spread
136143
// Use 'useBatchedOptionalPublishingSubjects' when 'subjects' are expected to change.
137144
// eslint-disable-next-line react-hooks/exhaustive-deps
138-
}, []);
145+
[]
146+
);
147+
148+
/**
149+
* Clean up subscription on unmount.
150+
*/
151+
useEffect(() => {
152+
return () => subscription.unsubscribe();
153+
}, [subscription]);
139154

140155
return latestPublishedValues;
141156
};

src/platform/packages/shared/presentation/presentation_publishing/publishing_subject/publishing_subject.test.tsx

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,30 @@ describe('publishing subject', () => {
118118
expect(renderCount).toBe(2);
119119
});
120120

121+
test('useBatchedPublishingSubjects should synchronously subscribe to observables to avoid race conditions', async () => {
122+
function Component() {
123+
const [value1] = useBatchedPublishingSubjects(subject1);
124+
125+
// synchronously emit new values for observables
126+
// this will cause test to fail if subscriptions are not setup synchronously
127+
incrementAll();
128+
129+
return (
130+
<>
131+
<span>{`value1: ${value1}`}</span>
132+
</>
133+
);
134+
}
135+
render(<Component />);
136+
await waitFor(() => {
137+
expect(
138+
// If there is a race condition, then 'value1: 0' will be rendered
139+
// because value1 will have the original value '0' instead of latest value
140+
screen.getByText('value1: 1')
141+
).toBeInTheDocument();
142+
});
143+
});
144+
121145
test('should batch state updates when using useBatchedOptionalPublishingSubjects', async () => {
122146
let renderCount = 0;
123147
function Component() {

0 commit comments

Comments
 (0)