Skip to content

Commit 5dc1f03

Browse files
committed
fix: resolve benchmark cold start OOM by resetting DFA cache
1 parent 3f21f2c commit 5dc1f03

5 files changed

Lines changed: 66 additions & 24 deletions

File tree

‎benchmark/sqlBenchmark.ts‎

Lines changed: 15 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -110,35 +110,30 @@ class SqlBenchmark {
110110

111111
private _lastResultsCache: BenchmarkResult[] | null = null;
112112

113+
private _parserConstructor: (new () => BasicSQL) | null = null;
114+
113115
/**
114116
* Returns SqlParser instance of specific language.
115117
*/
116118
getSqlParser(): BasicSQL {
119+
if (!this._parserConstructor) {
120+
this._parserConstructor = require(path.resolve(`src/parser/${this.language}/index.ts`))[
121+
languageNameMap[this.language]
122+
];
123+
}
124+
const parser = new this._parserConstructor();
117125
if (!this.isHot) {
118-
this.clearATNCache();
126+
parser.resetDfaCache();
119127
}
120-
const Parser = require(path.resolve(`src/parser/${this.language}/index.ts`))[
121-
languageNameMap[this.language]
122-
];
123-
return new Parser();
128+
return parser;
124129
}
125130

126131
/**
127-
* Due to the presence of ATN cache in antlr4, we will clear the module cache to ensure that each parser is brand new and with no cache.
132+
* Reset the shared DFA caches before collecting hot-start samples.
128133
*/
129-
clearATNCache() {
130-
const caches = Object.keys(require.cache);
131-
const sourcePath = path.join(__dirname, '../src');
132-
caches
133-
.filter((cache) => cache.includes(sourcePath))
134-
.forEach((moduleName) => {
135-
const module = require.cache[moduleName]!;
136-
// Fix Memory Leak
137-
if (module.parent) {
138-
module.parent.children = [];
139-
}
140-
delete require.cache[moduleName];
141-
});
134+
resetDfaCache() {
135+
const parser = this.getSqlParser();
136+
parser.resetDfaCache();
142137
}
143138

144139
getColumns = () => {
@@ -166,7 +161,7 @@ class SqlBenchmark {
166161
this._lastResultsCache?.find((item) => item.type === type && item.name === name) ?? {};
167162

168163
if (this.isHot) {
169-
this.clearATNCache();
164+
this.resetDfaCache();
170165
}
171166

172167
if (this.isHot && loopTimes < 2) {

‎package.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,14 @@
2929
"build": "rm -rf dist && tsc",
3030
"watch": "tsc -w",
3131
"check-types": "tsc -p ./tsconfig.json && tsc -p ./test/tsconfig.json",
32-
"test": "NODE_OPTIONS=--max_old_space_size=4096 && jest",
32+
"test": "NODE_OPTIONS=--max_old_space_size=4096 jest",
3333
"release": "node ./scripts/release.js",
3434
"prettier-check": "prettier --check .",
3535
"format": "prettier --write .",
3636
"format-g4": "antlr-format -c ./antlr.format.json -v ./src/grammar/**/*.g4",
3737
"cleanComment": "node ./scripts/cleanCommentCli.js",
38-
"benchmark": "NODE_OPTIONS=--max_old_space_size=4096 && node --no-warnings ./scripts/benchmark.js",
39-
"benchmark:release": "node --no-warnings ./scripts/benchmark.js --release"
38+
"benchmark": "NODE_OPTIONS=--max_old_space_size=4096 node --no-warnings ./scripts/benchmark.js",
39+
"benchmark:release": "NODE_OPTIONS=--max_old_space_size=4096 node --no-warnings ./scripts/benchmark.js --release"
4040
},
4141
"license": "MIT",
4242
"dependencies": {

‎scripts/benchmark.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
process.env.NODE_OPTIONS = process.env.NODE_OPTIONS || '--max_old_space_size=4096';
12
const path = require('path');
23
const spawn = require('child_process').spawn;
34
const fs = require('fs');
@@ -108,7 +109,7 @@ function main() {
108109
if (argv.lang) {
109110
const supportedLanguage = languages.some((language) => language === argv.lang);
110111
if (supportedLanguage || argv.lang === 'All Languages') {
111-
runBenchmark(argv.lang);
112+
runBenchmark(argv.lang, argv.hot ? 'hot' : 'cold');
112113
} else {
113114
console.error(
114115
chalk.bold.red('\n[Invalid language]:'),

‎src/parser/common/basicSQL.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,22 @@ export abstract class BasicSQL<
270270
return this._parseTree;
271271
}
272272

273+
/**
274+
* Reset the shared Lexer and Parser DFA caches for cold-start benchmarks.
275+
* This affects every parser instance of the same dialect.
276+
*/
277+
public resetDfaCache(): void {
278+
if (!this._parser || !this._lexer) {
279+
this.createParserWithCache('');
280+
}
281+
this._parser.interpreter.clearDFA();
282+
this._lexer.interpreter.clearDFA();
283+
this._parseTree = null;
284+
this._parsedInput = '';
285+
this._parseErrors = [];
286+
this._statementStartTokenTypes = null;
287+
}
288+
273289
/**
274290
* Validate input string and return syntax errors if exists.
275291
* When input contains multiple statements separated by semicolons

‎test/common/basicSQL.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@ import { FlinkSqlLexer } from 'src/lib/flink/FlinkSqlLexer';
33
import { ErrorListener } from 'src/parser/common/parseErrorListener';
44
import { CommonTokenStream } from 'antlr4ng';
55

6+
type DfaInterpreter = { decisionToDFA: Array<{ states: { length: number } }> };
7+
8+
const countDfaStates = (interpreter: DfaInterpreter) =>
9+
interpreter.decisionToDFA.reduce((count, dfa) => count + dfa.states.length, 0);
10+
611
describe('BasicSQL unit tests', () => {
712
const flink = new FlinkSQL();
813
test('Create lexer', () => {
@@ -81,6 +86,31 @@ describe('BasicSQL unit tests', () => {
8186
expect(errors.length).not.toBe(0);
8287
});
8388

89+
test('Reset shared DFA caches and reparse the same input', () => {
90+
const parser = new FlinkSQL();
91+
const sql = 'SELECT a, b FROM tbl1 WHERE a = 1 ORDER BY b';
92+
93+
expect(parser.validate(sql)).toHaveLength(0);
94+
95+
const parserInternals = parser as unknown as {
96+
_lexer: { interpreter: DfaInterpreter };
97+
_parser: { interpreter: DfaInterpreter };
98+
};
99+
100+
expect(countDfaStates(parserInternals._lexer.interpreter)).toBeGreaterThan(0);
101+
expect(countDfaStates(parserInternals._parser.interpreter)).toBeGreaterThan(0);
102+
103+
parser.resetDfaCache();
104+
105+
expect(countDfaStates(parserInternals._lexer.interpreter)).toBe(0);
106+
expect(countDfaStates(parserInternals._parser.interpreter)).toBe(0);
107+
expect(parser.getParsedInput()).toBe('');
108+
109+
expect(parser.validate(sql)).toHaveLength(0);
110+
expect(countDfaStates(parserInternals._lexer.interpreter)).toBeGreaterThan(0);
111+
expect(countDfaStates(parserInternals._parser.interpreter)).toBeGreaterThan(0);
112+
});
113+
84114
test('Get All tokens', () => {
85115
const sql = 'SELECT * FROM tbl1;';
86116
const tokens = flink.getAllTokens(sql);

0 commit comments

Comments
 (0)