diff --git a/.github/workflows/ci-performance.yml b/.github/workflows/ci-performance.yml index b080b668aa..c9cb055e13 100644 --- a/.github/workflows/ci-performance.yml +++ b/.github/workflows/ci-performance.yml @@ -70,7 +70,7 @@ jobs: env: NODE_ENV: production run: | - echo "Running baseline benchmarks with CPU affinity (using PR's benchmark script)..." + echo "Running baseline benchmarks..." if [ ! -f "benchmark/performance.js" ]; then echo "⚠️ Benchmark script not found - this is expected for new features" echo "Skipping baseline benchmark" @@ -135,7 +135,7 @@ jobs: env: NODE_ENV: production run: | - echo "Running PR benchmarks with CPU affinity..." + echo "Running PR benchmarks..." taskset -c 0 npm run benchmark > pr-output.txt 2>&1 || npm run benchmark > pr-output.txt 2>&1 || true echo "Benchmark command completed with exit code: $?" echo "Output file size: $(wc -c < pr-output.txt) bytes" diff --git a/benchmark/performance.js b/benchmark/performance.js index 64aa016df3..93ec6e3501 100644 --- a/benchmark/performance.js +++ b/benchmark/performance.js @@ -10,6 +10,7 @@ /* eslint-disable no-console */ +const core = require('@actions/core'); const Parse = require('parse/node'); const { performance, PerformanceObserver } = require('perf_hooks'); const { MongoClient } = require('mongodb'); @@ -20,11 +21,16 @@ const SERVER_URL = 'http://localhost:1337/parse'; const APP_ID = 'benchmark-app-id'; const MASTER_KEY = 'benchmark-master-key'; const ITERATIONS = parseInt(process.env.BENCHMARK_ITERATIONS || '1000', 10); +const LOG_ITERATIONS = false; // Parse Server instance let parseServer; let mongoClient; +// Logging helpers +const logInfo = message => core.info(message); +const logError = message => core.error(message); + /** * Initialize Parse Server for benchmarking */ @@ -87,26 +93,56 @@ async function cleanupDatabase() { } /** - * Measure average time for an async operation over multiple iterations - * Uses warmup iterations, median metric, and outlier filtering for robustness + * Reset Parse SDK to use the default server + */ +function resetParseServer() { + Parse.serverURL = SERVER_URL; +} + +/** + * Measure average time for an async operation over multiple iterations. + * @param {Object} options - Measurement options + * @param {string} options.name - Name of the operation being measured + * @param {Function} options.operation - Async function to measure + * @param {number} [options.iterations=ITERATIONS] - Number of iterations to run + * @param {boolean} [options.skipWarmup=false] - Skip warmup phase */ -async function measureOperation(name, operation, iterations = ITERATIONS) { - const warmupCount = Math.floor(iterations * 0.2); // 20% warmup iterations +async function measureOperation({ name, operation, iterations = ITERATIONS, skipWarmup = false }) { + const warmupCount = skipWarmup ? 0 : Math.floor(iterations * 0.2); const times = []; - // Warmup phase - stabilize JIT compilation and caches - for (let i = 0; i < warmupCount; i++) { - await operation(); + if (warmupCount > 0) { + logInfo(`Starting warmup phase of ${warmupCount} iterations...`); + const warmupStart = performance.now(); + for (let i = 0; i < warmupCount; i++) { + await operation(); + } + logInfo(`Warmup took: ${(performance.now() - warmupStart).toFixed(2)}ms`); } // Measurement phase + logInfo(`Starting measurement phase of ${iterations} iterations...`); + const progressInterval = Math.ceil(iterations / 10); // Log every 10% + const measurementStart = performance.now(); + for (let i = 0; i < iterations; i++) { const start = performance.now(); await operation(); const end = performance.now(); - times.push(end - start); + const duration = end - start; + times.push(duration); + + // Log progress every 10% or individual iterations if LOG_ITERATIONS is enabled + if (LOG_ITERATIONS) { + logInfo(`Iteration ${i + 1}: ${duration.toFixed(2)}ms`); + } else if ((i + 1) % progressInterval === 0 || i + 1 === iterations) { + const progress = Math.round(((i + 1) / iterations) * 100); + logInfo(`Progress: ${progress}%`); + } } + logInfo(`Measurement took: ${(performance.now() - measurementStart).toFixed(2)}ms`); + // Sort times for percentile calculations times.sort((a, b) => a - b); @@ -143,13 +179,16 @@ async function measureOperation(name, operation, iterations = ITERATIONS) { async function benchmarkObjectCreate() { let counter = 0; - return measureOperation('Object Create', async () => { - const TestObject = Parse.Object.extend('BenchmarkTest'); - const obj = new TestObject(); - obj.set('testField', `test-value-${counter++}`); - obj.set('number', counter); - obj.set('boolean', true); - await obj.save(); + return measureOperation({ + name: 'Object Create', + operation: async () => { + const TestObject = Parse.Object.extend('BenchmarkTest'); + const obj = new TestObject(); + obj.set('testField', `test-value-${counter++}`); + obj.set('number', counter); + obj.set('boolean', true); + await obj.save(); + }, }); } @@ -171,9 +210,12 @@ async function benchmarkObjectRead() { let counter = 0; - return measureOperation('Object Read', async () => { - const query = new Parse.Query('BenchmarkTest'); - await query.get(objects[counter++ % objects.length].id); + return measureOperation({ + name: 'Object Read', + operation: async () => { + const query = new Parse.Query('BenchmarkTest'); + await query.get(objects[counter++ % objects.length].id); + }, }); } @@ -196,11 +238,14 @@ async function benchmarkObjectUpdate() { let counter = 0; - return measureOperation('Object Update', async () => { - const obj = objects[counter++ % objects.length]; - obj.increment('counter'); - obj.set('lastUpdated', new Date()); - await obj.save(); + return measureOperation({ + name: 'Object Update', + operation: async () => { + const obj = objects[counter++ % objects.length]; + obj.increment('counter'); + obj.set('lastUpdated', new Date()); + await obj.save(); + }, }); } @@ -223,10 +268,13 @@ async function benchmarkSimpleQuery() { let counter = 0; - return measureOperation('Simple Query', async () => { - const query = new Parse.Query('BenchmarkTest'); - query.equalTo('category', counter++ % 10); - await query.find(); + return measureOperation({ + name: 'Simple Query', + operation: async () => { + const query = new Parse.Query('BenchmarkTest'); + query.equalTo('category', counter++ % 10); + await query.find(); + }, }); } @@ -236,18 +284,21 @@ async function benchmarkSimpleQuery() { async function benchmarkBatchSave() { const BATCH_SIZE = 10; - return measureOperation('Batch Save (10 objects)', async () => { - const TestObject = Parse.Object.extend('BenchmarkTest'); - const objects = []; - - for (let i = 0; i < BATCH_SIZE; i++) { - const obj = new TestObject(); - obj.set('batchField', `batch-${i}`); - obj.set('timestamp', new Date()); - objects.push(obj); - } + return measureOperation({ + name: 'Batch Save (10 objects)', + operation: async () => { + const TestObject = Parse.Object.extend('BenchmarkTest'); + const objects = []; + + for (let i = 0; i < BATCH_SIZE; i++) { + const obj = new TestObject(); + obj.set('batchField', `batch-${i}`); + obj.set('timestamp', new Date()); + objects.push(obj); + } - await Parse.Object.saveAll(objects); + await Parse.Object.saveAll(objects); + }, }); } @@ -257,13 +308,16 @@ async function benchmarkBatchSave() { async function benchmarkUserSignup() { let counter = 0; - return measureOperation('User Signup', async () => { - counter++; - const user = new Parse.User(); - user.set('username', `benchmark_user_${Date.now()}_${counter}`); - user.set('password', 'benchmark_password'); - user.set('email', `benchmark${counter}@example.com`); - await user.signUp(); + return measureOperation({ + name: 'User Signup', + operation: async () => { + counter++; + const user = new Parse.User(); + user.set('username', `benchmark_user_${Date.now()}_${counter}`); + user.set('password', 'benchmark_password'); + user.set('email', `benchmark${counter}@example.com`); + await user.signUp(); + }, }); } @@ -286,10 +340,64 @@ async function benchmarkUserLogin() { let counter = 0; - return measureOperation('User Login', async () => { - const userCreds = users[counter++ % users.length]; - await Parse.User.logIn(userCreds.username, userCreds.password); - await Parse.User.logOut(); + return measureOperation({ + name: 'User Login', + operation: async () => { + const userCreds = users[counter++ % users.length]; + await Parse.User.logIn(userCreds.username, userCreds.password); + await Parse.User.logOut(); + }, + }); +} + +/** + * Benchmark: Query with Include (Parallel Include Pointers) + */ +async function benchmarkQueryWithInclude() { + + // Setup: Create nested object hierarchy + const Level2Class = Parse.Object.extend('Level2'); + const Level1Class = Parse.Object.extend('Level1'); + const RootClass = Parse.Object.extend('Root'); + + return measureOperation({ + name: 'Query with Include (2 levels)', + skipWarmup: true, + operation: async () => { + // Create 10 Level2 objects + const level2Objects = []; + for (let i = 0; i < 10; i++) { + const obj = new Level2Class(); + obj.set('name', `level2-${i}`); + obj.set('value', i); + level2Objects.push(obj); + } + await Parse.Object.saveAll(level2Objects); + + // Create 10 Level1 objects, each pointing to a Level2 object + const level1Objects = []; + for (let i = 0; i < 10; i++) { + const obj = new Level1Class(); + obj.set('name', `level1-${i}`); + obj.set('level2', level2Objects[i % level2Objects.length]); + level1Objects.push(obj); + } + await Parse.Object.saveAll(level1Objects); + + // Create 10 Root objects, each pointing to a Level1 object + const rootObjects = []; + for (let i = 0; i < 10; i++) { + const obj = new RootClass(); + obj.set('name', `root-${i}`); + obj.set('level1', level1Objects[i % level1Objects.length]); + rootObjects.push(obj); + } + await Parse.Object.saveAll(rootObjects); + + const query = new Parse.Query('Root'); + query.include('level1.level2'); + await query.find(); + }, }); } @@ -297,14 +405,14 @@ async function benchmarkUserLogin() { * Run all benchmarks */ async function runBenchmarks() { - console.log('Starting Parse Server Performance Benchmarks...'); - console.log(`Iterations per benchmark: ${ITERATIONS}`); + logInfo('Starting Parse Server Performance Benchmarks...'); + logInfo(`Iterations per benchmark: ${ITERATIONS}`); let server; try { // Initialize Parse Server - console.log('Initializing Parse Server...'); + logInfo('Initializing Parse Server...'); server = await initializeParseServer(); // Wait for server to be ready @@ -312,47 +420,38 @@ async function runBenchmarks() { const results = []; - // Run each benchmark with database cleanup - console.log('Running Object Create benchmark...'); - await cleanupDatabase(); - results.push(await benchmarkObjectCreate()); - - console.log('Running Object Read benchmark...'); - await cleanupDatabase(); - results.push(await benchmarkObjectRead()); - - console.log('Running Object Update benchmark...'); - await cleanupDatabase(); - results.push(await benchmarkObjectUpdate()); - - console.log('Running Simple Query benchmark...'); - await cleanupDatabase(); - results.push(await benchmarkSimpleQuery()); + // Define all benchmarks to run + const benchmarks = [ + // { name: 'Object Create', fn: benchmarkObjectCreate }, + // { name: 'Object Read', fn: benchmarkObjectRead }, + // { name: 'Object Update', fn: benchmarkObjectUpdate }, + // { name: 'Simple Query', fn: benchmarkSimpleQuery }, + // { name: 'Batch Save', fn: benchmarkBatchSave }, + // { name: 'User Signup', fn: benchmarkUserSignup }, + // { name: 'User Login', fn: benchmarkUserLogin }, + { name: 'Query with Include', fn: benchmarkQueryWithInclude }, + ]; - console.log('Running Batch Save benchmark...'); - await cleanupDatabase(); - results.push(await benchmarkBatchSave()); - - console.log('Running User Signup benchmark...'); - await cleanupDatabase(); - results.push(await benchmarkUserSignup()); - - console.log('Running User Login benchmark...'); - await cleanupDatabase(); - results.push(await benchmarkUserLogin()); + // Run each benchmark with database cleanup + for (const benchmark of benchmarks) { + logInfo(`\nRunning benchmark '${benchmark.name}'...`); + resetParseServer(); + await cleanupDatabase(); + results.push(await benchmark.fn()); + } // Output results in github-action-benchmark format (stdout) - console.log(JSON.stringify(results, null, 2)); + logInfo(JSON.stringify(results, null, 2)); // Output summary to stderr for visibility - console.log('Benchmarks completed successfully!'); - console.log('Summary:'); + logInfo('Benchmarks completed successfully!'); + logInfo('Summary:'); results.forEach(result => { - console.log(` ${result.name}: ${result.value.toFixed(2)} ${result.unit} (${result.extra})`); + logInfo(` ${result.name}: ${result.value.toFixed(2)} ${result.unit} (${result.extra})`); }); } catch (error) { - console.error('Error running benchmarks:', error); + logError('Error running benchmarks:', error); process.exit(1); } finally { // Cleanup diff --git a/spec/RestQuery.spec.js b/spec/RestQuery.spec.js index 6fe3c0fa18..7b676da1ea 100644 --- a/spec/RestQuery.spec.js +++ b/spec/RestQuery.spec.js @@ -386,6 +386,88 @@ describe('rest query', () => { } ); }); + + it('battle test parallel include with 100 nested includes', async () => { + const RootObject = Parse.Object.extend('RootObject'); + const Level1Object = Parse.Object.extend('Level1Object'); + const Level2Object = Parse.Object.extend('Level2Object'); + + // Create 100 level2 objects (10 per level1 object) + const level2Objects = []; + for (let i = 0; i < 100; i++) { + const level2 = new Level2Object({ + index: i, + value: `level2_${i}`, + }); + level2Objects.push(level2); + } + await Parse.Object.saveAll(level2Objects); + + // Create 10 level1 objects, each with 10 pointers to level2 objects + const level1Objects = []; + for (let i = 0; i < 10; i++) { + const level1 = new Level1Object({ + index: i, + value: `level1_${i}`, + }); + // Set 10 pointer fields (level2_0 through level2_9) + for (let j = 0; j < 10; j++) { + level1.set(`level2_${j}`, level2Objects[i * 10 + j]); + } + level1Objects.push(level1); + } + await Parse.Object.saveAll(level1Objects); + + // Create 1 root object with 10 pointers to level1 objects + const rootObject = new RootObject({ + value: 'root', + }); + for (let i = 0; i < 10; i++) { + rootObject.set(`level1_${i}`, level1Objects[i]); + } + await rootObject.save(); + + // Build include paths: level1_0 through level1_9, and level1_0.level2_0 through level1_9.level2_9 + const includePaths = []; + for (let i = 0; i < 10; i++) { + includePaths.push(`level1_${i}`); + for (let j = 0; j < 10; j++) { + includePaths.push(`level1_${i}.level2_${j}`); + } + } + + // Query with all includes + const query = new Parse.Query(RootObject); + query.equalTo('objectId', rootObject.id); + for (const path of includePaths) { + query.include(path); + } + console.time('query.find'); + const results = await query.find(); + console.timeEnd('query.find'); + expect(results.length).toBe(1); + + const result = results[0]; + expect(result.id).toBe(rootObject.id); + + // Verify all 10 level1 objects are included + for (let i = 0; i < 10; i++) { + const level1Field = result.get(`level1_${i}`); + expect(level1Field).toBeDefined(); + expect(level1Field instanceof Parse.Object).toBe(true); + expect(level1Field.get('index')).toBe(i); + expect(level1Field.get('value')).toBe(`level1_${i}`); + + // Verify all 10 level2 objects are included for each level1 object + for (let j = 0; j < 10; j++) { + const level2Field = level1Field.get(`level2_${j}`); + expect(level2Field).toBeDefined(); + expect(level2Field instanceof Parse.Object).toBe(true); + expect(level2Field.get('index')).toBe(i * 10 + j); + expect(level2Field.get('value')).toBe(`level2_${i * 10 + j}`); + } + } + }); }); describe('RestQuery.each', () => { diff --git a/src/RestQuery.js b/src/RestQuery.js index dd226f249c..c48cecdb6f 100644 --- a/src/RestQuery.js +++ b/src/RestQuery.js @@ -856,31 +856,54 @@ _UnsafeRestQuery.prototype.handleExcludeKeys = function () { }; // Augments this.response with data at the paths provided in this.include. -_UnsafeRestQuery.prototype.handleInclude = function () { +_UnsafeRestQuery.prototype.handleInclude = async function () { if (this.include.length == 0) { return; } - var pathResponse = includePath( - this.config, - this.auth, - this.response, - this.include[0], - this.context, - this.restOptions - ); - if (pathResponse.then) { - return pathResponse.then(newResponse => { - this.response = newResponse; - this.include = this.include.slice(1); - return this.handleInclude(); + const indexedResults = this.response.results.reduce((indexed, result, i) => { + indexed[result.objectId] = i; + return indexed; + }, {}); + + // Build the execution tree + const executionTree = {} + this.include.forEach(path => { + let current = executionTree; + path.forEach((node) => { + if (!current[node]) { + current[node] = { + path, + children: {} + }; + } + current = current[node].children }); - } else if (this.include.length > 0) { - this.include = this.include.slice(1); - return this.handleInclude(); + }); + + const recursiveExecutionTree = async (treeNode) => { + const { path, children } = treeNode; + const pathResponse = includePath( + this.config, + this.auth, + this.response, + path, + this.context, + this.restOptions, + this, + ); + if (pathResponse.then) { + const newResponse = await pathResponse + newResponse.results.forEach(newObject => { + // We hydrate the root of each result with sub results + this.response.results[indexedResults[newObject.objectId]][path[0]] = newObject[path[0]]; + }) + } + return Promise.all(Object.values(children).map(recursiveExecutionTree)); } - return pathResponse; + await Promise.all(Object.values(executionTree).map(recursiveExecutionTree)); + this.include = [] }; //Returns a promise of a processed set of results @@ -1018,7 +1041,6 @@ function includePath(config, auth, response, path, context, restOptions = {}) { } else if (restOptions.readPreference) { includeRestOptions.readPreference = restOptions.readPreference; } - const queryPromises = Object.keys(pointersHash).map(async className => { const objectIds = Array.from(pointersHash[className]); let where; @@ -1057,7 +1079,6 @@ function includePath(config, auth, response, path, context, restOptions = {}) { } return replace; }, {}); - var resp = { results: replacePointers(response.results, path, replace), };