verify-listing-rollout.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import 'dotenv/config';
  2. import { z } from 'zod';
  3. import { ParseRestClient } from '../src/db/parse-rest.client.js';
  4. import { VOC_PARSE_CLASSES } from '../src/db/parse-rest.schema.js';
  5. import type { ListingDimension, ListingScoreJob, ListingScoreJobItem, ListingScoreResult, ListingSourceSnapshot } from '../src/modules/listing-ai/domain.js';
  6. import { LISTING_DIMENSION_MAX, LISTING_RUBRIC_VERSION } from '../src/modules/listing-ai/scoring/rule-engine.js';
  7. import { LISTING_AI_RUBRIC_VERSION } from '../src/modules/listing-ai/scoring/ai-rubric.js';
  8. import { isListingV7Score } from '../src/modules/listing-ai/scoring/score-status.js';
  9. interface Stored<T> { workspaceId: string; productId?: string; jobId?: string; idempotencyKey?: string; slot?: 'rule_precheck' | 'formal_ai'; model?: string; payload: T }
  10. async function main() {
  11. const env = z.object({ PARSE_SERVER_URL: z.url(), PARSE_APP_ID: z.string().min(1), PARSE_MASTER_KEY: z.string().min(1), SAAS_DEFAULT_WORKSPACE_ID: z.string().default('demashi') }).parse(process.env);
  12. const client = new ParseRestClient({ serverUrl: env.PARSE_SERVER_URL, appId: env.PARSE_APP_ID, masterKey: env.PARSE_MASTER_KEY });
  13. const workspaceId = env.SAAS_DEFAULT_WORKSPACE_ID;
  14. const [sourceRows, resultRows, itemRows, jobRows] = await Promise.all([
  15. client.findAll<Stored<ListingSourceSnapshot>>(VOC_PARSE_CLASSES.listingSourceSnapshot, { workspaceId, platform: 'jd', isCurrent: true, catalogIncluded: true, catalogCohort: 'listing-jd-v3-formal-625' }),
  16. client.findAll<Stored<ListingScoreResult>>(VOC_PARSE_CLASSES.listingCurrentScore, { workspaceId }),
  17. client.findAll<Stored<ListingScoreJobItem>>(VOC_PARSE_CLASSES.listingScoreItem, { workspaceId }),
  18. client.findAll<Stored<ListingScoreJob> & { idempotencyKey: string }>(VOC_PARSE_CLASSES.listingScoreJob, { workspaceId }),
  19. ]);
  20. const schemas = await client.schemas();
  21. const legacyScoreSchemaPresent = schemas.some((schema) => schema.className === 'VocListingScoreResult');
  22. const slotKeys = resultRows.map((row) => `${row.workspaceId}|${row.productId ?? row.payload.productId}|${row.slot ?? (row.payload.scoreKind === 'hybrid_ai' ? 'formal_ai' : 'rule_precheck')}`);
  23. const duplicateCurrentSlots = slotKeys.length - new Set(slotKeys).size;
  24. const latestSources = new Map<string, ListingSourceSnapshot>();
  25. for (const row of sourceRows) { const value = row.payload; const current = latestSources.get(value.productId); if (!current || value.syncedAt > current.syncedAt) latestSources.set(value.productId, value); }
  26. const ruleResults = new Map<string, ListingScoreResult>();
  27. const aiResults = new Map<string, ListingScoreResult>();
  28. for (const row of resultRows) {
  29. const value = row.payload;
  30. if (!isListingV7Score(value)) continue;
  31. const target = row.slot === 'formal_ai' || value.scoreKind === 'hybrid_ai' ? aiResults : ruleResults;
  32. const current = target.get(value.productId);
  33. if (!current || value.createdAt > current.createdAt) target.set(value.productId, value);
  34. }
  35. const results = [...ruleResults.values()];
  36. const orphanResults = results.filter((result) => !latestSources.has(result.productId));
  37. const missingResults = [...latestSources.values()].filter((source) => !ruleResults.has(source.productId));
  38. const invalidDimensions = results.filter((result) => result.dimensions.length !== 5);
  39. const staleResults = results.filter((result) => latestSources.get(result.productId)?.sourceHash !== result.sourceHash);
  40. const invalidWeights = results.filter((result) => result.dimensions.some((item) => item.maxScore !== LISTING_DIMENSION_MAX[item.dimension]));
  41. const knownScores = results.map((result) => result.knownOverallScore).filter((value): value is number => typeof value === 'number');
  42. const staleAiResults = [...aiResults.values()].filter((result) => latestSources.get(result.productId)?.sourceHash !== result.sourceHash);
  43. const invalidAiResults = [...aiResults.values()].filter((result) => result.rubricVersion !== LISTING_AI_RUBRIC_VERSION || result.scoreKind !== 'hybrid_ai' || result.aiStatus !== 'completed' || !result.model || result.model === 'listing-showcase-ai');
  44. const simulatedScores = [...aiResults.values()].filter((result) => result.model === 'listing-v7-demo-simulation');
  45. const simulatedAverage = simulatedScores.length ? Math.round(simulatedScores.reduce((sum, result) => sum + (result.overallScore ?? 0), 0) / simulatedScores.length * 10) / 10 : null;
  46. const simulatedMinimum = simulatedScores.length ? Math.min(...simulatedScores.map((result) => result.overallScore ?? Number.POSITIVE_INFINITY)) : null;
  47. const simulatedMaximum = simulatedScores.length ? Math.max(...simulatedScores.map((result) => result.overallScore ?? Number.NEGATIVE_INFINITY)) : null;
  48. const simulatedMinimumCount = simulatedScores.filter((result) => result.overallScore === 73).length;
  49. const simulatedMaximumCount = simulatedScores.filter((result) => result.overallScore === 100).length;
  50. const dimensions = Object.keys(LISTING_DIMENSION_MAX) as ListingDimension[];
  51. const dimensionPartial = Object.fromEntries(dimensions.map((dimension) => [dimension, results.filter((result) => result.dimensions.find((item) => item.dimension === dimension)?.status === 'partial').length]));
  52. const knownMaxDistribution = results.reduce<Record<string, number>>((output, result) => { const key = String(result.knownOverallMaxScore ?? 'legacy'); output[key] = (output[key] ?? 0) + 1; return output; }, {});
  53. const compliance = results.reduce<Record<string, number>>((output, result) => { const key = result.compliance?.status ?? 'legacy'; output[key] = (output[key] ?? 0) + 1; return output; }, {});
  54. const normalizers = [...latestSources.values()].reduce<Record<string, number>>((output, source) => { const key = source.normalizerVersion ?? 'legacy'; output[key] = (output[key] ?? 0) + 1; return output; }, {});
  55. const latestJob = jobRows.map((row) => row.payload).filter((job) => job.rubricVersion === LISTING_RUBRIC_VERSION && job.total === 625).sort((a, b) => b.requestedAt.localeCompare(a.requestedAt))[0] ?? null;
  56. const latestJobItems = latestJob ? itemRows.map((row) => row.payload).filter((item) => item.jobId === latestJob.id) : [];
  57. const ruleOutcomes = (ruleId: string) => results.reduce<Record<string, number>>((output, result) => {
  58. const evidence = result.dimensions.flatMap((dimension) => dimension.evidence).find((item) => item.ruleId === ruleId);
  59. const key = evidence?.outcome ?? 'missing';
  60. output[key] = (output[key] ?? 0) + 1;
  61. return output;
  62. }, {});
  63. const partialWithErrorCode = latestJobItems.filter((item) => item.status === 'partial' && item.errorCode !== null).length;
  64. const failedWithoutErrorCode = latestJobItems.filter((item) => item.status === 'failed' && !item.errorCode).length;
  65. const titleLengthOutcomes = ruleOutcomes('title.length');
  66. const titleCategoryOutcomes = ruleOutcomes('title.category_in_first_15');
  67. const hardFailRate = (outcomes: Record<string, number>) => {
  68. const decided = (outcomes.pass ?? 0) + (outcomes.fail ?? 0);
  69. return decided ? Math.round((outcomes.fail ?? 0) / decided * 10_000) / 10_000 : 0;
  70. };
  71. const systemicHardFailGate = {
  72. maximumAllowedRate: 0.5,
  73. titleLength: hardFailRate(titleLengthOutcomes),
  74. titleCategoryInFirst15: hardFailRate(titleCategoryOutcomes),
  75. };
  76. const report = {
  77. workspaceId, rubricVersion: `${LISTING_RUBRIC_VERSION} / ${LISTING_AI_RUBRIC_VERSION}`, weights: LISTING_DIMENSION_MAX, sources: latestSources.size, normalizers,
  78. currentScoreRows: resultRows.length, duplicateCurrentSlots, legacyScoreSchemaPresent,
  79. ruleScores: ruleResults.size, rulePartialResults: results.filter((result) => result.overallScore === null).length,
  80. formalScores: aiResults.size, simulatedScores: simulatedScores.length, simulatedAverage, simulatedMinimum, simulatedMaximum, simulatedMinimumCount, simulatedMaximumCount, invalidAiResults: invalidAiResults.length, staleAiResults: staleAiResults.length,
  81. averageKnownScore: knownScores.length ? Math.round(knownScores.reduce((sum, value) => sum + value, 0) / knownScores.length * 10) / 10 : null,
  82. knownMaxDistribution, dimensionPartial, compliance,
  83. ruleOutcomes: {
  84. titleLength: titleLengthOutcomes,
  85. titleCategoryInFirst15: titleCategoryOutcomes,
  86. imagePrimary: ruleOutcomes('images.primary'),
  87. },
  88. systemicHardFailGate,
  89. dataReadiness: {
  90. categoryRuleMissing: [...latestSources.values()].filter((source) => !source.categoryContext?.ruleVersion).length,
  91. vocEvidenceMissing: [...latestSources.values()].filter((source) => !source.vocEvidence?.length).length,
  92. descriptionStructureMissing: [...latestSources.values()].filter((source) => !source.descriptionStructure?.observed).length,
  93. },
  94. missingResults: missingResults.length, orphanResults: orphanResults.length, staleResults: staleResults.length, invalidDimensions: invalidDimensions.length, invalidWeights: invalidWeights.length,
  95. latestJob: latestJob ? { id: latestJob.id, status: latestJob.status, total: latestJob.total, processed: latestJob.processed, succeeded: latestJob.succeeded, partial: latestJob.partial, blocked: latestJob.blocked, failed: latestJob.failed } : null,
  96. latestJobItems: latestJobItems.length,
  97. jobItemStatusSemantics: { partialWithErrorCode, failedWithoutErrorCode },
  98. };
  99. console.log(JSON.stringify(report, null, 2));
  100. if (latestSources.size !== 625 || normalizers['jd-listing-v5'] !== 625 || resultRows.length !== 1250 || duplicateCurrentSlots || legacyScoreSchemaPresent || ruleResults.size !== 625 || aiResults.size !== 625 || simulatedScores.length !== 625 || simulatedAverage !== 87.3 || simulatedMinimum !== 73 || simulatedMaximum !== 100 || simulatedMinimumCount !== 1 || simulatedMaximumCount !== 1 || invalidAiResults.length || staleAiResults.length || missingResults.length || orphanResults.length || staleResults.length || invalidDimensions.length || invalidWeights.length || (latestJob !== null && latestJob.processed !== latestJob.total) || partialWithErrorCode || failedWithoutErrorCode || systemicHardFailGate.titleLength > systemicHardFailGate.maximumAllowedRate || systemicHardFailGate.titleCategoryInFirst15 > systemicHardFailGate.maximumAllowedRate) process.exitCode = 2;
  101. }
  102. main().catch((error) => { console.error(`[verify-listing-rollout] ${error instanceof Error ? error.message : error}`); process.exitCode = 1; });