Skip to content

fix: Http2Adapter does not fail with StateError when connection is closed#2469

Closed
vanelizarov wants to merge 3 commits into
cfug:mainfrom
vanelizarov:fix/http2_adapter_state_error
Closed

fix: Http2Adapter does not fail with StateError when connection is closed#2469
vanelizarov wants to merge 3 commits into
cfug:mainfrom
vanelizarov:fix/http2_adapter_state_error

Conversation

@vanelizarov

@vanelizarov vanelizarov commented Dec 12, 2025

Copy link
Copy Markdown
Contributor

Periodically I receive unhandled StateError: Bad state: Cannot add event after closing in Crashlytics:

Stack Trace
StateError: Bad state: Cannot add event after closing
  *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** (***)
  pid: 19891, tid: 483148275864, name 1.ui (unparsed)
  android arch: arm64 comp: yes sim: no (os:)
  build_id: '4f1bdaeddbb49260128a5ff3c1e2e0c4' (unparsed)
  isolate_dso_base: 6ca549c000, vm_dso_base: 6ca549c000 (unparsed)
  isolate_instructions: 6ca5622940, vm_instructions: 6ca560c000 (unparsed)
#0      _StreamController.add (third_party/dart/sdk/lib/async/stream_controller.dart:617:24)
#1      _StreamSinkWrapper.add (third_party/dart/sdk/lib/async/stream_controller.dart:898:13)
#2      Http2Adapter._fetch.<anonymous closure> (/Users/vanelizarov/.pub-cache/git/dio-5259d4ae4fb665b8212c343c015e53fcbfe7d0b7/plugins/http2_adapter/lib/src/http2_adapter.dart:144:33)
#3      _RootZone.runUnaryGuarded (third_party/dart/sdk/lib/async/zone.dart:1778:10)
#4      _BufferingStreamSubscription._sendData (third_party/dart/sdk/lib/async/stream_impl.dart:381:11)
#5      _BufferingStreamSubscription._add (third_party/dart/sdk/lib/async/stream_impl.dart:312:7)
#6      _SinkTransformerStreamSubscription._add (third_party/dart/sdk/lib/async/stream_transformers.dart:67:11)
#7      _EventSinkWrapper.add (third_party/dart/sdk/lib/async/stream_transformers.dart:13:11)
#8      _transform.<anonymous closure> (/Users/vanelizarov/.pub-cache/hosted/pub.dev/dio-5.9.0/lib/src/progress_stream/io_progress_stream.dart:33:16)
#9      _HandlerEventSink.add (third_party/dart/sdk/lib/async/stream_transformers.dart:230:17)
#10     _SinkTransformerStreamSubscription._handleData (third_party/dart/sdk/lib/async/stream_transformers.dart:115:24)
#11     _SinkTransformerStreamSubscription._handleData (third_party/dart/sdk/lib/async/stream_transformers.dart:113:3)
#12     _RootZone.runUnaryGuarded (third_party/dart/sdk/lib/async/zone.dart:1778:10)
#13     _BufferingStreamSubscription._sendData (third_party/dart/sdk/lib/async/stream_impl.dart:381:11)
#14     _BufferingStreamSubscription._add (third_party/dart/sdk/lib/async/stream_impl.dart:312:7)
#15     _MultiStreamController.addSync (third_party/dart/sdk/lib/async/stream_impl.dart:1195:36)
#16     new Stream.fromIterable.<anonymous closure>.next (third_party/dart/sdk/lib/async/stream.dart:385:26)
#17     _microtaskLoop (third_party/dart/sdk/lib/async/schedule_microtask.dart:40:35)
#18     _startMicrotaskLoop (third_party/dart/sdk/lib/async/schedule_microtask.dart:49:5)
#19     _startMicrotaskLoop (third_party/dart/sdk/lib/async/schedule_microtask.dart:44:1)

This problem was mentioned earlier by me in this PR.

After investigation, it appears that the error was caused by a race condition, for example, when the server closed the connection before receiving the request body.

This PR introduces a more reliable way to handle such situations. It also includes a test that can be run with the old implementation to reproduce the described issue.

New Pull Request Checklist

  • I have read the Documentation
  • I have searched for a similar pull request in the project and found none
  • I have updated this branch with the latest main branch to avoid conflicts (via merge from master or rebase)
  • I have added the required tests to prove the fix/feature I'm adding
  • I have updated the documentation (if necessary)
  • I have run the tests without failures
  • I have updated the CHANGELOG.md in the corresponding package

@vanelizarov
vanelizarov requested a review from a team as a code owner December 12, 2025 14:03

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes a race condition in the Http2Adapter that caused unhandled StateError: Bad state: Cannot add event after closing exceptions when the server closes the connection before the client finishes sending the request body.

Key Changes:

  • Replaced the simple stream listener with a more robust approach using StreamSubscription, Completer, and explicit error handling to gracefully handle StateError
  • Added try-catch block around the final stream.outgoingMessages.close() call to prevent StateError propagation
  • Improved cancellation handling by properly cancelling subscriptions before closing streams

Reviewed changes

Copilot reviewed 3 out of 4 changed files in this pull request and generated 4 comments.

File Description
plugins/http2_adapter/lib/src/http2_adapter.dart Refactored request stream handling to catch StateError during data transmission and gracefully complete the request without propagating the error
plugins/http2_adapter/test/http2_test.dart Added test case that simulates server closing connection early to verify the StateError fix
plugins/http2_adapter/CHANGELOG.md Documented the bug fix in the unreleased section
.gitignore Added .history directory to ignore list

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread plugins/http2_adapter/lib/src/http2_adapter.dart Outdated
Comment thread plugins/http2_adapter/test/http2_test.dart
Comment thread plugins/http2_adapter/CHANGELOG.md Outdated
Comment thread plugins/http2_adapter/test/http2_test.dart
@vanelizarov

vanelizarov commented Dec 14, 2025

Copy link
Copy Markdown
Contributor Author

@AlexV525 should I take into account comments from AI or will you do the review manually?

@AlexV525

Copy link
Copy Markdown
Member

@AlexV525 should I take into account comments from AI or will you do the review manually?

@vanelizarov AI might give helpful suggestions. If you have opposite opinions, you can leave comments saying that you disagree with the suggestion. A manual review will be sent eventually, before the PR is merged.

Additionally, the suggestions in the above review seem reasonable.

@github-actions

Copy link
Copy Markdown
Contributor

Code Coverage Report: Only Changed Files listed

Package Base Coverage New Coverage Difference
plugins/http2_adapter/lib/src/connection_manager_imp.dart 🟢 78.83% 🟢 83.94% 🟢 5.11%
plugins/http2_adapter/lib/src/http2_adapter.dart 🟠 74.13% 🟢 78.48% 🟢 4.35%
Overall Coverage 🟢 87.95% 🟢 88.58% 🟢 0.63%

Minimum allowed coverage is 0%, this run produced 88.58%

Comment on lines +192 to +193
} on StateError {
// Ignore StateError, which may occur if the stream is already closed.

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.

I'm still not confident about shipping this implementation, given that we didn't find the root cause here. Could you share a reproducible case in production?

Comment on lines +194 to +196
} catch (_) {
rethrow;
}

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.

This seems redundant.

Comment thread .gitignore
Comment on lines +37 to +38
# Local history
.history No newline at end of file

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.

It would be better if you could submit a separate PR for this with more context.

@AlexV525

Copy link
Copy Markdown
Member

Superseded by #2571. The replacement is rebuilt on the current main branch, preserves credit for the original report and reproduction, addresses the unresolved review feedback, adds an exact transport-error regression test, and fixes the upload-cancellation hang found during adversarial review. Closing this stale, conflicting PR in favor of the replacement.

@AlexV525 AlexV525 closed this Jul 20, 2026
AlexV525 added a commit that referenced this pull request Jul 21, 2026
Supersedes #2469.

The original report and reproduction are credited to @vanelizarov. This
replacement is rebuilt on the current `main` branch and addresses the
unresolved review feedback and the cancellation hang found while
auditing the earlier implementation.

### Motivation

When an HTTP/2 peer closes a connection before a streamed request body
finishes, `http2` closes its outgoing stream controller. The request
body subscription can then deliver another chunk to the closed sink,
producing an unhandled `StateError: Bad state: Cannot add event after
closing` instead of the transport error that caused the closure.

### Changes

- Stop the request body subscription when the outgoing HTTP/2 sink has
already closed.
- Explicitly settle request-body waiting when cancellation stops the
subscription, rather than relying on `onDone`, which is not called after
cancellation.
- Keep cancellation callbacks weakly referenced so shared,
never-cancelled tokens do not retain completed request resources.
- Assert the exact `TransportConnectionException` for a peer connection
closure and cover cancellation while the source stream remains open.
- Update the `dio_http2_adapter` changelog.

### Verification

With only the new tests applied to `main`, the connection-closure test
fails with the reported `StateError`, and the cancellation test times
out after two seconds. Both pass with this change, and the cancellation
test also confirms that the source stream listener is removed.

`dart test` for `plugins/http2_adapter`, `melos run format`, and `melos
run analyze` complete successfully. An independent adversarial pass also
exercised 20 concurrent cancellations, send timeout, a synchronous
stream controller, and request-source error propagation.

### Hosted verification

The min, stable, and beta workflows all pass with the configured httpbun
and proxy services. The stable workflow also passes formatting,
analysis, publish dry-run, VM/Chrome/Firefox/Flutter tests, the example
APK build, and coverage reporting. Changed-file coverage for
`http2_adapter.dart` increases from 75.69% to 82.42%.

### AI assistance

Implementation, tests, and local review were performed with Codex. A
separate Codex sub-agent performed the adversarial review. The original
diagnosis and reproduction came from @vanelizarov in #2469.

### New Pull Request Checklist

- [x] I have read the
[Documentation](https://pub.dev/documentation/dio/latest/)
- [x] I have read the [Agent Contribution
Guidelines](https://github.com/cfug/dio/blob/main/AGENTS.md) (required
if any part of the change was produced with AI assistance)
- [ ] I have searched for a similar pull request in the
[project](https://github.com/cfug/dio/pulls) and found none *(not
applicable - this supersedes #2469)*
- [x] I have updated this branch with the latest `main` branch to avoid
conflicts (via merge from master or rebase)
- [x] I have added the required tests to prove the fix/feature I'm
adding
- [ ] I have updated the documentation (if necessary) *(not applicable -
no public API or documented behavior changes)*
- [x] I have run the tests without failures
- [x] I have updated the `CHANGELOG.md` in the corresponding package

### Additional context and info (if any)

The replacement preserves the final outgoing-sink close as a normal
`await`; the observed `StateError` originates from adding the next body
chunk after the transport has closed the sink, not from closing the sink
again.

Co-authored-by: Codex <noreply@openai.com>
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.

3 participants