import { computeRawScore, adjustEmissionWeights, toUint16Weights, type SellWeightState, normalizeWeightsWithEmissionTiers, PRISM_WEIGHT_FORMULA_VERSION, type EmissionTier, } from "./epoch-summary-math.js"; const BLOCK_MS = 12_000; const BLOCKS_PER_DAY = 7_200; const MAX_BACKFILL_EPOCHS = 50; export interface ChainEpochSnapshot { currentEpoch: number; currentBlock: number; blocksPerEpoch: number; lastSyncedAt: Date; } export interface EpochTaskWindow { epoch: number; start: Date; end: Date; } export interface EpochTaskCount { epoch: number; orchestratorId: string; completedTaskCount: number; } export interface QualifiedOrchestratorWeightInput { id: string; hotkey: string; uid: number | null; stakeTao: number; profiles: readonly {workload:'standard_transfers'|'room_transfers';pool:'qualified';prismFinalScore:number;epochVerifiedBytes:number}[]; penaltyMultiplier: number; sellState: SellWeightState; fraudReportReward: number; fraudReportRewardIds: readonly string[]; taskDoneCount: number; verifiedUploadedMib: number; } export interface EpochSummaryRow extends QualifiedOrchestratorWeightInput { epoch: number; emissionPrismTiebreakScore: number; epochTaskDoneCount: number; rawWeight: number; normalizedWeight: number; uint16Weight: number; tier: EmissionTier; } export interface EpochSummaryTotals { epoch: number; sumRawWeight: number; sumTaskDoneCount: number; sumEpochTaskDoneCount: number; sumVerifiedUploadedMib: number; qualifiedOrchestratorCount: number; allWeightsZero: boolean; currentBlock: number; blocksPerEpoch: number; formulaVersion: string; } export interface EpochSummaryRepository { loadChainSnapshot(): Promise; loadLastRecordedEpoch(): Promise; loadQualifiedOrchestrators(): Promise; countCompletedProductionTasks(windows: readonly EpochTaskWindow[]): Promise; transaction(operation: (store: EpochSummaryStore) => Promise): Promise; } export interface EpochSummaryStore { backfillEmptyTotals(epochs: readonly number[], chain: ChainEpochSnapshot): Promise; // Replace only this epoch's cohort, including when it is empty. Older snapshots remain intact. replaceCurrentEpochRows(epoch: number, rows: readonly EpochSummaryRow[]): Promise; upsertTotals(totals: EpochSummaryTotals): Promise; refreshStoredTaskCounts(epoch: number, counts: ReadonlyMap): Promise; pruneBeforeEpoch(firstRetainedEpoch: number): Promise; } export interface EpochMaterializationResult { epoch: number; rows: EpochSummaryRow[]; totals: EpochSummaryTotals; backfilledEpochs: number[]; refreshedPreviousEpoch: boolean; } export function epochRetentionCount(blocksPerEpoch: number): number { return Math.ceil((30 * BLOCKS_PER_DAY) / Math.max(1, blocksPerEpoch)); } function addMilliseconds(date: Date, milliseconds: number): Date { return new Date(date.getTime() + milliseconds); } export function buildEpochTaskWindows( chain: ChainEpochSnapshot, now: Date, includePrevious: boolean, ): EpochTaskWindow[] { const blocksPerEpoch = Math.max(1, chain.blocksPerEpoch); const epochStartBlock = chain.currentEpoch * blocksPerEpoch; const blocksSinceStart = Math.max(0, chain.currentBlock - epochStartBlock); const currentStart = addMilliseconds(chain.lastSyncedAt, -blocksSinceStart * BLOCK_MS); const projectedEnd = addMilliseconds(currentStart, blocksPerEpoch * BLOCK_MS); const currentEnd = projectedEnd.getTime() < now.getTime() ? projectedEnd : now; const windows: EpochTaskWindow[] = []; if (currentEnd.getTime() > currentStart.getTime()) { windows.push({ epoch: chain.currentEpoch, start: currentStart, end: currentEnd }); } if (includePrevious && chain.currentEpoch > 0) { const previousStart = addMilliseconds(currentStart, -blocksPerEpoch * BLOCK_MS); windows.push({ epoch: chain.currentEpoch - 1, start: previousStart, end: currentStart }); } return windows; } function taskCountMap(counts: readonly EpochTaskCount[], epoch: number): Map { return new Map( counts .filter((count) => count.epoch === epoch) .map((count) => [count.orchestratorId, Math.max(0, count.completedTaskCount)]), ); } export function buildEpochSummary(input: { epoch: number; currentBlock: number; blocksPerEpoch: number; orchestrators: readonly QualifiedOrchestratorWeightInput[]; epochTaskCounts: ReadonlyMap; }): { rows: EpochSummaryRow[]; totals: EpochSummaryTotals } { const rawScores = input.orchestrators.map((orchestrator) => computeRawScore(orchestrator.verifiedUploadedMib), ); const prismFinalScores=input.orchestrators.map(o=>{ const bytes=o.profiles.reduce((sum,p)=>sum+p.epochVerifiedBytes,0); return bytes>0?o.profiles.reduce((sum,p)=>sum+p.epochVerifiedBytes*p.prismFinalScore,0)/bytes:0; }); const normalized = normalizeWeightsWithEmissionTiers( input.orchestrators.map((orchestrator, index) => ({ uid: orchestrator.uid, hotkey: orchestrator.hotkey, prismFinalScore: prismFinalScores[index] ?? 0, verifiedUploadedMib: orchestrator.verifiedUploadedMib, rawScore: rawScores[index] ?? 0, })), ); const adjusted = adjustEmissionWeights(input.orchestrators.map((orchestrator, i) => ({ tierWeight: normalized.weights[i]!, reportReward: orchestrator.fraudReportReward, penalty: orchestrator.penaltyMultiplier, sellState: orchestrator.sellState, }))); const uint16 = toUint16Weights(adjusted.weights); const rows = input.orchestrators.map((orchestrator, index): EpochSummaryRow => ({ ...orchestrator, epoch: input.epoch, emissionPrismTiebreakScore: prismFinalScores[index] ?? 0, epochTaskDoneCount: input.epochTaskCounts.get(orchestrator.id) ?? 0, rawWeight: rawScores[index] ?? 0, normalizedWeight: adjusted.weights[index] ?? 0, uint16Weight: uint16[index] ?? 0, tier: normalized.tiers[index] ?? "E", })); return { rows, totals: { epoch: input.epoch, sumRawWeight: normalized.sumRaw, sumTaskDoneCount: rows.reduce((sum, row) => sum + row.taskDoneCount, 0), sumEpochTaskDoneCount: rows.reduce((sum, row) => sum + row.epochTaskDoneCount, 0), sumVerifiedUploadedMib: rows.reduce((sum, row) => sum + row.verifiedUploadedMib, 0), qualifiedOrchestratorCount: rows.length, allWeightsZero: adjusted.weights.every(weight => weight === 0), currentBlock: input.currentBlock, blocksPerEpoch: input.blocksPerEpoch, formulaVersion: PRISM_WEIGHT_FORMULA_VERSION, }, }; } export async function materializeCurrentEpoch( repository: EpochSummaryRepository, now = new Date(), ): Promise { const chain = await repository.loadChainSnapshot(); if (chain === null) return null; const lastRecordedEpoch = await repository.loadLastRecordedEpoch(); const refreshPrevious = chain.currentEpoch > 0 && (lastRecordedEpoch === null || lastRecordedEpoch < chain.currentEpoch); const windows = buildEpochTaskWindows(chain, now, refreshPrevious); const [orchestrators, counts] = await Promise.all([ repository.loadQualifiedOrchestrators(), repository.countCompletedProductionTasks(windows), ]); const currentCounts = taskCountMap(counts, chain.currentEpoch); const previousCounts = taskCountMap(counts, chain.currentEpoch - 1); const backfillStart = lastRecordedEpoch === null ? chain.currentEpoch : Math.max(lastRecordedEpoch + 1, chain.currentEpoch - MAX_BACKFILL_EPOCHS); const backfilledEpochs: number[] = []; for (let epoch = backfillStart; epoch < chain.currentEpoch; epoch += 1) { backfilledEpochs.push(epoch); } const summary = buildEpochSummary({ epoch: chain.currentEpoch, currentBlock: chain.currentBlock, blocksPerEpoch: chain.blocksPerEpoch, orchestrators, epochTaskCounts: currentCounts, }); await repository.transaction(async (store) => { if (backfilledEpochs.length) await store.backfillEmptyTotals(backfilledEpochs, chain); await store.replaceCurrentEpochRows(chain.currentEpoch, summary.rows); await store.upsertTotals(summary.totals); if (refreshPrevious) { await store.refreshStoredTaskCounts(chain.currentEpoch - 1, previousCounts); } const firstRetainedEpoch = Math.max( 0, chain.currentEpoch - epochRetentionCount(chain.blocksPerEpoch), ); await store.pruneBeforeEpoch(firstRetainedEpoch); }); return { epoch: chain.currentEpoch, rows: summary.rows, totals: summary.totals, backfilledEpochs, refreshedPreviousEpoch: refreshPrevious, }; }