Skip to content

Fix client startup, session and settings lifecycle - #223

Draft
ejsmith wants to merge 6 commits into
fix/queue-submission-reliabilityfrom
fix/client-lifecycle-settings
Draft

ejsmith wants to merge 6 commits into
fix/queue-submission-reliabilityfrom
fix/client-lifecycle-settings

Conversation

@ejsmith

@ejsmith ejsmith commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Stacked on #221; review that first.

Problem Fix
Exceptionless.config.apiKey = …; await Exceptionless.startup() skipped runtime setup: no global handlers, request info, browser/node/RN error plugins The first startup() call that leaves a valid API key configures the client, with or without arguments. Until then it stays unconfigured, so a later startup(cb) still works. Later calls only resume; configuration passed to them is ignored with a warning instead of silently
Every tab refocus (and RN foreground) sent a new session start, inflating session counts startup() starts a session only when none is active. Resuming continues the session and its heartbeats, unless the client was suspended for more than the server's 5-minute inactivity period, in which case a new session starts
Browser used beforeunload, which is unreliable on mobile and can keep pages out of the back/forward cache pagehide ends the session and sends the queue; pageshow from the back/forward cache resumes. React Native web also uses pagehide
The session end sent on page hide was a GET without keepalive, so it was cancelled with the page Requests without a body always use keepalive
applyServerSettings merged into the saved originals, so a setting the server later removed (for example an @@error:TypeError=false exclusion) stayed in effect until restart Rebuilt from the originals each time; non-string values are ignored
HeartbeatPlugin relied on each caller clearing the interval before starting a new one startHeartbeats clears any existing interval itself
Settings updates used one global lock, so a second client's update was skipped Locked per configuration
config.plugins sorted the live array, so removing a plugin while iterating skipped the next one Returns a sorted copy

Public API: no additions and no breaking changes. Short-lived processes keep using processQueue(), which now waits for a send that is already in progress (#221).

Checks: new lifecycle, settings and browser lifecycle tests; the ones covering fixed bugs fail on the base branch. npm test (395), npm run lint, and type-checks for core, browser, node and react-native pass. Skill docs (SKILL.md, sessions.md, troubleshooting.md) are updated.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-02T01:30:24.398303Z 4e9b490 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@ejsmith
ejsmith force-pushed the fix/client-lifecycle-settings branch from 161831a to 0903a18 Compare December 2, 2026 01:14

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 161831ad2b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ejsmith
ejsmith force-pushed the fix/client-lifecycle-settings branch from 0903a18 to c93b6d1 Compare December 2, 2026 01:21

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c93b6d1826

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

- startup() with no arguments now configures runtime plugins when the
  API key was set beforehand; the client stays unconfigured until a call
  leaves a valid key, and later calls only resume (configuration passed
  to them is ignored with a warning).
- Resuming a hidden tab no longer starts a new session every time; the
  session continues unless the client was suspended longer than the
  server's 5-minute inactivity period. Heartbeats resume with it.
- Browser: end the session and flush on pagehide instead of
  beforeunload, and resume on back/forward cache restore. React Native
  web also uses pagehide.
- Add flush(timeoutMs) for short-lived processes.
- Applying server settings no longer overwrites the original settings,
  so settings the server stops sending are removed; non-string values
  are ignored.
- Settings updates lock per configuration instead of globally.
- config.plugins returns a sorted copy so removing a plugin while
  iterating doesn't skip the next one.
A session end submitted on pagehide is a GET without a body, so it was
cancelled with the page.
Track which settings came from the server instead of rebuilding from a
snapshot taken at the first apply, so removed server settings are
cleared, overridden local values come back, and local changes made
after startup survive a refresh.
@ejsmith
ejsmith force-pushed the fix/client-lifecycle-settings branch from c93b6d1 to ed4cdbf Compare December 2, 2026 01:25

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ed4cdbfef0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

A local value equal to the incoming server value wasn't saved, so it
was deleted when the server later stopped sending that key.

await Exceptionless.processQueue();
// Waits at most 10 seconds by default; returns false if the queue didn't finish in time.
await Exceptionless.flush();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Flush must be new, historically always processQueue because it aligns with other clients.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed. I removed flush() in e66c52d, and the docs and skill now use processQueue() again, matching the other clients. The real fix is in #221: processQueue() called during a send now waits for that send to finish instead of returning straight away. The test "processQueue waits for a submission that is already in flight" covers it and fails against the old queue.


globalThis.addEventListener("beforeunload", () => {
// pagehide fires reliably on mobile and doesn't stop the page from entering the back/forward cache, unlike beforeunload.
globalThis.addEventListener("pagehide", () => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

beforeunload fires before pagehide and gives more time for submission.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I kept pagehide on purpose:

  • Mobile: beforeunload often doesn't fire on mobile (iOS Safari, or Android when the app is backgrounded or killed). pagehide does.
  • Back/forward cache: a beforeunload listener can keep the page out of the bfcache (Firefox, for example).
  • Cancelled navigation: beforeunload also fires when another handler cancels the navigation ("Leave site?" → Stay). We would then end a session that is still active.
  • Timing: the earlier start isn't lost. The order is beforeunload → visibilitychange (hidden) → pagehide, and the existing visibilitychange handler already suspends and starts the queue send there. Only the session end waits for pagehide.
  • Delivery: the request survives because it uses keepalive (added in Make queued event delivery reliable #221), not because it starts a few ms earlier.

If you still want beforeunload, I can add it alongside pagehide. That brings back the cancelled-navigation false session end.

export class BrowserExceptionlessClient extends ExceptionlessClient {
public async startup(configurationOrApiKey?: ((config: Configuration) => void) | string): Promise<void> {
const config = this.config;
if (configurationOrApiKey && !this._initialized) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

not sure why we had this check that we removed wasn't sure if was for double init

@ejsmith ejsmith Dec 2, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It wasn't a double-init guard. _initialized already covers that, and addPlugin skips a plugin whose name is already registered. The check only skipped registering the browser plugins when startup() was called with no arguments, for example a no-arg startup() after config.apiKey = ..., which then ran without global error capture. The test "should configure browser plugins when startup is called without arguments" covers it.

public get plugins(): IEventPlugin[] {
return this._plugins.sort((p1: IEventPlugin, p2: IEventPlugin) => {
// Sort a copy: callers iterate this list while plugins may add or remove plugins.
return [...this._plugins].sort((p1: IEventPlugin, p2: IEventPlugin) => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

sort mutates but js is single threaded (browsers) so how would there ever be an issue with this? Did we ever hit an issue with this with node??

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not a threading problem, and I have no report of it in the wild. The getter sorted _plugins in place and returned the live array. A caller iterating config.plugins (EventPluginManager awaits each plugin inside the loop) while a plugin calls removePlugin/addPlugin mutates the array it is iterating, so the next plugin gets skipped. The test "removing a plugin while iterating does not skip the next plugin" shows it synchronously. Returning a sorted copy costs a few plugins' worth of allocation. If you'd rather not carry it, I can revert it.


private startHeartbeats(client: ExceptionlessClient): void {
// Heartbeats always go to the session that is current when they fire.
this._intervalId = setInterval(() => void client.submitSessionHeartbeat(), this._interval);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

makes me wonder if we should be clearing the interval here if it's set before calling it again.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes. startHeartbeats now clears any existing interval itself (e66c52d), so a new caller cannot leak one. Before this, both callers cleared it first.

public async flush(timeoutMs: number = 10000): Promise<boolean> {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<boolean>((resolve) => {
timeoutId = setTimeout(() => resolve(false), timeoutMs);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

we should create a wait helper but also ensure it's cleaned up?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Gone with flush() (e66c52d), so there is no timeout race or timer left to clean up.

});

try {
return await Promise.race([this.processQueue().then(() => true), timeout]);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

really hate having a then here with fully async and await.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Gone with flush() (e66c52d).

@ejsmith
ejsmith marked this pull request as draft December 2, 2026 03:20

@niemyjski niemyjski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[AGENT] Overlapping startup calls still inflate session counts. I reproduced this on the current head.

const suspendedAt = this._suspendedAt;
this._suspendedAt = undefined;
const sessionExpired = suspendedAt !== undefined && Date.now() - suspendedAt > this.SESSION_INACTIVE_PERIOD;
if (this.config.sessionsEnabled && (!this._sessionActive || sessionExpired)) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[AGENT] Guard the in-flight session start. Promise.all([client.startup(), client.startup()]) with sessions and session ID management enabled sent two session events with distinct IDs. The same calls made sequentially sent one. Both calls can pass the check before either awaited submission sets _sessionActive. Share or reserve the start before awaiting it, and clear the reservation if the event is cancelled so a later resume can retry.

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.

2 participants