Skip to content

fix(core): resolve request-scoped forward refs for concurrent requests - #18200

Merged
kamilmysliwiec merged 2 commits into
nestjs:masterfrom
maxymlyskov:fix/detect-forward-ref-cycles-per-context
Oct 20, 2026
Merged

kamilmysliwiec merged 2 commits into
nestjs:masterfrom
maxymlyskov:fix/detect-forward-ref-cycles-per-context

Conversation

@maxymlyskov

Copy link
Copy Markdown
Contributor

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Other... Please describe:

What is the current behavior?

Since #18186, two request-scoped providers that forwardRef() each other can throw CircularDependencyException when a few requests resolve them at the same time. One request at a time is fine. This shipped in v12.2.0.

The settlement signal belongs to one load, but it's only stored on the shared wrapper. applySettlementSignal makes a new signal per load and puts it on host.settlementSignal, so the latest load of any context replaces it.

And everything else reads it from there. The pending check reads wrapper.settlementSignal, the edges (L678, L727) go into inquirer.settlementSignal, and the deferred-load catch errors instanceWrapper.settlementSignal. Any of them can end up on another request's signal.

That was mostly harmless until #18186 added resolutionContext.inquirer?.settlementSignal?.insertRef(instanceWrapper) before the forwardRef load. Wrapper ids are the same in every context, so a pending host that reads another request's unfinished signal finds that inquirer edge and throws.

The catch has its own problem: one request's failing dependency can error a signal some other request is waiting on, so healthy requests get rejected with it.

Real express 5.3.0 app on master, Node v22.23.3. The round lines fire 30 concurrent requests, 3 of them for a tenant whose database is down. First of 3 runs here (the counts move around between runs, but every run had failures):

PROBE master concurrent resolve x2: ok=2 failed=0 
PROBE master concurrent resolve x10: ok=8 failed=2 CircularDependencyException: A circular dependency has been detected inside "Update". Please, make sure that 
PROBE master concurrent resolve x50: ok=48 failed=2 CircularDependencyException: A circular dependency has been detected inside "Update". Please, make sure that 
PROBE round 1: 30 concurrent (3 'down' tenant, 27 'up'): {"down:500":3,"up:500":16,"up:200":11} errors logged: {"Error: tenant \"down\" database unreachable":3,"Error: A circular dependency has been detected inside \"Create\". Please, make sure that eac":16}
PROBE round 2: 30 concurrent (3 'down' tenant, 27 'up'): {"down:500":3,"up:500":4,"up:200":23} errors logged: {"Error: A circular dependency has been detected inside \"Create\". Please, make sure that eac":4,"Error: tenant \"down\" database unreachable":3}
PROBE round 3: 30 concurrent (3 'down' tenant, 27 'up'): {"down:500":3,"up:200":25,"up:500":2} errors logged: {"Error: A circular dependency has been detected inside \"Create\". Please, make sure that eac":2,"Error: tenant \"down\" database unreachable":3}
PROBE control sequential 30 (3 down, 27 up): {"down:500":3,"up:200":27}
PROBE master HTTP GET /r sequential x40: {"200":40}
PROBE master HTTP GET /r x1: {"200 {\"ok\":true}":1}
PROBE master HTTP GET /r x20: {"500 {\"statusCode\":500,\"message\":\"Internal server error\"}":10,"200 {\"ok\":true}":10}

Issue Number: N/A

Steps to reproduce

  1. take the specs from this PR, run git checkout master -- packages/core/injector/injector.ts packages/core/injector/instance-wrapper.ts, then run the new and changed tests in packages/core/test/injector/injector.spec.ts and npx vitest run --config vitest.config.integration.mts integration/injector/e2e/request-scoped-forward-ref.spec.ts -t "for every request|rejects only the requests whose dependency fails"
  2. Expected: every request builds both providers, and only the requests whose own dependency fails get rejected
  3. Actual (raw output on untouched master):
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 6 ⎯⎯⎯⎯⎯⎯⎯
 FAIL  packages/core/test/injector/injector.spec.ts > Injector > loadInstance > when "isPending" and the wrapper is also loaded for another context > should not throw when only the load for the other context waits on the inquirer
AssertionError: promise rejected "Error: A circular dependency has been det…" instead of resolving
Caused by: Error: A circular dependency has been detected inside "MainTest". Please, make sure that each side of a bidirectional relationships are decorated with "forwardRef()". Note that circular relationships between custom providers (e.g., factories) are not supported since functions cannot be called more than once.
 FAIL  packages/core/test/injector/injector.spec.ts > Injector > loadInstance > when "isPending" and the wrapper is also loaded for another context > should throw when the pending load waits on the inquirer
AssertionError: promise resolved "undefined" instead of rejecting
 FAIL  packages/core/test/injector/injector.spec.ts > Injector > resolveComponentHost > when the inquirer is also loaded for another context > should record a dependency without forward ref in the signal of this context
 FAIL  packages/core/test/injector/injector.spec.ts > Injector > resolveComponentHost > when the inquirer is also loaded for another context > should record a dependency with forward ref in the signal of this context
AssertionError: expected false to be true // Object.is equality
 FAIL  packages/core/test/injector/injector.spec.ts > Injector > resolveComponentHost > when the inquirer is also loaded for another context > should follow the signal of the dependency for this context
AssertionError: expected false to be true // Object.is equality
 FAIL  packages/core/test/injector/injector.spec.ts > Injector > resolveComponentHost > when instanceWrapper has forward ref and is in non-static context > should call settlementSignal.error when loadProvider throws
AssertionError: expected "error" to be called once, but got 0 times
 Test Files  1 failed (1)
      Tests  6 failed | 1 passed | 77 skipped (84)
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 2 ⎯⎯⎯⎯⎯⎯⎯
 FAIL  integration/injector/e2e/request-scoped-forward-ref.spec.ts > Request-scoped providers with a forward reference > when resolving circular providers directly > when several requests resolve them at once > constructs both providers with two-sided forward references for every request
Error: A circular dependency has been detected inside "UpdateUsecase". Please, make sure that each side of a bidirectional relationships are decorated with "forwardRef()". Note that circular relationships between custom providers (e.g., factories) are not supported since functions cannot be called more than once.
 FAIL  integration/injector/e2e/request-scoped-forward-ref.spec.ts > Request-scoped providers with a forward reference > when resolving circular providers directly > when several requests resolve them at once > rejects only the requests whose dependency fails
AssertionError: expected [ 'rejected', 'rejected', …(18) ] to deeply equal [ 'rejected', 'fulfilled', …(18) ]
 Test Files  1 failed (1)
      Tests  2 failed | 1 passed | 28 skipped (31)

What is the new behavior?

Each context keeps its own signal. InstancePerContext gets a settlementSignal field and applySettlementSignal stores the signal on the per-context host too. The wrapper still gets the latest one, since it's a public field and I didn't want to pull it out from under anyone.

  • the pending check reads instanceHost.settlementSignal
  • a private insertSettlementRef(resolutionContext, wrapper, instanceHost) writes the edge into the inquirer's signal for this context (inquirer.getInstanceByContextId(getContextId(contextId, inquirer))). The ref it inserts has a settlementSignal getter over the dependency's per-context host, so it follows the right load
  • the deferred-load catch errors this context's host signal, so a failure stays in its own request

A transient inquirer keeps using its wrapper's latest signal. Its host is keyed by its own inquirer, and the resolution context doesn't carry that, so there's nothing to look up. A unit test pins that fallback (it passes on master too).

What stays the same: single-request resolution, and #18186's own cases. The one-sided cycle from #18186 is still rejected for every request under concurrency, and doesn't hang.

Same probe on the branch, all 3 runs gave identical output (the master tag is hard-coded in the probe, these lines run the branch source):

PROBE master concurrent resolve x2: ok=2 failed=0 
PROBE master concurrent resolve x10: ok=10 failed=0 
PROBE master concurrent resolve x50: ok=50 failed=0 
PROBE round 1: 30 concurrent (3 'down' tenant, 27 'up'): {"down:500":3,"up:200":27} errors logged: {"Error: tenant \"down\" database unreachable":3}
PROBE round 2: 30 concurrent (3 'down' tenant, 27 'up'): {"down:500":3,"up:200":27} errors logged: {"Error: tenant \"down\" database unreachable":3}
PROBE round 3: 30 concurrent (3 'down' tenant, 27 'up'): {"down:500":3,"up:200":27} errors logged: {"Error: tenant \"down\" database unreachable":3}
PROBE control sequential 30 (3 down, 27 up): {"down:500":3,"up:200":27}
PROBE master HTTP GET /r sequential x40: {"200":40}
PROBE master HTTP GET /r x1: {"200 {\"ok\":true}":1}
PROBE master HTTP GET /r x20: {"200 {\"ok\":true}":20}

Does this PR introduce a breaking change?

  • Yes
  • No

The public API is the same apart from one optional field on InstancePerContext.

Other information

The e2e cases sit inside #18186's "when resolving circular providers directly" block. createFixture takes an optional request-scoped CONNECTION dependency, @Optional() on both sides, so #18186's existing cases run exactly as before. The new describe resolves 20 requests at once, each with its own registered request, all under #18186's withTimeout. There's also a control case for the one-sided cycle; it passes on master and on the branch.

The existing "should call settlementSignal.error when loadProvider throws" test now puts the signal on the host instead of the wrapper, since that's where the catch reads it now.

I couldn't make the edge-writer change fail an e2e test on its own. 30 concurrent resolves with async deps over 4 timings gave the same result with only the pending read fixed and with the full fix (20 CircularDependencyException, 10 ok, no hang; master gave 22 / 8). I kept it because the check and the edges should use the same signal, and the unit tests pin it.

Validation on Node v22.23.3:

  • the 2 new e2e tests failed on master in 3 of 3 runs and pass on the branch in 3 of 3
  • 6 of the 7 new or changed unit tests fail on master, all 7 pass on the branch. 4 mutations of the fix, all 4 caught
  • full unit suite: branch 4795 passed / 1 failed, master 4789 passed / 1 failed. The one failure is packages/common/test/services/logger.service.spec.ts "should serialise a plain JS object (as a message) without context to the console", and it fails the same way on master here
  • integration (vitest.config.integration.mts) for injector, scopes, hooks, lazy-modules, inspector, discovery, testing-module-override, module-utils and hello-world: branch 531 passed, master 528 passed, 0 failed
  • tsc -p tsconfig.spec.json error set unchanged (296 on master and on the branch), prettier and oxlint clean

maxymlyskov and others added 2 commits October 20, 2026 08:01
Since nestjs#18186, concurrent requests that resolve a two-sided forwardRef()
pair of request-scoped providers can fail with a false
CircularDependencyException. Each load creates its own settlement
signal, but it was only stored on the shared wrapper, so the pending
check, the recorded cycle edges and the deferred-load failure used the
signal of whichever context loaded the wrapper last.

Each per-context instance now keeps its own signal, and the three sites
use the signals of the context being resolved.
An object literal with a getter on every unresolved edge made resolving request-scoped chains about 12% slower. Also cover resolving both sides of a one-sided cycle at once.
@kamilmysliwiec
kamilmysliwiec merged commit 2786cbe into nestjs:master Oct 20, 2026
4 checks passed
kamilmysliwiec added a commit that referenced this pull request Nov 9, 2026
A wrapper keeps the signal of its latest load for the lifetime of the
application. Since #18200 the refs of a signal point at per-context
hosts, so the instances of the latest request, and whatever they
reference, stayed reachable after the request had ended.

A settled signal is never walked by isCycle(), so its refs are dropped
when it settles. An edge can still arrive afterwards, as a transient
inquirer records it on the latest signal of its wrapper, which a
concurrent load may have settled, so insertRef() ignores those too.
ttt43ttt pushed a commit to NoDevelopers/ts-monorepo that referenced this pull request Nov 22, 2026
| datasource | package                  | from   | to     |
| ---------- | ------------------------ | ------ | ------ |
| npm        | @nestjs/common           | 12.2.0 | 12.3.1 |
| npm        | @nestjs/core             | 12.2.0 | 12.3.1 |
| npm        | @nestjs/platform-express | 12.2.0 | 12.3.1 |


## [v12.3.1](nestjs/nest@v12.3.0...v12.3.1)



## [v12.3.0](https://github.com/nestjs/nest/releases/tag/v12.3.0)

#### v12.3.0 (2026-10-27)

##### Features

- `platform-node`
  - [#18063](nestjs/nest#18063) feat(node): add a native node http platform adapter ([@kamilmysliwiec](https://github.com/kamilmysliwiec))

##### Bug fixes

- `common`
  - [#18289](nestjs/nest#18289) fix(common): report the detected file type in file type errors ([@DenisCDev](https://github.com/DenisCDev))
  - [#18246](nestjs/nest#18246) fix(common): avoid throwing for arrow prototype constructors ([@fengxueweilai](https://github.com/fengxueweilai))
  - [#18220](nestjs/nest#18220) fix(common): abort the response when a streamable file fails midway ([@thekhegay](https://github.com/thekhegay))
- `core`
  - [#18276](nestjs/nest#18276) fix(core): run middleware once for routes that differ only in version ([@OmBhandwaldar](https://github.com/OmBhandwaldar))
  - [#18262](nestjs/nest#18262) fix(core): tolerate sse request sockets without tuning methods ([@SnowingFox](https://github.com/SnowingFox))
  - [#18252](nestjs/nest#18252) fix(core): read the url protocol from the server ([@thekhegay](https://github.com/thekhegay))
  - [#18254](nestjs/nest#18254) fix(core): name the array and index of undefined module entries ([@thekhegay](https://github.com/thekhegay))
  - [#18235](nestjs/nest#18235) fix(core): discover classes by each of their discovery decorators ([@OmBhandwaldar](https://github.com/OmBhandwaldar))
  - [#18216](nestjs/nest#18216) fix(core): read the abort on error option of the app being called ([@thekhegay](https://github.com/thekhegay))
  - [#18209](nestjs/nest#18209) fix(core): let middleware exclusions cover prefix-excluded routes ([@thekhegay](https://github.com/thekhegay))
  - [#18210](nestjs/nest#18210) fix(core): honor abortOnError passed to select() ([@Cayan](https://github.com/Cayan))
  - [#18215](nestjs/nest#18215) fix(core): subscribe to handler observables from other rxjs copies ([@koreahghg](https://github.com/koreahghg))
  - [#18201](nestjs/nest#18201) fix(core): read a quoted media type version in the middleware exclusions ([@hktitof](https://github.com/hktitof))
  - [#18200](nestjs/nest#18200) fix(core): resolve request-scoped forward refs for concurrent requests ([@maxymlyskov](https://github.com/maxymlyskov))
- `common`, `microservices`, `platform-ws`
  - [#18285](nestjs/nest#18285) fix(ws,microservices): load packages where bundlers can see them ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `common`, `microservices`, `websockets`
  - [#18272](nestjs/nest#18272) fix(common): keep one route param per argument in an overriding method ([@maxymlyskov](https://github.com/maxymlyskov))
- `platform-express`
  - [#18264](nestjs/nest#18264) fix(express): map unsupported multipart content types to 415 ([@seren-wib](https://github.com/seren-wib))
  - [#18234](nestjs/nest#18234) fix(express): end a head response for an empty streamable file ([@spokodev](https://github.com/spokodev))
  - [#18232](nestjs/nest#18232) fix(express): leave 5xx http-errors errors unmapped so they are logged ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#18214](nestjs/nest#18214) fix(platform-express): map http-errors exceptions to HttpException in Express adapter ([@okxint](https://github.com/okxint))
  - [#18199](nestjs/nest#18199) fix(express): send the standard body for an exception wrapping an error ([@KAPUIST](https://github.com/KAPUIST))
- `platform-fastify`
  - [#18253](nestjs/nest#18253) fix(fastify): send object error bodies with a json content type ([@maxymlyskov](https://github.com/maxymlyskov))
  - [#18240](nestjs/nest#18240) fix(fastify): leave 5xx fastify errors unmapped so they are logged ([@thekhegay](https://github.com/thekhegay))
  - [#18239](nestjs/nest#18239) fix(fastify): map 4xx http-errors errors to http exceptions ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#18226](nestjs/nest#18226) fix(fastify): listen on a file descriptor ([@thekhegay](https://github.com/thekhegay))
  - [#18217](nestjs/nest#18217) fix(fastify): run cors before nest middleware ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `core`, `platform-express`, `platform-fastify`, `platform-socket.io`, `platform-ws`, `websockets`
  - [#18251](nestjs/nest#18251) fix(core,express,fastify,ws,socket.io): load adapters with an older core ([@thekhegay](https://github.com/thekhegay))
- `microservices`
  - [#18250](nestjs/nest#18250) fix(microservices): re-arm the redis retries on a new listen ([@hktitof](https://github.com/hktitof))
  - [#18255](nestjs/nest#18255) fix(microservices): report a nats connection that gave up reconnecting ([@thekhegay](https://github.com/thekhegay))
  - [#18249](nestjs/nest#18249) fix(microservices): do not emit a trailing null to kafka requesters ([@thekhegay](https://github.com/thekhegay))
  - [#18256](nestjs/nest#18256) fix(microservices): let a retriable exception keep travelling ([@hktitof](https://github.com/hktitof))
  - [#18238](nestjs/nest#18238) fix(microservices): retry the tcp server again after close and listen ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#18223](nestjs/nest#18223) fix(microservices): clear the tcp retry timer when a new listen starts ([@hktitof](https://github.com/hktitof))
  - [#18221](nestjs/nest#18221) fix(microservices): honor mqtt topic filter boundaries ([@fabric0de](https://github.com/fabric0de))
  - [#18229](nestjs/nest#18229) fix(microservices): let only the exact message handler answer a request ([@maxymlyskov](https://github.com/maxymlyskov))
  - [#18211](nestjs/nest#18211) fix(microservices): fail the request when its last reply cannot be sent ([@maxymlyskov](https://github.com/maxymlyskov))
  - [#18206](nestjs/nest#18206) fix(microservices): reset the tcp retry attempts on each listen ([@hktitof](https://github.com/hktitof))
  - [#18204](nestjs/nest#18204) fix(microservices): count every failed rmq connection attempt ([@maxymlyskov](https://github.com/maxymlyskov))
  - [#18197](nestjs/nest#18197) fix(microservices): send the record headers of nats as message headers ([@hktitof](https://github.com/hktitof))

##### Dependencies

- `platform-express`
  - [#18268](nestjs/nest#18268) fix(deps): update dependency multer to v2.5.0 \[security] ([@renovate\[bot\]](https://github.com/apps/renovate))
- `common`
  - [#18257](nestjs/nest#18257) fix(deps): update dependency file-type to v22.2.0 ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `platform-fastify`
  - [#18219](nestjs/nest#18219) fix(deps): update dependency [@fastify/middie](https://github.com/fastify/middie) to v9.3.6 ([@renovate\[bot\]](https://github.com/apps/renovate))

##### Committers: 16

- Abdellatif Anaflous ([@hktitof](https://github.com/hktitof))
- Daniel Pinto ([@Cayan](https://github.com/Cayan))
- Denis Scarabelli ([@DenisCDev](https://github.com/DenisCDev))
- Junpei Zhang ([@pei711](https://github.com/pei711))
- Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- Luke Son ([@KAPUIST](https://github.com/KAPUIST))
- Maksym Lyskov ([@maxymlyskov](https://github.com/maxymlyskov))
- Om Bhandwaldar ([@OmBhandwaldar](https://github.com/OmBhandwaldar))
- Roman Khegay ([@thekhegay](https://github.com/thekhegay))
- Spoko Dev ([@spokodev](https://github.com/spokodev))
- [@fengxueweilai](https://github.com/fengxueweilai)
- [@okxint](https://github.com/okxint)
- snowingfox ([@SnowingFox](https://github.com/SnowingFox))
- yooseong ([@seren-wib](https://github.com/seren-wib))
- 김정현 (Kim JungHyeon) ([@fabric0de](https://github.com/fabric0de))
- 한국 ([@koreahghg](https://github.com/koreahghg))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants