Repository navigation
fix(core): let a lazy module load again after its first load() failed - #18183
maxymlyskov wants to merge 1 commit into
Conversation
When a provider of a lazily loaded module throws while load() builds it (a database that is briefly down, say), load() rejects but the module stays registered with its module class already instantiated. The next load() finds it through scanForModules and returns the same ModuleRef: the failed provider reads as null, the providers built next to it hold null, and it stays that way until the process restarts. On a failure while scanning or instantiating, remove the modules of this load() from the container again, with their global module, dynamic metadata and discovery entries, so the next load() builds them like a first load. Like the logger restore of nestjs#17631, the cleanup stays inside load().
micalevisk
left a comment
There was a problem hiding this comment.
Thanks for the detailed write-up, it made this easy to verify.
I checked out 9b2f747 locally and traced the paths it touches. The diagnosis matches the code. Injector#loadInstance drops the failed static host in its catch, so the wrapper falls back to the { instance: null, isResolved: true } default. The module class wrapper is already built, so isInstantiated short-circuits every later load(). removeModules() undoes what setModule() / addDynamicMetadata() / addGlobalModule() register, plus the discovery entries.
What I ran:
npm run build, thennpx vitest run packages/core: 1629 passed.- The 3 new specs fail on master's sources with the output from the description, and pass here.
npm run lint:ci: clean apart from one pre-existing warning inwebsockets. The prettier diffs incontainer.tsandlazy-module-loader.spec.tsare on master too.- Integration suites
lazy-modules,discovery,injector,scopesandinspector: 204 passed. - An express app over HTTP against the built packages:
req1=500 req2=200 req3=200, factory called twice. - Two concurrent failing
load()s of a@Globallazy module, then a retry:globalModulesis back to its original size and a later lazy module gets the working export. - A retry started from the first rejection while a second
load()of the same module is still pending: it builds once and later loads return the same ref.
Blocking: the rollback evicts a module that a concurrent, successful load() is still using. Details and a failing spec are inline.
Non-blocking / follow-up:
- Providers that were built during a failed attempt are dropped, and every retry builds new ones. Lazy modules never get shutdown hooks anyway, because
getModulesToTriggerHooksOn()caches the module list atinit(). So a sibling that opens a socket, such as a Redis client next to a failing DB provider, leaks one instance per failed retry. On master it leaks only once. A sentence about this in the docs would help. - The lazy-loading docs page says modules are "cached on the first
LazyModuleLoader#loadmethod invocation". It's worth a follow-up in nestjs/docs.nestjs.com stating that aload()that rejects is not cached and the next call builds the module again.
| ); | ||
| } catch (err) { | ||
| // Half-built modules would otherwise be returned by every later load(). | ||
| this.dependenciesScanner.removeModules(lazyModulesContainer.values()); |
There was a problem hiding this comment.
Blocking. This removes every module in the batch, including a not-yet-instantiated module that a concurrent load() also picked up and is still building. After that load() succeeds, the module is gone from the container. The next load() of it, or of any new lazy module that imports it, builds a second set of singletons. Its providers also disappear from DiscoveryService.
Scenario: AModule and BModule both import a lazy SharedModule. They are loaded concurrently, A fails on its own provider, and B succeeds.
| master | this PR | |
|---|---|---|
SharedModule in the container after A fails |
yes | no |
later load(() => SharedModule) |
cached | builds SharedService again |
This spec passes on master (3/3) and fails here (3/3) with expected 3 to be 2:
it('should not evict a module that a concurrent load() still uses', async () => {
const delay = (ms: number) => new Promise(r => setTimeout(r, ms));
let sharedInstances = 0;
@Injectable()
class SharedService {
constructor() {
sharedInstances++;
}
}
@Module({ providers: [SharedService], exports: [SharedService] })
class SharedModule {}
@Module({
imports: [SharedModule],
providers: [
{
provide: 'FAIL',
useFactory: () =>
delay(10).then(() => Promise.reject(new Error('A failed'))),
},
],
})
class AModule {}
@Module({
imports: [SharedModule],
providers: [{ provide: 'SLOW', useFactory: () => delay(30) }],
})
class BModule {}
const [a, b] = await Promise.allSettled([
lazyModuleLoader.load(() => AModule),
lazyModuleLoader.load(() => BModule),
]);
expect(a.status).toBe('rejected');
expect(b.status).toBe('fulfilled');
const instancesBefore = sharedInstances;
await lazyModuleLoader.load(() => SharedModule);
expect(sharedInstances).toBe(instancesBefore);
});The naive fixes have a catch. I tried keeping modules that another in-flight load() still has in its batch, and keeping modules that a module outside the batch imports. Both make this spec pass, but both break a case this PR currently handles correctly:
load(() => X)fails whileload(() => Z), whereZimportsX, is still in flight.- A retry of
Xstarts from the first rejection.
With the PR as it is, that retry gets a working X. With either variant, it gets the cached broken X, which stays broken after Z fails. Please add a spec for that race too, so whatever approach you take keeps it green.
| DiscoverableMetaHostCollection.metaHostLinks.delete(DiscoverableProvider); | ||
| }); | ||
|
|
||
| it('should remove the modules with their global, dynamic and discoverable entries', async () => { |
There was a problem hiding this comment.
Nit: removeInstanceWrappers() also walks controllersByMetaKey, but this spec only registers a discoverable provider. Adding a discoverable controller through container.addController() and asserting that getControllersByMetaKey() is empty would cover that branch.
|
Thanks for working on this! Adding to @micalevisk's review, here are two more cases where the rollback removes a module that another
The second one needs an identity check before each delete, e.g. Two smaller points:
|
|
Some numbers from master for case 1 in @kamilmysliwiec's comment (3a44abf, same harness as lazy-module-loader.spec.ts) Master alredy builds X twice when two
Also So maybe start from one build per module - map of in-flight loads by token, concurrent private readonly loadsInFlight = new Map<string, Promise<ModuleRef>>();
async load(loaderFn, loadOpts) {
const definition = await loaderFn();
const { token } = await this.moduleCompiler.compile(definition);
let loading = this.loadsInFlight.get(token);
if (!loading) {
// loadModule = current body with your try/catch
loading = this.loadModule(definition, loadOpts).finally(() =>
this.loadsInFlight.delete(token),
);
this.loadsInFlight.set(token, loading);
}
return loading;
}Entry is deleted before callers see rejection, so retry from Tried it on 9b2f747 togehter with identity check from @kamilmysliwiec's comment: specs for same-time, mid-build, case 1 and case 2 fail on PR and pass with it, @micalevisk's retry race stays green. Can paste them Not covered: two different lazy modules importing same new module (@micalevisk's AModule/BModule), and cycle where A's factory loads B and B's loads A now hangs instead of returning half built A |
kratos0722
left a comment
There was a problem hiding this comment.
Nice fix — returning a half-built module from every subsequent load() after a failed first load is a genuinely confusing failure mode, and the two added tests (a regular module and a global module both rebuilding on the next load(), asserting factoryCalls === 2) pin the behavior down well.
A couple of notes from reading through it:
-
In
removeInstanceWrappers, deleting from thewrappersSet while iterating it withfor...ofis safe here since only the current element is removed — Set iteration won't skip the elements that follow — so no concern there. -
The one thing I wasn't sure about: does
lazyModulesContainer.values()capture modules thatscanModulesForDependenciesdiscovers transitively? If scanning a lazy module pulls in a nested imported module that gets added to the main container but isn't part oflazyModulesContainer, would that nested module be left half-built on failure (i.e. not covered byremoveModules)? IfcreateLazyModulesContaineralready scopes to exactly the modules that scanning can add, this is moot — I just wanted to confirm the cleanup set matches the set that scanning can grow.
Either way the core approach (clean up the partially-built modules, then rethrow) looks right.
|
Thanks for working on this! Closing it for now, since the earlier review points are still open. A safe rollback first needs concurrent |
PR Checklist
Please check if your PR fulfills the following requirements:
PR Type
What kind of change does this PR introduce?
What is the current behavior?
When a provider factory in a lazy module rejects,
LazyModuleLoader.load()rethrows but leaves the half-built modules in the container.createInstancesOfDependencieshas already built the module class next to its providers, soModule#isInstantiatedis true. The failed provider has no static instance, which reads as{ instance: null, isResolved: true }, so the providers resolved next to it getnullinjected.nest/packages/core/injector/lazy-module-loader/lazy-module-loader.ts
Lines 21 to 60 in c8923bd
On the next
load(),scanForModuleshitslazy && !moduleInserted && moduleInstance?.isInstantiatedand returns[], soload()takes the "loaded already" branch and hands back the same brokenModuleRef. The factory is never called again.nest/packages/core/scanner.ts
Lines 116 to 120 in c8923bd
A
@Globalmodule is worse. It also stays inglobalModules, and lazy modules get globals bound throughbindGlobalsToImports, so a module loaded later imports the dead copy. The failed modules also stay indynamicModulesMetadata(for aDynamicModuledefinition) and inDiscoverableMetaHostCollection.Reproduced on master with a real express app over HTTP (
NestFactory+fetch). A route lazy loads a module whose "DB" is an async factory that throws on its first call. Same line on 3/3 runs:Issue Number: N/A
Steps to reproduce
npx vitest run packages/core/test/injector/lazy-module-loader/lazy-module-loader.spec.ts packages/core/test/injector/container.spec.ts -t "on the next load|discoverable entries"load()builds the module again and the provider gets'connection'What is the new behavior?
load()now runsscanModulesForDependenciesandcreateInstancesOfDependenciesin a try/catch. On a failure the catch removes the modules this call scanned and rethrows the original error, so the nextload()scans and builds them from scratch. The logger restore infinallyfrom #17631 is unchanged.The removal is one container method,
NestContainer.removeModules()next toclear(). The loader reaches it through a smallDependenciesScanner.removeModules()forwarder, since it already talks to the container through the scanner. Per module it deletes theModulesContainerentry, theglobalModulesanddynamicModulesMetadataentries, and the module's provider and controller wrappers inDiscoverableMetaHostCollection(newremoveInstanceWrappers(), matched by wrapper id the wayinsertByMetaKeydoes).What gets rebuilt and what doesn't:
load()scanForModulesreturns[]for a module that's already instantiated, so they never end up in the batchload()that succeeds behaves as beforeSame probe on this branch, 3/3:
Does this PR introduce a breaking change?
The public API only gains
NestContainer.removeModules,DependenciesScanner.removeModulesandDiscoverableMetaHostCollection.removeInstanceWrappers.Other information
Earlier fixes on the same loader: #17631 (logger restore in
load()'s finally), #17430 (share eager singletons with lazy modules), #17464 (scan imports pre-registered byaddDynamicMetadata) and #17667 (discovery of factory providers). This keeps #17631'sfinallyas it is and puts the rollback in a catch beside it, and the eager singletons from #17430 aren't touched.Validation on Node 22, Linux:
packages/common/test/services/logger.service.spec.tsunderNO_COLOR=1, same on bothcontainer.tsandlazy-module-loader.spec.ts, I left those as master has them