Skip to content

feat: add evaluation sync status listener - #357

Draft
duyhungtnn wants to merge 14 commits into
fix/stream-error-event-not-alivefrom
feat/status-listener
Draft

duyhungtnn wants to merge 14 commits into
fix/stream-error-event-not-alivefrom
feat/status-listener

Conversation

@duyhungtnn

@duyhungtnn duyhungtnn commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #355

Built on #362 (a stream that only sends a server error event now gives up and falls back to polling). Please review and merge #362 first. This PR's merge target will move to main after that.

What

Apps can now see when updating flag values fails, and when it works again. A failure is reported only after the SDK's existing polling retries are used up, not after one failed request.

New BKTClient methods:

  • evaluationSyncStatus(): returns the current status.
  • addEvaluationSyncStatusListener(listener): returns a listener id.
  • removeEvaluationSyncStatusListener(listenerId)
  • clearEvaluationSyncStatusListeners()

New exported types: BKTEvaluationSyncStatus, BKTEvaluationSyncState, BKTEvaluationSyncError, BKTEvaluationSyncStatusListener.

How the status works

State When
INITIALIZING No sync result yet. It can last after initializeBKTClient() finishes: when the first fetch fails, the state stays INITIALIZING until a sync succeeds, or polling fails after its retries.
SYNCED The last poll or stream update worked.
FAILING Polling used up its retries (also the polling fallback while streaming is down), or init failed for a reason other than the request. lastError has the cause and the time.
DESTROYED After destroyBKTClient(). Sent once, then all listeners are removed.
  • A success sets SYNCED at once.
  • Listeners are called on every state change and on every failure that is not ignored. A change to lastSyncedAt alone calls no listener.
  • Polling failures are ignored while the stream works: the stream keeps the flags current, so a failed poll says nothing about them.
  • Stream heartbeats move lastSyncedAt forward, but only while the stream works (a valid put or patch arrived, and no error since).
  • A listener that throws is logged and does not stop polling or the stream.
  • A listener that destroys the client stops polling at once: no poll is sent after that, whether the listener runs on a polling success or failure.
  • A poll that finishes after polling was stopped (destroy, or the stream reconnected) reports nothing.

When a failure is reported

Flow Reported
Polling (also the polling fallback) Only when the existing retries are used up: the 6th failure in a row, about 5 minutes after the first one. With pollingInterval of 60 s or less there is no retry, so every failure is reported.
Streaming Never. A failed connection try, a server event: error, or the give-up (a terminal error, or 120 s with no working connection) reports nothing. They only mark the stream as not working, so heartbeats stop moving lastSyncedAt and polling failures count again. After a give-up, the polling fallback starts at once, and its results decide the status. The fallback stops only when a reopened stream delivers a valid put or patch, not when it opens, so a stream that opens and then fails does not reset the fallback's retries.
First fetch at init A failed request is not reported (initializeBKTClient() still rejects as before). The poller reports later, after its retries, and that moves INITIALIZING to FAILING. An init error not related to the request (for example a custom storageFactory that throws) sets FAILING at once, as IllegalStateException.
Manual fetchEvaluations() A failure is not reported (it still throws as before). A success sets SYNCED.

Known startup cases (#363)

The JS SDK opens the stream at the same time as the first fetch. So the stream, or the polling fallback it starts, can change the status before initializeBKTClient() ends, and an init error that comes after that is not shown in the status. These cases are not fixed here. #363 opens the stream only after the first fetch ends, like the mobile SDKs, and that removes them.

Why the stream reports no failure

The status says whether the flag values are current. After the stream gives up, the polling fallback keeps them current. Reporting the stream error as well made the status flip between FAILING and SYNCED and told the app nothing new.

The cost: when the server really has a problem, the app sees FAILING only after the poller's retries, with the polling error. Why the stream stopped belongs in tracking events sent to the backend, not in the status. The decision is written above StreamingSyncReporter.

Tests

  • New EvaluationSyncStatusTracker.spec.ts, plus new suites in the BKTClient, EvaluationInteractor, EvaluationTask, StreamConnection, StreamingTask and BKTException specs.
  • 620 of 620 pass on Node and browser. Type check, lint and build pass.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unresolved defects can leave stream health stale across reconnects, replace meaningful server errors with unknown errors, and notify listeners of destruction twice.

3 open issues
What changed in this PR

Adds evaluation sync status reporting for #355, letting applications observe polling and streaming failures and recovery independently of flag-value changes.

Changes:

  • Adds public status types and client methods for reading status and managing listeners.
  • Connects polling, streaming, initialization, and destruction to a shared status tracker.
  • Shares HTTP error mapping between polling and streaming and adds regression tests.
File Description
test/​internal/​streaming/​StreamingTask.spec.ts Tests stream status, recovery, fallback, and error mapping.
test/​internal/​streaming/​StreamConnection.spec.ts Tests transport failure and heartbeat callbacks.
test/​internal/​evaluation/​EvaluationSyncStatusTracker.spec.ts Tests status transitions and listener behavior.
test/​internal/​evaluation/​EvaluationInteractor.spec.ts Tests polling and streaming result reporting.
test/​BKTException.spec.ts Tests shared HTTP status mapping.
test/​BKTClient.spec.ts Tests public status APIs and lifecycle behavior.
src/​main.ts Exports sync status types.
src/​main.native.ts Exports sync status types for native consumers.
src/​main.browser.ts Exports sync status types for browsers.
src/​internal/​streaming/​StreamingTask.ts Maps stream errors and reports stream activity.
src/​internal/​streaming/​StreamConnection.ts Adds transport failure and liveness callbacks.
src/​internal/​remote/​toBKTException.ts Extracts shared HTTP error mapping.
src/​internal/​evaluation/​StreamingSyncReporter.ts Defines streaming status reporting interface.
src/​internal/​evaluation/​EvaluationSyncStatusTracker.ts Implements status tracking and listener dispatch.
src/​internal/​evaluation/​EvaluationSyncReporter.ts Defines evaluation result reporting interface.
src/​internal/​evaluation/​EvaluationInteractor.ts Reports polling and streaming results.
src/​internal/​di/​InteractorModule.ts Constructs and injects status reporting components.
src/​internal/​di/​Component.ts Shares one tracker through focused interfaces.
src/​BKTEvaluationSyncStatus.ts Defines public status, error, and listener types.
src/​BKTClient.ts Exposes status APIs and lifecycle notifications.

Review effort: Balanced

Comment thread src/internal/streaming/StreamingTask.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Critical reentrant lifecycle bugs prevent replacement initialization from DESTROYED callbacks and allow startup to continue after destruction, leaving an orphaned flush timer and issuing a bootstrap fetch.

2 open issues
3 resolved since last review

Review effort: Balanced

Comment thread src/BKTClient.ts Resolved
Comment thread src/internal/streaming/StreamingTask.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

If initializeCache() rejects, the sync tracker is never finalized, leaving registered listeners stuck in INITIALIZING instead of notifying them after singleton cleanup so they can safely retry.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Medium severity Finalize sync tracker when cache initialization fails

src/​BKTClient.ts:492

If initializeCache() rejects, its earlier catch clears the singleton and rethrows without finalizing the sync tracker. An app that registered a listener while initialization was pending is left with INITIALIZING indefinitely, although initialization has ended and no tasks will start. Finalize the tracker on that failure path too, notifying listeners after singleton cleanup so a callback can safely retry initialization.

1 resolved since last review

Review effort: Balanced

@duyhungtnn

Copy link
Copy Markdown
Collaborator Author

About the Copilot item "Finalize sync tracker when cache initialization fails" (src/BKTClient.ts:492):

Fixed in c68eb52.

Thanks, good catch. When initializeCache() rejects, the client is removed first, then its listeners get DESTROYED, so a listener can start a new client. The app still gets the error from the rejected promise.

Details
  • Fix:
    clearInstance()
    // The client is gone, so its sync status must not stay INITIALIZING.
    // Sends DESTROYED after clearInstance(), so a listener can start a new
    // client here. The app still gets the error from the rejected promise.
    client.markSyncStatusDestroyed()
    }
  • Test: a cache load failure at init gives DESTROYED, and the listener can start a new client (
    test('a cache load failure at init gives DESTROYED, and the listener can start a new client', async () => {
    )
  • DESTROYED, not FAILING: FAILING means the SDK keeps retrying, but here the client is gone.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues are reported for the evaluation sync-status reporting changes.

1 open issue

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues remain for the evaluation sync status reporting change.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@duyhungtnn
duyhungtnn marked this pull request as ready for review November 10, 2026 02:57
Copilot AI balanced review requested due to automatic review settings November 10, 2026 02:57

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues remain for the evaluation sync status reporting change.

No open issues 🎉

Review effort: Balanced

@duyhungtnn

duyhungtnn commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator Author

@cre8ivejp please help me to take a look.

This changes has the e2e test here #358

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues remain for the SDK’s evaluation sync status reporting changes.

No open issues 🎉

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 26, 2026 10:51

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

An initialization race can leave the tracker stuck in INITIALIZING after fallback polling exhausts its retries; unsuccessful initialization must promote the recorded failure to FAILING while preserving its cause and occurrence time.

No open issues 🎉

Review effort: Balanced

A polling failure reported after its retries now moves INITIALIZING to
FAILING at once, even before the init request ends. Before, the state
stayed INITIALIZING until init finished, so a failed fallback poll during
init was shown only in lastError.

finishInitializing() is replaced by reportInitError(), called only for an
init error not related to the request.
Copilot AI balanced review requested due to automatic review settings November 26, 2026 14:44

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Human assessment is needed because an SDK-typed task-startup exception may leave the client stuck in INITIALIZING without an error or notification.

No open issues 🎉

Review effort: Balanced

@duyhungtnn
duyhungtnn marked this pull request as draft November 26, 2026 14:53
@duyhungtnn
duyhungtnn marked this pull request as ready for review November 26, 2026 15:02
@duyhungtnn

Copy link
Copy Markdown
Collaborator Author

No change needed. About the overview note "an SDK-typed task-startup exception may leave the client stuck in INITIALIZING". The reason is now written in the code in 13a0929.

Details
  • Init errors are split by where they come from. A failed first fetch is only the first try, so it is not reported: the poller (or the stream fallback) reports after its retries. Any other init error (for example a custom storageFactory that throws) sets FAILING at once.
  • The code tells them apart by type, and that is enough: only the first fetch throws SDK exceptions during init. Task startup throws none (a stream open error is caught in StreamConnection), and app code that runs during startup (storageFactory, an injected EventSource) cannot create one, since the SDK exception classes are not exported and isBKTException() checks with instanceof.

Copilot AI balanced review requested due to automatic review settings November 26, 2026 15:03

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Human assessment is needed because streaming recovery can repeatedly reset polling retries, leaving the status SYNCED or INITIALIZING indefinitely despite every poll failing.

No open issues 🎉

Review effort: Balanced

@duyhungtnn
duyhungtnn marked this pull request as draft November 26, 2026 15:11
The backend answers the stream request with 200 before it evaluates. When
evaluation fails, it sends an error event and closes. The fallback was
stopped when the stream opened, so every 5-minute recovery try threw away
its retry count, and the next give-up started a new fallback from zero.
Its last retry never ran, and FAILING was never reported.

The fallback now stops on the first valid put or patch, the same signal
that marks the stream as working everywhere else.
@duyhungtnn

Copy link
Copy Markdown
Collaborator Author

Fixed in c596384. About the overview note "streaming recovery can repeatedly reset polling retries, leaving the status SYNCED or INITIALIZING indefinitely despite every poll failing".

Details
  • The backend answers the stream request with 200 before it evaluates. When evaluation fails, it sends an error event and closes the stream.
  • The polling fallback was stopped when the stream opened. So every 5-minute recovery try threw away the fallback's retry count, and the next give-up started a new fallback from zero. Its last retry never ran, and FAILING never came.
  • Now the fallback stops only on the first valid put or patch, the same signal that marks the stream as working for the give-up window and for the sync status. A stream that opens and then fails leaves the fallback running, so it uses up its retries and reports FAILING.
  • Tests: "when every reopened stream fails before a put, the fallback still uses up its retries and sets FAILING" (real poller, the backend's 200 then error answer, past the 5-minute recovery) and "a reopened stream that fails before any put keeps the same polling fallback".

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Human assessment is needed because a critical race allows an older stream save to overwrite a newer fallback failure and incorrectly report SYNCED.

No open issues 🎉

Review effort: Balanced

@duyhungtnn

Copy link
Copy Markdown
Collaborator Author

No change needed. About the overview note "an older stream save can overwrite a newer fallback failure and report SYNCED". Test added in 489e2c0 (renamed in cb8b994).

Details
  • The race needs a fallback poll that fails while the save of a put is running. No poll runs then:
    • The put stops the running fallback before the save starts. A poll that was already sent reports nothing after that.
    • A new fallback starts only when the stream gives up. In an outage the backend answers the stream with 500 or 503, or 200 then an error event and close. All of these are retried, so the stream does not give up during the save.
  • The race is possible only if all of these are true: pollingInterval of 60 s (no polling retries), a save that takes more than 1 s, and a reconnect answered with a status that gives up at once (for example 401), or no working stream for 120 s. A real save takes less than 0.01 s.
  • Test: "an older stream save cannot overwrite a newer fallback failure with SYNCED, because no fallback poll runs during the save". It uses the real poller, pollingInterval 60 s and polls that fail at once. A fallback is running when the put arrives. During the save, the stream gets an error event and closes, and its reconnect gets 503. The save is held open for 90 s. Result: no poll during the save, and SYNCED after it.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Human assessment is needed because an older asynchronous stream save can overwrite a newer polling failure with SYNCED, masking that streaming has stopped.

No open issues 🎉

Review effort: Balanced

@duyhungtnn

Copy link
Copy Markdown
Collaborator Author

No change needed. About the overview note "an older asynchronous stream save can overwrite a newer polling failure with SYNCED, masking that streaming has stopped". This is the same case as the previous note, answered in #357 (comment).

Details
  • While streaming is on, the only polling that reports a failure is the fallback, and no fallback poll runs during the save of a put. Test: "an older stream save cannot overwrite a newer fallback failure with SYNCED, because no fallback poll runs during the save".
  • "Streaming has stopped" is not shown in the status on purpose: the stream never reports a failure, and after a give-up only the polling fallback's results decide the status. See "Why the stream reports no failure" in the PR description.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: notify apps when fetching flag values fails and when it recovers

2 participants