Skip to content

JavaScript heap out of memory after upgrading to 4.3 #44299

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
dagstuan opened this issue May 27, 2021 · 50 comments
Open

JavaScript heap out of memory after upgrading to 4.3 #44299

dagstuan opened this issue May 27, 2021 · 50 comments
Assignees
Labels
Needs Investigation This issue needs a team member to investigate its status. Rescheduled This issue was previously scheduled to an earlier milestone

Comments

@dagstuan
Copy link

Bug Report

🔎 Search Terms

Memory

🕗 Version & Regression Information

After upgrading to 4.3.2 I get a "JavaScript heap out of memory" exception when i try to run tsc. Downgrading to 4.2.4 does not yield the same error.

<--- Last few GCs --->

[43233:0x108008000]    75872 ms: Scavenge 2043.5 (2049.9) -> 2043.0 (2049.9) MB, 6.6 / 0.0 ms  (average mu = 0.119, current mu = 0.127) allocation failure 
[43233:0x108008000]    75927 ms: Scavenge 2043.8 (2049.9) -> 2043.3 (2050.2) MB, 6.5 / 0.0 ms  (average mu = 0.119, current mu = 0.127) allocation failure 
[43233:0x108008000]    75986 ms: Scavenge 2044.0 (2050.2) -> 2043.5 (2050.4) MB, 7.0 / 0.0 ms  (average mu = 0.119, current mu = 0.127) allocation failure 


<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 0x100930c99]
Security context: 0x390dbb3008a1 <JSObject>
    1: getIntersectionType(aka getIntersectionType) [0x390df5b65bb9] [/.../node_modules/typescript/lib/tsc.js:~47588] [pc=0x1a0124246ed4](this=0x390d982804a9 <undefined>,0x390d7a08df51 <JSArray[18]>,0x390d982804a9 <undefined>,0x390d982804a9 <undefined>)
    2: getCrossProductIntersections(aka getCrossProductIntersections) [0...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 0x10007e9b3 node::Abort() [/usr/local/bin/node]
 2: 0x10007eb37 node::OnFatalError(char const*, char const*) [/usr/local/bin/node]
 3: 0x100176337 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/usr/local/bin/node]
 4: 0x1001762d3 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/usr/local/bin/node]
 5: 0x1002fa485 v8::internal::Heap::FatalProcessOutOfMemory(char const*) [/usr/local/bin/node]
 6: 0x1002fbb54 v8::internal::Heap::RecomputeLimits(v8::internal::GarbageCollector) [/usr/local/bin/node]
 7: 0x1002f8a27 v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [/usr/local/bin/node]
 8: 0x1002f6a0d v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [/usr/local/bin/node]
 9: 0x1002f58c1 v8::internal::Heap::HandleGCRequest() [/usr/local/bin/node]
10: 0x1002bac3f v8::internal::StackGuard::HandleInterrupts() [/usr/local/bin/node]
11: 0x1005f7b6c v8::internal::Runtime_StackGuard(int, unsigned long*, v8::internal::Isolate*) [/usr/local/bin/node]
12: 0x100930c99 Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_NoBuiltinExit [/usr/local/bin/node]
13: 0x1a0124246ed4

🙁 Actual behavior

It crashed.

🙂 Expected behavior

No crash

@adam-thomas-privitar
Copy link

adam-thomas-privitar commented Jun 2, 2021

Almost (young object promotion failed Allocation failed) exact same issue. obviously must be something specific about our codebase, but verbose outputs nothing so I dont know where we go from here. Perhaps providing some kind of dump might be useful for someone?

Worth noting it happens after a very long time hanging.


<--- Last few GCs --->

[7184:0x110008000]   621386 ms: Mark-sweep (reduce) 4064.9 (4101.8) -> 4064.2 (4103.3) MB, 2424.6 / 0.0 ms  (average mu = 0.114, current mu = 0.018) allocation failure scavenge might not succeed
[7184:0x110008000]   624960 ms: Mark-sweep (reduce) 4065.3 (4102.3) -> 4064.5 (4103.5) MB, 3528.9 / 0.0 ms  (average mu = 0.056, current mu = 0.013) allocation failure scavenge might not succeed


<--- JS stacktrace --->

FATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap out of memory
 1: 0x1012d84c5 node::Abort() (.cold.1) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
 2: 0x1000a5d59 node::Abort() [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
 3: 0x1000a5ebf node::OnFatalError(char const*, char const*) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
 4: 0x1001e8007 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
 5: 0x1001e7fa3 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
 6: 0x100394ea5 v8::internal::Heap::FatalProcessOutOfMemory(char const*) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
 7: 0x1003f0e03 v8::internal::EvacuateNewSpaceVisitor::Visit(v8::internal::HeapObject, int) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
 8: 0x1003d866b void v8::internal::LiveObjectVisitor::VisitBlackObjectsNoFail<v8::internal::EvacuateNewSpaceVisitor, v8::internal::MajorNonAtomicMarkingState>(v8::internal::MemoryChunk*, v8::internal::MajorNonAtomicMarkingState*, v8::internal::EvacuateNewSpaceVisitor*, v8::internal::LiveObjectVisitor::IterationMode) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
 9: 0x1003d81b5 v8::internal::FullEvacuator::RawEvacuatePage(v8::internal::MemoryChunk*, long*) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
10: 0x1003d7ef6 v8::internal::Evacuator::EvacuatePage(v8::internal::MemoryChunk*) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
11: 0x1003f582e v8::internal::PageEvacuationTask::RunInParallel(v8::internal::ItemParallelJob::Task::Runner) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
12: 0x1003af8a2 v8::internal::ItemParallelJob::Task::RunInternal() [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
13: 0x1003afd28 v8::internal::ItemParallelJob::Run() [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
14: 0x1003d9f65 void v8::internal::MarkCompactCollectorBase::CreateAndExecuteEvacuationTasks<v8::internal::FullEvacuator, v8::internal::MarkCompactCollector>(v8::internal::MarkCompactCollector*, v8::internal::ItemParallelJob*, v8::internal::MigrationObserver*, long) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
15: 0x1003d9b66 v8::internal::MarkCompactCollector::EvacuatePagesInParallel() [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
16: 0x1003c5397 v8::internal::MarkCompactCollector::Evacuate() [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
17: 0x1003c2c2b v8::internal::MarkCompactCollector::CollectGarbage() [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
18: 0x10039556b v8::internal::Heap::MarkCompact() [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
19: 0x100391b59 v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
20: 0x10038f9a0 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
21: 0x10039e08a v8::internal::Heap::AllocateRawWithLightRetrySlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
22: 0x10039e111 v8::internal::Heap::AllocateRawWithRetryOrFailSlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
23: 0x10036c1e7 v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationType, v8::internal::AllocationOrigin) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
24: 0x1006eb078 v8::internal::Runtime_AllocateInYoungGeneration(int, unsigned long*, v8::internal::Isolate*) [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
25: 0x100a709b9 Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_NoBuiltinExit [/Users/adamthomas/.nvm/versions/node/v14.14.0/bin/node]
26: 0x2cb8704f923c ```

@brudil
Copy link

brudil commented Jun 2, 2021

We're experiencing this against both our front and backend applications which is interesting as they share little code. By any chance is anyone else here using Zod? It's perhaps the most type-complex library which we're using in both.

@adam-thomas-privitar
Copy link

@brudil Im using Zod too!

@mudit-gupta-privitar
Copy link

@brudil I am also using Zod!

@jraoult
Copy link

jraoult commented Jun 2, 2021

Interesting, using Zod here as well, 3.1.0 and I can't compile typecheck anything anymore since TS 4.3.2

@adam-thomas-privitar
Copy link

adam-thomas-privitar commented Jun 2, 2021

I setup a minimal test case like so:

import zod from 'zod'

export const SchemaExample = zod.object({
    name: zod.string().min(1),
    description: zod.string().min(1),
})
  
export type SchemaExampleType = zod.infer<typeof SchemaExample>

Interestingly, in the simple case, this causes "maximum depth" TS errors rather than a hang. I think when you have a lot of calls to zod.infer this triggers some infinite recursion/memory leak. Actually you dont need the infer even, or even the schema -- importing zod alone is enough. Not sure exactly how this might ultimately end up in hang when consumed a lot of times in a large codebase. Also not sure what changed in TS to make Zod incompatible.

Here are the errors:


node_modules/zod/lib/helpers/partialUtil.d.ts:5:42 - error TS2321: Excessive stack depth comparing types 'ZodError<?>' and 'ZodError<?>'.

5         object: T extends AnyZodObject ? ZodObject<{
                                           ~~~~~~~~~~~
6             [k in keyof T["_shape"]]: DeepPartial<T["_shape"][k]>;
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7         }, T["_unknownKeys"], T["_catchall"]> : never;
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/zod/lib/helpers/partialUtil.d.ts:5:42 - error TS2321: Excessive stack depth comparing types 'ZodFormattedError<?>' and 'ZodFormattedError<?>'.

5         object: T extends AnyZodObject ? ZodObject<{
                                           ~~~~~~~~~~~
6             [k in keyof T["_shape"]]: DeepPartial<T["_shape"][k]>;
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7         }, T["_unknownKeys"], T["_catchall"]> : never;
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/zod/lib/helpers/partialUtil.d.ts:5:42 - error TS2321: Excessive stack depth comparing types 'ZodIntersection<?, U>' and 'ZodIntersection<?, U>'.

5         object: T extends AnyZodObject ? ZodObject<{
                                           ~~~~~~~~~~~
6             [k in keyof T["_shape"]]: DeepPartial<T["_shape"][k]>;
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7         }, T["_unknownKeys"], T["_catchall"]> : never;
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/zod/lib/helpers/partialUtil.d.ts:5:42 - error TS2321: Excessive stack depth comparing types 'ZodIntersection<T, ?>' and 'ZodIntersection<T, ?>'.

5         object: T extends AnyZodObject ? ZodObject<{
                                           ~~~~~~~~~~~
6             [k in keyof T["_shape"]]: DeepPartial<T["_shape"][k]>;
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7         }, T["_unknownKeys"], T["_catchall"]> : never;
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/zod/lib/helpers/partialUtil.d.ts:5:42 - error TS2321: Excessive stack depth comparing types 'ZodNonEmptyArray<?>' and 'ZodNonEmptyArray<?>'.

5         object: T extends AnyZodObject ? ZodObject<{
                                           ~~~~~~~~~~~
6             [k in keyof T["_shape"]]: DeepPartial<T["_shape"][k]>;
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7         }, T["_unknownKeys"], T["_catchall"]> : never;
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/zod/lib/helpers/partialUtil.d.ts:5:42 - error TS2321: Excessive stack depth comparing types 'ZodOptional<?>' and 'ZodOptional<?>'.

5         object: T extends AnyZodObject ? ZodObject<{
                                           ~~~~~~~~~~~
6             [k in keyof T["_shape"]]: DeepPartial<T["_shape"][k]>;
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7         }, T["_unknownKeys"], T["_catchall"]> : never;
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/zod/lib/types.d.ts:60:168 - error TS2577: Return type annotation circularly references itself.

60     refine: <Func extends (arg: Output) => any, This extends this = this>(check: Func, message?: string | CustomErrorParams | ((arg: Output) => CustomErrorParams)) => ZodEffectsType<This>;
                                                                                                                                                                          ~~~~~~~~~~~~~~~~~~~~

node_modules/zod/lib/types.d.ts:61:162 - error TS2577: Return type annotation circularly references itself.

61     refinement: <This extends this = this>(check: (arg: Output) => any, refinementData: MakeErrorData | ((arg: Output, ctx: RefinementCtx) => MakeErrorData)) => ZodEffectsType<This>;
                                                                                                                                                                    ~~~~~~~~~~~~~~~~~~~~

node_modules/zod/lib/types.d.ts:62:86 - error TS2577: Return type annotation circularly references itself.

62     _refinement<This extends this>(refinement: InternalCheck<Output>["refinement"]): ZodEffectsType<This>;
                                                                                        ~~~~~~~~~~~~~~~~~~~~

node_modules/zod/lib/types.d.ts:63:90 - error TS2577: Return type annotation circularly references itself.

63     superRefine: <This extends this>(refinement: InternalCheck<Output>["refinement"]) => ZodEffectsType<This>;
                                                                                            ~~~~~~~~~~~~~~~~~~~~

node_modules/zod/lib/types.d.ts:69:68 - error TS2577: Return type annotation circularly references itself.

69     or<T extends ZodTypeAny, This extends this = this>(option: T): This extends ZodUnion<infer Opts> ? [...Opts, T] extends ZodUnionOptions ? ZodUnion<[...Opts, T]> : never : ZodUnion<[This, T]>;
                                                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/zod/lib/types.d.ts:71:97 - error TS2577: Return type annotation circularly references itself.

71     transform<NewOut, This extends this>(transform: (arg: Output) => NewOut | Promise<NewOut>): This extends ZodEffects<infer T, any> ? ZodEffects<T, NewOut> : ZodEffects<This, NewOut>;
                                                                                                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/zod/lib/types.d.ts:381:18 - error TS2321: Excessive stack depth comparing types 'ZodTuple<?>' and 'ZodTuple<?>'.

381 export interface ZodFunctionDef<Args extends ZodTuple<any> = ZodTuple<any>, Returns extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef {
                     ~~~~~~~~~~~~~~


Found 13 errors.

@dagstuan
Copy link
Author

dagstuan commented Jun 3, 2021

FWIW I'm not using Zod, but the codebase is quite large.

@adam-thomas-privitar
Copy link

Interesting. Perhaps its more t do with anything that uses recursive types.

karrui added a commit to opengovsg/FormSG that referenced this issue Jun 7, 2021
zod is incompatible with Typescript 4.3.x due a change in 4.3 for evaluating deep complex types.

Since we do not use any 4.3 features (yet), lock typescript package to 4.2 until this is fixed

see microsoft/TypeScript#43249, colinhacks/zod#443, colinhacks/zod#473, microsoft/TypeScript#44299
@RyanCavanaugh RyanCavanaugh added the Needs Investigation This issue needs a team member to investigate its status. label Jun 7, 2021
@RyanCavanaugh RyanCavanaugh added this to the TypeScript 4.4.0 (Beta) milestone Jun 7, 2021
@amcasey
Copy link
Member

amcasey commented Jun 8, 2021

I'm going to investigate Zod, since there's a repro. Hopefully, the underlying issue will turn out to be the same as @dagstuan's.

@amcasey
Copy link
Member

amcasey commented Jun 8, 2021

Introduced in #30639 (cc @weswigham). On the bright side, in that exact commit, the toy repro runs out of memory, so we've made improvements since then. 😄

@weswigham
Copy link
Member

Yeah, when we merged that we started exploring more types during relationship checking to test for compatibility which, for generatively expanding types, means manufacturing more types (before we hit somewhat arbitrary limiters) - in the intervening time, we've tightened up on some of those limiters/identities a bit, and that's generally how I've been going about "fixing" it - identify costly structures to compare, figure out how they're dodging our complexity limiters, and the update the complexity limiters to capture them.

@meadowsys
Copy link

meadowsys commented Jun 10, 2021

I'm getting similar error, and I have a (maybe) simpler repro:

import { object, string } from "zod";
const validator = object({
   _key: string()
});

That's enough to trigger the excessive stack depth error. My guess is that it has something to do with generic inference.

@amcasey
Copy link
Member

amcasey commented Jun 11, 2021

Okay, it took a while, but here's a toy repro with no imports.

export declare type ZodFormattedError<T> = T extends [any, ...any] ? {
    [K in keyof T]?: ZodFormattedError<T[K]>;
} & {
    _errors: string[];
} : T extends any[] ? ZodFormattedError<T[number]>[] & {
    _errors: string[];
} : T extends object ? {
    [K in keyof T]?: ZodFormattedError<T[K]>;
} & {
    _errors: string[];
} : {
    _errors: string[];
};
export declare class ZodError<T> {
    format: () => ZodFormattedError<T>;
}
declare const c1: ZodError<number>;
const c2: ZodError<string> = c1;

Personally, I find it easier to read like this:

type ZodFormattedError<T> = T extends [any, ...any] 
    ? { [K in keyof T]?: ZodFormattedError<T[K]>; } & { _errors: string[]; } 
    : T extends any[] 
        ? ZodFormattedError<T[number]>[] & { _errors: string[]; } 
        : T extends object 
            ? { [K in keyof T]?: ZodFormattedError<T[K]>; } & { _errors: string[]; } 
            : { _errors: string[]; };

interface ZodError<T> {
    format: () => ZodFormattedError<T>;
}
declare const c1: ZodError<number>;
const c2: ZodError<string> = c1;

@amcasey
Copy link
Member

amcasey commented Jun 11, 2021

Ooh, if you comment out these lines, it OOMs:

type ZodFormattedError<T> = T extends [any, ...any] 
    ? { [K in keyof T]?: ZodFormattedError<T[K]>; } & { _errors: string[]; } 
    : T extends any[] 
        ? ZodFormattedError<T[number]>[] & { _errors: string[]; } 
//      : T extends object 
//          ? { [K in keyof T]?: ZodFormattedError<T[K]>; } & { _errors: string[]; } 
            : { _errors: string[]; };

interface ZodError<T> {
    format: () => ZodFormattedError<T>;
}
declare const c1: ZodError<number>;
const c2: ZodError<string> = c1;

@amcasey
Copy link
Member

amcasey commented Jun 11, 2021

And pulling out the intersection with { _errors: string[]; } seems to mitigate the issue.

type ZodFormattedError<T> = { _errors: string[]; } & (T extends [any, ...any]
    ? { [K in keyof T]?: ZodFormattedError<T[K]>; }
    : T extends any[]
        ? ZodFormattedError<T[number]>[]
        : T extends object
            ? { [K in keyof T]?: ZodFormattedError<T[K]>; }
            : {});

(I think I got that right.)

@amcasey amcasey assigned weswigham and unassigned amcasey Jun 11, 2021
@amcasey
Copy link
Member

amcasey commented Jun 11, 2021

@weswigham Is there something smart we can do with the depth limit in the the toy repros? And does my mitigation look correct enough to submit as a PR to zod?

@meadowsys
Copy link

is this a zod problem or a ts problem? I feel like this might be more of a ts problem, because something changed in ts 4.3 that broke zod

@amcasey
Copy link
Member

amcasey commented Jun 11, 2021

@autumnblazey It's a TS problem, but a zod PR might help people until a new version of TS is released. Also, the proposed change to zod will likely make it faster even after the TS fix.

@EvHaus
Copy link

EvHaus commented Apr 11, 2022

@EvHaus Have you tried using performance tracing to isolate a repro?

Here's the output I got:

See trace analysis
$ tsc --noEmit --generateTrace tracing || yarn analyze-trace tracing

<--- Last few GCs --->

[28:0x5d9fb10]    62608 ms: Scavenge (reduce) 1020.8 (1041.2) -> 1020.2 (1041.2) MB, 4.3 / 0.0 ms  (average mu = 0.137, current mu = 0.007) allocation failure 
[28:0x5d9fb10]    62617 ms: Scavenge (reduce) 1020.8 (1041.2) -> 1020.2 (1041.4) MB, 3.1 / 0.0 ms  (average mu = 0.137, current mu = 0.007) allocation failure 
[28:0x5d9fb10]    63840 ms: Mark-sweep (reduce) 1021.1 (1041.4) -> 1020.0 (1041.7) MB, 1218.5 / 0.0 ms  (average mu = 0.113, current mu = 0.086) allocation failure scavenge might not succeed


<--- JS stacktrace --->

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 0xb09980 node::Abort() [/usr/local/bin/node]
 2: 0xa1c235 node::FatalError(char const*, char const*) [/usr/local/bin/node]
 3: 0xcf784e v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/usr/local/bin/node]
 4: 0xcf7bc7 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/usr/local/bin/node]
 5: 0xeaf465  [/usr/local/bin/node]
 6: 0xeaff46  [/usr/local/bin/node]
 7: 0xebe46e  [/usr/local/bin/node]
 8: 0xebeeb0 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [/usr/local/bin/node]
 9: 0xec1e2e v8::internal::Heap::AllocateRawWithRetryOrFailSlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [/usr/local/bin/node]
10: 0xe8336a v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationType, v8::internal::AllocationOrigin) [/usr/local/bin/node]
11: 0x11fc0b6 v8::internal::Runtime_AllocateInYoungGeneration(int, unsigned long*, v8::internal::Isolate*) [/usr/local/bin/node]
12: 0x15f0b19  [/usr/local/bin/node]
Aborted (core dumped)

$ /srv/node_modules/.bin/analyze-trace tracing
Trace ended unexpectedly
> checkSourceFile: {"path":"/srv/client/node_modules/@babel/types/lib/index.d.ts"}

Hot Spots
├─ Check file /srv/client/node_modules/@babel/types/lib/index.d.ts (18168ms)
│  ├─ Compare types 316395 and 315095 (17137ms)
│  │  └─ Compare types 318628 and 315095 (16964ms)
│  │     ├─ Compare types 318625 and 315095 (2515ms)
│  │     ├─ Compare types 318622 and 315095 (1430ms)
│  │     ├─ Compare types 318627 and 315095 (1[286](https://github.com/myrepo/runs/5957928826?check_suite_focus=true#step:2:286)ms)
│  │     │  └─ Compare types 318627 and 314202 (1219ms)
│  │     ├─ Compare types 318501 and 315095 (699ms)
│  │     └─ Compare types 318597 and 315095 (589ms)
│  │        └─ Compare types 318597 and 314048 (393ms)
│  │           └─ Compare types 316618 and 314048 (392ms)
│  │              └─ Compare types 317[307](https://github.com/myrepo/runs/5957928826?check_suite_focus=true#step:2:307) and [314](https://github.com/myrepo/runs/5957928826?check_suite_focus=true#step:2:314)048 (392ms)
│  └─ Compare types [315](https://github.com/myrepo/runs/5957928826?check_suite_focus=true#step:2:315)391 and 315095 (881ms)
├─ Check file /srv/packages/kraken-markdown/src/plugins/remark-github-emoji.ts (2148ms)
│  └─ Check deferred node from (line 36, char 10) to (line 88, char 4) (2134ms)
│     └─ Check expression from (line 37, char 5) to (line 87, char 7) (2134ms)
├─ Check file /srv/node_modules/@types/react/index.d.ts (1452ms)
│  └─ Compare types 10850 and 10860 (574ms)
│     └─ Compare types 11081 and 10860 (392ms)
├─ Check file /srv/node_modules/@emotion/serialize/types/index.d.ts (1431ms)
└─ Check file /srv/node_modules/csstype/index.d.ts (678ms)

Duplicate packages
├─ @types/express-serve-static-core
│  ├─ Version 4.17.28 from /srv/node_modules/@types/express-serve-static-core
│  └─ Version 4.17.26 from /srv/node_modules/@types/express/node_modules/@types/express-serve-static-core
├─ @types/history
│  ├─ Version 4.7.11 from /srv/node_modules/@types/history
│  └─ Version 4.7.9 from /srv/node_modules/@types/react-router-dom/node_modules/@types/react-router/node_modules/@types/history
└─ csstype
   ├─ Version 2.6.19 from /srv/node_modules/@emotion/serialize/node_modules/csstype
   └─ Version 3.0.10 from /srv/node_modules/csstype

@amcasey
Copy link
Member

amcasey commented Apr 11, 2022

@EvHaus If it were me, I'd try to eliminate that version mismatch for csstype. Those types can get pretty big and forcing the compiler to compare similar types structurally is a recipe for problems.

Without the corresponding types file, it's hard to be more specific about which types/packages are causing slowdowns. (I'm not sure why you didn't get that output - maybe it gets skipped if the trace is incomplete.) You can use the print-trace-types script to pretty-print them after the fact.

@mtt87
Copy link

mtt87 commented Apr 12, 2022

My issue (slowness with CSS types) doesn't happen with latest 4.7 beta npm i typescript@beta 👀

@EvHaus
Copy link

EvHaus commented Apr 14, 2022

Unfortunately removing the duplicate csstype didn't help, but now I'm getting new details in the tracing:

See trace analysis
$ tsc --noEmit --generateTrace tracing || yarn analyze-trace tracing

<--- Last few GCs --->

[28:0x4f4fb10]    64621 ms: Mark-sweep (reduce) 1020.9 (1041.7) -> 1020.0 (1041.7) MB, 1303.9 / 0.0 ms  (average mu = 0.115, current mu = 0.007) allocation failure scavenge might not succeed
[28:0x4f4fb10]    66002 ms: Mark-sweep (reduce) 1021.3 (1041.7) -> 1020.0 (1041.7) MB, 1320.4 / 0.0 ms  (average mu = 0.079, current mu = 0.044) allocation failure scavenge might not succeed


<--- JS stacktrace --->

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 0xb09980 node::Abort() [/usr/local/bin/node]
 2: 0xa1c235 node::FatalError(char const*, char const*) [/usr/local/bin/node]
 3: 0xcf784e v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/usr/local/bin/node]
 4: 0xcf7bc7 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/usr/local/bin/node]
 5: 0xeaf465  [/usr/local/bin/node]
 6: 0xeaff46  [/usr/local/bin/node]
 7: 0xebe46e  [/usr/local/bin/node]
 8: 0xebeeb0 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [/usr/local/bin/node]
 9: 0xec1e2e v8::internal::Heap::AllocateRawWithRetryOrFailSlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [/usr/local/bin/node]
10: 0xe830a2 v8::internal::Factory::AllocateRaw(int, v8::internal::AllocationType, v8::internal::AllocationAlignment) [/usr/local/bin/node]
11: 0xe7d9bc v8::internal::FactoryBase<v8::internal::Factory>::AllocateRawArray(int, v8::internal::AllocationType) [/usr/local/bin/node]
12: 0xe7da95 v8::internal::FactoryBase<v8::internal::Factory>::NewFixedArrayWithFiller(v8::internal::Handle<v8::internal::Map>, int, v8::internal::Handle<v8::internal::Oddball>, v8::internal::AllocationType) [/usr/local/bin/node]
13: 0x10e631e v8::internal::MaybeHandle<v8::internal::OrderedHashMap> v8::internal::OrderedHashTable<v8::internal::OrderedHashMap, 2>::Allocate<v8::internal::Isolate>(v8::internal::Isolate*, int, v8::internal::AllocationType) [/usr/local/bin/node]
14: 0x10e63d3 v8::internal::MaybeHandle<v8::internal::OrderedHashMap> v8::internal::OrderedHashTable<v8::internal::OrderedHashMap, 2>::Rehash<v8::internal::Isolate>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::OrderedHashMap>, int) [/usr/local/bin/node]
15: 0x11f24e5 v8::internal::Runtime_MapGrow(int, unsigned long*, v8::internal::Isolate*) [/usr/local/bin/node]
16: 0x15f0b19  [/usr/local/bin/node]
Aborted (core dumped)

$ /srv/node_modules/.bin/analyze-trace tracing
Trace ended unexpectedly
> checkSourceFile: {"path":"/srv/node_modules/@babel/types/lib/index.d.ts"}

Hot Spots
├─ Check file /srv/node_modules/@babel/types/lib/index.d.ts (16210ms)
│  ├─ Compare types 335994 and 332482 (2569ms)
│  │  └─ Compare types 335994 and 331395 (1304ms)
│  ├─ Compare types 335989 and 332482 (1434ms)
│  ├─ Compare types 335976 and 332482 (877ms)
│  ├─ Compare types 33[277](https://github.com/myrepo/runs/6030330434?check_suite_focus=true#step:2:277)9 and 332482 (821ms)
│  └─ Compare types 335902 and 332482 (522ms)
├─ Check file /srv/node_modules/@emotion/serialize/types/index.d.ts (2475ms)
├─ Check file /srv/packages/kraken-markdown/src/plugins/remark-github-emoji.ts (2067ms)
│  └─ Check deferred node from (line 36, char 10) to (line 88, char 4) (2053ms)
│     └─ Check expression from (line 37, char 5) to (line 87, char 7) (2053ms)
└─ Check file /srv/node_modules/@types/react/index.d.ts (1680ms)
   └─ Compare types 10878 and 10888 (780ms)
      └─ Compare types 11109 and 10888 (506ms)

No duplicate packages found

@amcasey
Copy link
Member

amcasey commented Apr 15, 2022

@EvHaus That's a very long time to spend checking the babel types and I'd be interested to know which version you're on. Having said that, it seems like there's little benefit in checking them yourself, so I'd probably build with skipLibCheck.

@EvHaus
Copy link

EvHaus commented Apr 26, 2022

@amcasey We're using @babel/types version 7.17.0 and I've ensured the package is deduplicated. I tried with skipLibCheck and that fixed the issue 🎉. Looking at the docs for the skipLibCheck makes me a bit nervous about turning it off. Are we going to lose some type safety as a result of disabling it?

Any ideas what could have changed between 4.5 and 4.6 that could explain this problem? I'm trying to evaluate if it's better to stick to 4.5 or to move to 4.6 with skipLibCheck on.

@amcasey
Copy link
Member

amcasey commented Apr 27, 2022

@EvHaus skipLibCheck can alert you to conflicts between your dependencies, but I generally turn it off myself, since it doesn't find problems in the code I'm working on. If you're concerned, you can try skipping the checks locally and running them in CI.

Notable exception: If you hand-author .d.ts files, you probably do not want skipLibCheck.

Without knowing the specifics, my guess would be that 4.6 does more checking (i.e. catches more bugs) than 4.5 in a way that affects one or more of your dependencies. If you can share an example, I can look for a more specific explanation. If your code isn't available, it's usually possible to isolate a repro using analyze-trace, though that's obviously more work.

@EvHaus
Copy link

EvHaus commented Aug 26, 2022

Not sure what you guys did, but typescript@4.8.2 fixed my memory issues. No more OOM failures, and in general I'm seeing TypeScript running MUCH faster. Nice work! 🎉

@abenhamdine
Copy link

abenhamdine commented Dec 18, 2022

Also experiencing this with typescript@4.9.4, after switching my machine from a MacBookPro 2019 (16 Go), to a Windows 11 PC (16 Go also) (nothing else changed : same code base, same command, etc).
We don't use Zod but we have a very large codebase.
We were surprised because it's the first time we see an OOM error with tsc, in 5 years.

@cullylarson
Copy link

cullylarson commented Mar 7, 2023

I'm seeing this with:

  • typescript: 4.9.4
  • zod: 3.21.4

Downgrading to zod: 3.21.2 resolves the issue. Upgrading to typescript: 4.9.5 doesn't make a difference.

@joao-moonward
Copy link

joao-moonward commented Mar 10, 2023

Hello, everyone! I'm getting the same error.
I had a legacy project and just started changing some js files to Typescript.
My tsconfig:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": true,
    "noImplicitAny": true,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false,
    "noUncheckedIndexedAccess": true,
    "allowJs": true,
    "outDir": "./dist",
    "checkJs": false,
  },
}

In my Mac mini (Monterey, M1 2020, 8GB). When I started the build process, I realised the node consumption exceeded 100% CPU usage.

PID    COMMAND      %CPU  TIME     #TH    #WQ  #PORT MEM    PURG
20928  node         160.0 00:04.77 7/1    0    18    740M+  0B

It builds with success, though. Otherwise, in my EC2 instance (Ubuntu 22.04.1 LTS, Intel(R) Xeon(R) CPU E5-2676 v3 @ 2.40GHz) shows me this error:

<--- Last few GCs --->

[1173:0x6634210]    15930 ms: Mark-sweep (reduce) 481.4 (493.8) -> 481.1 (491.0) MB, 440.3 / 0.0 ms  (+ 3.7 ms in 4 steps since start of marking, biggest step 1.7 ms, walltime since start of marking 457 ms) (average mu = 0.283, current mu = 0.279) finaliz[1173:0x6634210]    16090 ms: Scavenge (reduce) 482.2 (491.0) -> 481.4 (491.0) MB, 7.7 / 0.0 ms  (average mu = 0.283, current mu = 0.279) allocation failure; 


<--- JS stacktrace --->

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 0xbbf330 node::Abort() [node]
 2: 0xad464e  [node]
 3: 0xda4320 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, v8::OOMDetails const&) [node]
 4: 0xda46d6 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, v8::OOMDetails const&) [node]
 5: 0xfa1b65  [node]
 6: 0xfa2116 v8::internal::Heap::RecomputeLimits(v8::internal::GarbageCollector) [node]
 7: 0xfb371d  [node]
 8: 0xfb4235 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node]
 9: 0xfb69d8 v8::internal::Heap::HandleGCRequest() [node]
10: 0xf306f7 v8::internal::StackGuard::HandleInterrupts() [node]
11: 0x137441f v8::internal::Runtime_StackGuardWithGap(int, unsigned long*, v8::internal::Isolate*) [node]
12: 0x17fb2f9  [node]
Aborted (core dumped)
    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND                                                                   
   1933 ubuntu    20   0  790632 234228  29876 R  93.7  23.7   0:03.81 node             

I tried to increase the --max_old_space_size, but it seems stuck.
Node version: v14.21.3

I tried typescript version 4.2.4 and the latest, 4.9.5.

Am I doing something wrong?

@pascalporedda
Copy link

Hello, everyone! I'm getting the same error. I had a legacy project and just started changing some js files to Typescript. My tsconfig:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": true,
    "noImplicitAny": true,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false,
    "noUncheckedIndexedAccess": true,
    "allowJs": true,
    "outDir": "./dist",
    "checkJs": false,
  },
}

In my Mac mini (Monterey, M1 2020, 8GB). When I started the build process, I realised the node consumption exceeded 100% CPU usage.

PID    COMMAND      %CPU  TIME     #TH    #WQ  #PORT MEM    PURG
20928  node         160.0 00:04.77 7/1    0    18    740M+  0B

It builds with success, though. Otherwise, in my EC2 instance (Ubuntu 22.04.1 LTS, Intel(R) Xeon(R) CPU E5-2676 v3 @ 2.40GHz) shows me this error:

<--- Last few GCs --->

[1173:0x6634210]    15930 ms: Mark-sweep (reduce) 481.4 (493.8) -> 481.1 (491.0) MB, 440.3 / 0.0 ms  (+ 3.7 ms in 4 steps since start of marking, biggest step 1.7 ms, walltime since start of marking 457 ms) (average mu = 0.283, current mu = 0.279) finaliz[1173:0x6634210]    16090 ms: Scavenge (reduce) 482.2 (491.0) -> 481.4 (491.0) MB, 7.7 / 0.0 ms  (average mu = 0.283, current mu = 0.279) allocation failure; 


<--- JS stacktrace --->

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 0xbbf330 node::Abort() [node]
 2: 0xad464e  [node]
 3: 0xda4320 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, v8::OOMDetails const&) [node]
 4: 0xda46d6 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, v8::OOMDetails const&) [node]
 5: 0xfa1b65  [node]
 6: 0xfa2116 v8::internal::Heap::RecomputeLimits(v8::internal::GarbageCollector) [node]
 7: 0xfb371d  [node]
 8: 0xfb4235 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node]
 9: 0xfb69d8 v8::internal::Heap::HandleGCRequest() [node]
10: 0xf306f7 v8::internal::StackGuard::HandleInterrupts() [node]
11: 0x137441f v8::internal::Runtime_StackGuardWithGap(int, unsigned long*, v8::internal::Isolate*) [node]
12: 0x17fb2f9  [node]
Aborted (core dumped)
    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND                                                                   
   1933 ubuntu    20   0  790632 234228  29876 R  93.7  23.7   0:03.81 node             

I tried to increase the --max_old_space_size, but it seems stuck. Node version: v14.21.3

I tried typescript version 4.2.4 and the latest, 4.9.5.

Am I doing something wrong?

Experiencing the same here on my MBP with M2 Pro.

@armtuk
Copy link

armtuk commented Mar 14, 2023

Having this (or similar) issue with zod 3.20.6 and typescript 4.8.2

@karlhorky
Copy link
Contributor

I guess there's another issue about JavaScript heap out of memory errors over here (about 4.9.3):

@stephenasuncionDEV
Copy link

Still getting this issue. I'm getting the following error:

FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory

when running tsc --pretty --noEmit even if I set the space size like the following:

cross-env NODE_OPTIONS=--max-old-space-size=10240 tsc --pretty --noEmit

@LironHazan
Copy link

I've also had an issue with moving to typescript ~5.1 (or even ~5.0 TBH) in a React components library (it uses mui),
Here's how I resolved the TS2590: Expression produces a union type that is too complex to represent error:

tsx files:

// Changed
<StyledChip variant={variant} {...otherProps}>
// To
<StyledChip
    variant={variant as TChipVariants}
    {...(otherProps as React.HTMLAttributes<HTMLDivElement>)}
>

And

// Changed
{...otherProps}
// To
const { sx, ...restProps } = otherProps
...
<StyledRadioGroup {...restProps} >

But had to increase max-old-space-size dramatically to 16384 in order to get the relevant errors..
I hope it helps anyone..

@deannabosschert
Copy link

If anyone needs a quick/temp fix: downgrading to 4.2.4 fixed the problem for me.

@earthjan
Copy link

earthjan commented Oct 1, 2024

Using MUI (I'm using MUI v5.14.16) may give the heap-out-of-memory error. Upgrading the TS to 4.2.4 [reference] solves the problem if I continue using the SxProps of MUI. (After playing with setting the heap, tried upgrading to the latest TS version, but no luck.)

I have a util type CreateComponentProps that's used when creating a component prop type, and it's used throughout my React codebase. After adding the SxProps from MUI, I'm encountering the heap error, so I tried to remove it just to check if it's the root cause, and it is.

This may also seem related to the issue when using Zod.

export type CreateComponentProps<T = {}> = T & ComponentTestKit & MuiBaseComponent;
export interface MuiBaseComponent {
  className?: string;
  sx?: SxProps;
}

Environment

  • TypeScript: 5.2.2
  • React: v18.2.0
  • MUI: v5.14.16

@guiyom-e
Copy link

I'm seeing this with:

* `typescript: 4.9.4`

* `zod: 3.21.4`

Downgrading to zod: 3.21.2 resolves the issue. Upgrading to typescript: 4.9.5 doesn't make a difference.

Same kind of issue with typescript: 5.7.2 and zod: 3.22.2.
Upgrading Zod to 3.24.1 fixed the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Needs Investigation This issue needs a team member to investigate its status. Rescheduled This issue was previously scheduled to an earlier milestone
Projects
None yet
Development

No branches or pull requests