mobile-benchmark.mjs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import fs from 'node:fs';import ts from 'typescript';import assert from 'node:assert/strict';import {withGateway} from './server-util.mjs';
  2. const privateDir='tmp/speed-round3-2026-11-10',outDir='perf/speed-round3-2026-11-10';fs.mkdirSync(privateDir,{recursive:true});
  3. const baseline=JSON.parse(fs.readFileSync('/Users/mac/.local/state/xiaoshu/cloud-releases/2026-11-10-speed-round3/mobile-gateway.json','utf8')).code;
  4. const local=fs.readFileSync('scripts/deploy-admin-functions.mjs','utf8').match(/const appGatewayCode = String.raw`([\s\S]*?)\n`;/)[1]+'\n'+fs.readFileSync('scripts/cloud/mobile-teaching.js','utf8');
  5. const parsed=ts.createSourceFile('gateway.js',local,ts.ScriptTarget.Latest,true,ts.ScriptKind.JS);
  6. function helper(name){const node=parsed.statements.find(n=>ts.isFunctionDeclaration(n)&&n.name?.text===name);if(!node)throw Error('Missing helper '+name);return node.getText(parsed).replace('function '+name+'(','function candidate'+name+'(');}
  7. const company=baseline.match(/const DEFAULT_COMPANY_ID\s*=\s*['"]([^'"]+)/)?.[1];if(!company)throw Error('Missing tenant');
  8. const subjectSql=`WITH counts AS (SELECT szyh AS uid,COUNT(*)::int appointments FROM "CourseAppointment" WHERE company=$1 GROUP BY szyh) SELECT u."objectId",c.appointments FROM counts c JOIN "_User" u ON u.company=$1 AND u."legacyUserId"::text=c.uid WHERE u."legacyGroupId"=1 AND COALESCE(u."isDeleted",false)=false ORDER BY c.appointments DESC LIMIT 1`;
  9. const teacher=JSON.parse(fs.readFileSync(privateDir+'/mobile-subjects.json','utf8'))[0];
  10. const students=await withGateway(`async function run(){return await Psql.query(${JSON.stringify(subjectSql)},[${JSON.stringify(company)}]);}`,async call=>call({}));if(!students.length)throw Error('No real student subject');
  11. fs.writeFileSync(privateDir+'/mobile-student-subject.json',JSON.stringify(students),{mode:0o600});
  12. const additions=[helper('appCompanionOverview'),helper('appAccountOverview'),helper('appLiveScopeVersion'),helper('appLiveVersionSnapshot').replace('await appLiveScopeVersion(','await candidateappLiveScopeVersion('),helper('appReviewPage').replace('appLiveVersionSnapshot(','candidateappLiveVersionSnapshot(')].join('\n');
  13. const instrumentation=`let mobileSqlCalls=[];const MOBILE_PROFILE_DB=new Proxy({},{get(_target,name){const target=Psql;if(!['query','one','oneOrNone'].includes(name))return target[name];return async(sql,args)=>{const started=Date.now();const value=await target[name](sql,args);mobileSqlCalls.push({method:name,durationMs:Date.now()-started,rows:Array.isArray(value)?value.length:1});return value;};}});`;
  14. const source=instrumentation+'\n'+(baseline+'\n'+additions).replace(/\bPsql\b/g,'MOBILE_PROFILE_DB')+`
  15. // Projection excludes legacy synchronization: it must never write business data.
  16. async function syncLegacyReviews(){return{state:'read-only-projection'};}
  17. async function run(input){
  18. const cases={teacherCompanion:{subject:${JSON.stringify(teacher.objectId)},helper:'companion',params:{source:'database',page:1,pageSize:20,dateStart:'2026-11-10',dateEnd:'2026-11-10'}},teacherReview:{subject:${JSON.stringify(teacher.objectId)},helper:'review',params:{scope:'today',page:1,pageSize:100,includeMetadata:false,includeIncome:false}},studentCompanion:{subject:${JSON.stringify(students[0].objectId)},helper:'companion',params:{source:'database',month:'2026-11',page:1,pageSize:20}},studentProfile:{subject:${JSON.stringify(students[0].objectId)},helper:'profile',params:{source:'database',profileOnly:true}}};
  19. const selected=cases[input.case];if(!selected)throw Error('Unknown fixed case');
  20. const current=await new Parse.Query('_User').get(selected.subject,{useMasterKey:true});
  21. const functions=input.variant==='candidate'?{companion:candidateappCompanionOverview,review:candidateappReviewPage,profile:candidateappAccountOverview}:{companion:appCompanionOverview,review:appReviewPage,profile:appAccountOverview};
  22. mobileSqlCalls=[];const started=Date.now(),result=await functions[selected.helper](selected.params,current);return{durationMs:Date.now()-started,queries:mobileSqlCalls,result};
  23. }`;
  24. const cases=process.argv.includes('--smoke')?['teacherReview']:['teacherCompanion','teacherReview','studentCompanion','studentProfile'],rounds=process.argv.includes('--smoke')?1:10;
  25. const raw=[],metrics=[];
  26. function canonical(value){return JSON.parse(JSON.stringify(value,(key,v)=>['refreshedAt','serverNow','lagSeconds'].includes(key)?undefined:v));}
  27. await withGateway(source,async call=>{
  28. for(const name of cases)for(let round=0;round<rounds;round++){
  29. const pair={};for(const variant of ['baseline','candidate']){const start=performance.now(),value=await call({case:name,variant});const row={case:name,round,variant,durationMs:value.durationMs,requestMs:Math.round(performance.now()-start),queryCount:value.queries.length,queryMs:value.queries.map(q=>q.durationMs),rows:value.result.schedules?.length??value.result.items?.length,total:value.result.page?.itemCount};metrics.push(row);raw.push({...row,...value});pair[variant]=name==='studentProfile'?value.result.profile:value.result;console.log(JSON.stringify(row));}
  30. assert.deepEqual(canonical(pair.candidate),canonical(pair.baseline),name+' output changed in round '+round);
  31. }
  32. });
  33. fs.writeFileSync(privateDir+'/mobile-benchmark-raw.json',JSON.stringify(raw,null,2),{mode:0o600});
  34. const quantile=(a,p)=>a.toSorted((a,b)=>a-b)[Math.ceil(a.length*p)-1];
  35. const summary=cases.map(name=>{const value={case:name};for(const variant of ['baseline','candidate']){const rows=metrics.filter(r=>r.case===name&&r.variant===variant);value[variant]={samples:rows.length,p50Ms:quantile(rows.map(r=>r.durationMs),.5),p75Ms:quantile(rows.map(r=>r.durationMs),.75),p95Ms:quantile(rows.map(r=>r.durationMs),.95),requestP75Ms:quantile(rows.map(r=>r.requestMs),.75),queries:rows[0].queryCount};}value.p75Reduction=1-value.candidate.p75Ms/value.baseline.p75Ms;return value;});
  36. const filename=process.argv.includes('--smoke')?'mobile-candidate-smoke.json':'mobile-benchmark.json';fs.writeFileSync(outDir+'/'+filename,JSON.stringify({context:'Operator-bound projections of existing teacher/student records, not role-login acceptance. Ten sequential alternating AB samples per case. Fresh SQL each call; no business-result cache. Student profile compares profile only; legacy synchronization is replaced with a no-write stub in both variants. SQL duration excludes current-user Parse fetch; request time includes it and transport.',summary,metrics},null,2));console.log(JSON.stringify({summary}));