Просмотр исходного кода

feat(data-platform): 补齐数据接收和处理底座

补齐 Raw 保留、接收和 Worker 运行时间线、采购原版本复算与受控恢复。Web 2.4.435 / Server 1.0.624。
YY968XX 48 минут назад
Родитель
Сommit
b2d0d91bd8
27 измененных файлов с 1193 добавлено и 16 удалено
  1. 1 1
      Web/package.json
  2. 3 1
      Web/src/views/aidop/data-platform/components/DatasetReleasePanel.vue
  3. 5 1
      Web/src/views/aidop/data-platform/components/IngestBatchStatus.vue
  4. 205 0
      Web/src/views/aidop/data-platform/components/IngestBatchTrace.vue
  5. 53 0
      Web/src/views/aidop/data-platform/components/IngestRawRetention.vue
  6. 24 0
      server/Admin.NET.DataPlatform.Worker/PurchaseBatchJournal.cs
  7. 6 0
      server/Admin.NET.DataPlatform.Worker/PurchaseDispatcher.cs
  8. 21 4
      server/Admin.NET.DataPlatform.Worker/PurchaseWorkerStore.cs
  9. 12 0
      server/Admin.NET.DataPlatform.Worker/README.md
  10. 11 3
      server/Admin.NET.Web.Entry/Admin.NET.Web.Entry.csproj
  11. 46 0
      server/Admin.NET.Web.Entry/UpdateScripts/1.0.624.sql
  12. 12 0
      server/Admin.NET.Web.Entry/UpdateScripts/1.0.624.verify.sql
  13. 26 0
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/IngestBatchJournal.cs
  14. 7 2
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpApiPullService.Capture.cs
  15. 7 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpApiPullService.Run.cs
  16. 4 1
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpEdgeDeviceService.Receive.cs
  17. 14 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestBatchJournal.cs
  18. 144 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestBatchTraceService.cs
  19. 1 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestDatasetController.ApiPull.cs
  20. 73 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestDatasetController.Trace.cs
  21. 94 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestRawRetentionService.cs
  22. 9 1
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestReceiveService.cs
  23. 115 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestReplayService.cs
  24. 3 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestServiceCollectionExtensions.cs
  25. 261 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpPurchaseHandoffService.Recovery.cs
  26. 2 2
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpPurchaseMigrationWriter.cs
  27. 34 0
      server/Plugins/Admin.NET.Plugin.AiDOP/Job/MdpRawRetentionJob.cs

+ 1 - 1
Web/package.json

@@ -1,7 +1,7 @@
 {
 	"name": "admin.net",
 	"type": "module",
-	"version": "2.4.434",
+	"version": "2.4.435",
 	"packageManager": "pnpm@10.32.1",
 	"lastBuildTime": "2026.03.15",
 	"description": "Admin.NET 站在巨人肩膀上的 .NET 通用权限开发框架",

+ 3 - 1
Web/src/views/aidop/data-platform/components/DatasetReleasePanel.vue

@@ -4,6 +4,7 @@ import { ElMessage, ElMessageBox } from 'element-plus';
 import ApiPullWorkspace from './ApiPullWorkspace.vue';
 import EdgeDeviceWorkspace from './EdgeDeviceWorkspace.vue';
 import IngestBatchStatus from './IngestBatchStatus.vue';
+import IngestRawRetention from './IngestRawRetention.vue';
 import IngestPushSample from './IngestPushSample.vue';
 import RelationalTrialPanel from './RelationalTrialPanel.vue';
 import { changeLifecycle, releaseAction, saveCandidate, versions, type Candidate, type IngestDataset, type VersionWorkspace } from '../api/ingestDatasets';
@@ -211,7 +212,8 @@ async function lifecycle(action: string) {
 				>启用 {{ candidate.version }}</el-button
 			>
 		</section>
-		<IngestBatchStatus :key="factoryId + '/' + dataset.id" :dataset-id="dataset.id" :factory-id="factoryId" :has-schema="!!dataset.activeSchemaVersion" />
+		<IngestBatchStatus :key="factoryId + '/' + dataset.id" :dataset-id="dataset.id" :factory-id="factoryId" :has-schema="!!dataset.activeSchemaVersion" :can-inspect="model?.canTrial" />
+		<IngestRawRetention v-if="model?.canTrial" :key="factoryId + '/retention/' + dataset.id" :dataset-id="dataset.id" :factory-id="factoryId" />
 		<IngestPushSample v-if="dataset.activeSchemaVersion" :key="'sample/' + factoryId + '/' + dataset.id" :dataset-id="dataset.id" :factory-id="factoryId" />
 		<ApiPullWorkspace v-if="model?.canTrial" :key="factoryId + '/api-pull/' + dataset.id" :dataset="dataset" :factory-id="factoryId" />
 		<EdgeDeviceWorkspace v-if="model?.canTrial" :key="factoryId + '/edge/' + dataset.id" :dataset="dataset" :factory-id="factoryId" />

+ 5 - 1
Web/src/views/aidop/data-platform/components/IngestBatchStatus.vue

@@ -2,8 +2,9 @@
 import { shallowRef } from 'vue';
 import service from '/@/utils/request';
 import { downloadByData } from '/@/utils/download';
+import IngestBatchTrace from './IngestBatchTrace.vue';
 
-const props = defineProps<{ datasetId: string; factoryId: string; hasSchema: boolean }>();
+const props = defineProps<{ datasetId: string; factoryId: string; hasSchema: boolean; canInspect?: boolean }>();
 interface BatchStatus {
 	receiveStatus: string;
 	batchId: string;
@@ -115,6 +116,9 @@ async function query() {
 			<el-descriptions-item v-if="result.errorCode" label="诊断码">{{ result.errorCode }}</el-descriptions-item>
 		</el-descriptions>
 		<el-button v-if="result" link type="primary" @click="downloadDiagnostics">下载批次排查记录</el-button>
+		<IngestBatchTrace v-if="result && canInspect" :key="result.batchId" :dataset-id="datasetId"
+			:factory-id="factoryId" :batch-id="result.batchId"
+			:can-replay="['SUCCEEDED', 'PARTIAL', 'QUARANTINED'].includes(result.workerStatus ?? '')" />
 	</section>
 </template>
 

+ 205 - 0
Web/src/views/aidop/data-platform/components/IngestBatchTrace.vue

@@ -0,0 +1,205 @@
+<script setup lang="ts">
+import { computed, shallowRef } from 'vue';
+import { ElMessageBox } from 'element-plus';
+import service from '/@/utils/request';
+
+const props = defineProps<{ datasetId: string; factoryId: string; batchId: string; canReplay: boolean }>();
+interface TraceEvent { code: string; occurredAt: string; attempt?: number; recordCount?: number; diagnostic?: string }
+interface Line { rawEventId: string; ordinal: number; sourcePosition: string; businessKey?: string }
+interface Outcome { rawEventId: string; status: string; stageId?: string; standardId?: string }
+interface Stamp { version: string }
+interface Trace {
+	sourceCode: string;
+	factoryId: string;
+	payloadSha256: string;
+	payloadExpiredAt?: string;
+	sourceWindow?: { from?: string; to?: string; watermark?: string };
+	leaseUntil?: string;
+	workerUpdatedAt?: string;
+	partialHistory: boolean;
+	mappingVersion?: string;
+	ruleVersion?: string;
+	configVersion?: string;
+	sourceSchema?: Stamp;
+	rawSchema?: Stamp;
+	handoffSchema?: Stamp;
+	lines: Line[];
+	isolations: { rawEventId: string; field: string; code: string }[];
+	timeline: TraceEvent[];
+	delivery?: { packageVersion: string; lines: Outcome[]; recoveries: { actor: string; reason: string; createdAt: string; lines: Outcome[] }[] };
+	canRestore: boolean;
+}
+interface Preview {
+	packageVersion: string;
+	acceptedCount: number;
+	isolatedCount: number;
+	originalDigest: string | null;
+	calculatedDigest: string;
+	digestMatches: boolean;
+	recovery?: { digest: string; canRestore: boolean; lines: Outcome[] };
+}
+const trace = shallowRef<Trace>();
+const preview = shallowRef<Preview>();
+const reason = shallowRef('');
+const message = shallowRef('');
+const failed = shallowRef(false);
+const busy = shallowRef(false);
+const base = computed(() => '/api/DataPlatform/ingest-datasets/' + props.datasetId + '/batches/' + props.batchId);
+const options = computed(() => ({ params: { factoryId: props.factoryId } }));
+const stages: Record<string, string> = {
+	RAW_STORED: 'Raw 原文留存', RAW_STORED_HISTORICAL: 'Raw 原文留存(历史)', RAW_ACCEPTED: '业务接收,创建处理待办',
+	RAW_REJECTED: '原文保留,业务校验拒收', RAW_EMPTY: '空页确认', WORKER_STATE_HISTORICAL: '历史处理状态',
+	WORKER_CLAIMED: 'Worker 认领', WORKER_RECLAIMED: '租约到期后接管', WORKER_LEASE_EXPIRED: '租约到期,重试耗尽',
+	WORKER_RETRY: '处理失败,等待重试', WORKER_FAILED: '处理失败', ROWS_ISOLATED: '记录隔离',
+	PACKAGE_FROZEN: '二级包确认', DELIVERY_RETRY: '投递失败,等待重试', DELIVERY_FAILED: '投递失败',
+	DELIVERY_CONFIRMED: '交接已确认', DELIVERY_CONFIRMED_HISTORICAL: '交接已确认(历史)',
+	PURCHASE_LANDED: '采购贴源、标准及回执提交', PURCHASE_RECOVERED: '缺失采购结果已补写', RAW_EXPIRED: '到期原文已处置',
+};
+const outcomes: Record<string, string> = {
+	WRITTEN: '已落层', REUSED: '复用', DELETED: '已删除', STALE: '已过时', CONFLICT: '结果冲突',
+	COMPLETE: '两层齐全', MISSING_STAGE: '缺贴源', MISSING_STANDARD: '缺标准', MISSING_BOTH: '两层均缺',
+	EXCLUDED: '原结果无需补写', VERSION_CHANGED: '版本或归属有变', RESTORED: '已补写',
+};
+const errors: Record<string, string> = {
+	RAW_PAYLOAD_EXPIRED: 'Raw 原文已到期处置,可以继续查询追溯记录。',
+	RAW_FROZEN_SNAPSHOT_UNAVAILABLE: '冻结版本、原文或行定位无法复现。',
+	RAW_REPLAY_BATCH_NOT_COMPLETE: '批次仍在处理中或等待处置。',
+	RAW_REPLAY_OBJECT_UNSUPPORTED: '该批次不属于当前支持的采购回放对象。',
+	RAW_REPLAY_PREVIEW_CHANGED: '接收结果已变化,请重新预演。',
+	RAW_REPLAY_VERSION_CHANGED: '当前采购版本已变化,请重新预演。',
+	RAW_REPLAY_RECEIPT_MISMATCH: '原交接回执与复算结果不一致。',
+	RAW_REPLAY_TARGET_CONFLICT: '当前采购数据有冲突,请核对后再操作。',
+	PURCHASE_MIGRATION_FROZEN: '采购来源正在迁移冻结,暂不可补写。',
+};
+const deliveryByEvent = computed(() => {
+	const byEvent = new Map(trace.value?.delivery?.lines.map(row => [row.rawEventId, row]));
+	for (const recovery of [...(trace.value?.delivery?.recoveries ?? [])].reverse()) {
+		for (const row of recovery.lines) byEvent.set(row.rawEventId, row);
+	}
+	return byEvent;
+});
+const rows = computed(() => (trace.value?.lines ?? []).map(row => {
+	const delivery = deliveryByEvent.value.get(row.rawEventId);
+	return {
+		...row,
+		status: delivery ? outcomes[delivery.status] ?? delivery.status : '',
+		stageId: delivery?.stageId,
+		standardId: delivery?.standardId,
+		isolated: trace.value?.isolations.filter(issue => issue.rawEventId === row.rawEventId)
+			.map(issue => issue.field + ' · ' + issue.code).join(','),
+	};
+}));
+
+async function run(action: () => Promise<void>) {
+	if (busy.value) return;
+	busy.value = true;
+	failed.value = false;
+	message.value = '';
+	try {
+		await action();
+	} catch (error) {
+		failed.value = true;
+		const code = (error as { response?: { data?: { code?: string } } }).response?.data?.code;
+		message.value = code ? errors[code] ?? code : '批次操作失败。';
+	} finally {
+		busy.value = false;
+	}
+}
+
+async function read() {
+	trace.value = (await service.get<Trace>(base.value + '/trace', options.value)).data;
+}
+
+function calculate() {
+	preview.value = undefined;
+	reason.value = '';
+	return run(async () => {
+		preview.value = (await service.post<Preview>(base.value + '/replay-preview', {}, options.value)).data;
+	});
+}
+
+async function restore() {
+	const recovery = preview.value?.recovery;
+	const explanation = reason.value.trim();
+	if (!recovery?.canRestore || !trace.value?.canRestore || !explanation || busy.value) return;
+	try {
+		await ElMessageBox.confirm('将按预演结果补写缺失的采购贴源或标准记录。', '确认补写', { type: 'warning' });
+	} catch {
+		return;
+	}
+	await run(async () => {
+		const { data } = await service.post<{ restored: Outcome[] }>(base.value + '/restore',
+			{ previewDigest: recovery.digest, reason: explanation }, options.value);
+		preview.value = undefined;
+		reason.value = '';
+		await read();
+		message.value = '已补写 ' + data.restored.length + ' 条采购明细的缺失结果。';
+	});
+}
+</script>
+
+<template>
+	<section class="batch-trace">
+		<el-button link type="primary" :loading="busy" @click="run(read)">查询追溯与运行时间线</el-button>
+		<p v-if="message" :role="failed ? 'alert' : 'status'">{{ message }}</p>
+		<template v-if="trace">
+			<el-descriptions :column="2" border>
+				<el-descriptions-item label="来源">{{ trace.sourceCode }}</el-descriptions-item>
+				<el-descriptions-item label="实际工厂">{{ trace.factoryId }}</el-descriptions-item>
+				<el-descriptions-item label="来源 / Raw Schema">{{ trace.sourceSchema?.version }} / {{ trace.rawSchema?.version }}</el-descriptions-item>
+				<el-descriptions-item label="二级包">{{ trace.delivery?.packageVersion ?? trace.handoffSchema?.version }}</el-descriptions-item>
+				<el-descriptions-item label="配置 / 规则">{{ trace.configVersion }} / {{ trace.ruleVersion }}</el-descriptions-item>
+				<el-descriptions-item label="映射摘要"><span class="digest">{{ trace.mappingVersion }}</span></el-descriptions-item>
+				<el-descriptions-item label="Raw 原文 SHA-256" :span="2"><span class="digest">{{ trace.payloadSha256 }}</span></el-descriptions-item>
+			</el-descriptions>
+			<p v-if="trace.sourceWindow">
+				采集窗口 {{ trace.sourceWindow.from ?? '起点未登记' }} 至 {{ trace.sourceWindow.to ?? '终点未登记' }}
+				<span v-if="trace.sourceWindow.watermark">· {{ trace.sourceWindow.watermark }}</span>
+			</p>
+			<p v-if="trace.leaseUntil && trace.workerUpdatedAt">
+				Worker 最近更新 {{ new Date(trace.workerUpdatedAt).toLocaleString() }}
+				· 租约至 {{ new Date(trace.leaseUntil).toLocaleString() }}
+			</p>
+			<p v-if="trace.partialHistory">历史批次仅展示有记录的事件。</p>
+			<p v-if="trace.payloadExpiredAt">原文已在 {{ new Date(trace.payloadExpiredAt).toLocaleString() }} 到期处置。</p>
+			<el-timeline class="batch-timeline">
+				<el-timeline-item v-for="(event, index) in trace.timeline" :key="index" :timestamp="new Date(event.occurredAt).toLocaleString()">
+					{{ stages[event.code] ?? event.code }}
+					<span v-if="event.attempt"> · 第 {{ event.attempt }} 次</span>
+					<span v-if="event.recordCount !== undefined && event.recordCount !== null"> · {{ event.recordCount }} 行</span>
+					<span v-if="event.diagnostic"> · {{ event.diagnostic }}</span>
+				</el-timeline-item>
+			</el-timeline>
+			<el-table v-if="rows.length" :data="rows" max-height="320">
+				<el-table-column prop="sourcePosition" label="原文位置" min-width="120" />
+				<el-table-column prop="businessKey" label="业务键" min-width="120" />
+				<el-table-column prop="status" label="交接结果" min-width="105" />
+				<el-table-column prop="stageId" label="贴源 ID" min-width="120" />
+				<el-table-column prop="standardId" label="标准 ID" min-width="120" />
+				<el-table-column prop="isolated" label="隔离诊断" min-width="140" />
+			</el-table>
+			<el-button v-if="canReplay" type="primary" plain :disabled="!!trace.payloadExpiredAt" :loading="busy" @click="calculate">按原版本预演</el-button>
+			<template v-if="preview">
+				<p>复算 {{ preview.acceptedCount }} 行通过、{{ preview.isolatedCount }} 行隔离。
+					{{ preview.digestMatches ? '二级包摘要一致。' : preview.originalDigest ? '二级包摘要有差异。' : '该批次没有历史二级包摘要。' }}</p>
+				<p class="digest">本次摘要 {{ preview.calculatedDigest }}</p>
+				<el-table v-if="preview.recovery" :data="preview.recovery.lines" max-height="240">
+					<el-table-column prop="rawEventId" label="Raw 事件" min-width="245" />
+					<el-table-column label="当前落层结果" min-width="160">
+						<template #default="{ row }">{{ outcomes[row.status] ?? row.status }}</template>
+					</el-table-column>
+				</el-table>
+				<el-form v-if="trace.canRestore && preview.recovery?.canRestore" inline @submit.prevent="restore">
+					<el-form-item label="补写原因"><el-input v-model="reason" :maxlength="240" /></el-form-item>
+					<el-button native-type="submit" type="warning" :disabled="!reason.trim()" :loading="busy">确认补写缺失结果</el-button>
+				</el-form>
+			</template>
+		</template>
+	</section>
+</template>
+
+<style scoped>
+.batch-trace { display: grid; gap: 10px; justify-items: start; }
+.batch-timeline { padding-inline-start: 14px; }
+.digest { overflow-wrap: anywhere; }
+</style>

+ 53 - 0
Web/src/views/aidop/data-platform/components/IngestRawRetention.vue

@@ -0,0 +1,53 @@
+<script setup lang="ts">
+import { shallowRef } from 'vue';
+import service from '/@/utils/request';
+
+const props = defineProps<{ datasetId: string; factoryId: string }>();
+const days = shallowRef<number>();
+const saved = shallowRef<number>();
+const canChange = shallowRef(false);
+const busy = shallowRef(false);
+const message = shallowRef('');
+const failed = shallowRef(false);
+
+async function run(save = false) {
+	if (busy.value) return;
+	busy.value = true;
+	failed.value = false;
+	message.value = '';
+	const path = '/api/DataPlatform/ingest-datasets/' + props.datasetId + '/raw-retention';
+	const options = { params: { factoryId: props.factoryId } };
+	try {
+		if (save) {
+			const { data } = await service.put<{ days: number }>(path, { days: days.value }, options);
+			saved.value = days.value = data.days;
+			message.value = '保留期限已保存。';
+		} else {
+			const { data } = await service.get<{ days: number; canChange: boolean }>(path, options);
+			saved.value = days.value = data.days;
+			canChange.value = data.canChange;
+		}
+	} catch {
+		failed.value = true;
+		message.value = save ? '保存失败,请核对权限和保留天数。' : '无法读取保留期限。';
+	} finally {
+		busy.value = false;
+	}
+}
+</script>
+
+<template>
+	<el-collapse>
+		<el-collapse-item title="Raw 原文保留期限" name="retention">
+			<el-button v-if="saved === undefined" :loading="busy" @click="run()">读取保留期限</el-button>
+			<el-form v-else inline @submit.prevent="run(true)">
+				<el-form-item label="原文保留天数">
+					<el-input-number v-model="days" :min="7" :max="3650" :step="1" step-strict :disabled="!canChange || busy" />
+				</el-form-item>
+				<el-button v-if="canChange" native-type="submit" :disabled="days === undefined || days === saved" :loading="busy">保存</el-button>
+			</el-form>
+			<p v-if="saved !== undefined">清理作业启用后处置已到期原文,保留摘要和追溯记录。在途及待恢复批次继续保留。</p>
+			<p v-if="message" :role="failed ? 'alert' : 'status'">{{ message }}</p>
+		</el-collapse-item>
+	</el-collapse>
+</template>

+ 24 - 0
server/Admin.NET.DataPlatform.Worker/PurchaseBatchJournal.cs

@@ -0,0 +1,24 @@
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+using MySqlConnector;
+
+namespace Admin.NET.DataPlatform.Worker;
+
+internal static class PurchaseBatchJournal
+{
+    internal static async Task AppendAsync(MySqlConnection connection, MySqlTransaction transaction,
+        PurchaseTaskLease scope, string eventCode, CancellationToken token, int? attempt = null,
+        int? count = null, string? diagnostic = null)
+    {
+        using var command = new MySqlCommand(IngestBatchJournal.Insert, connection, transaction);
+        command.Parameters.AddWithValue("@BatchId", scope.BatchId.ToString("D"));
+        command.Parameters.AddWithValue("@TenantId", scope.TenantId);
+        command.Parameters.AddWithValue("@FactoryId", scope.FactoryId);
+        command.Parameters.AddWithValue("@DatasetId", scope.DatasetId);
+        command.Parameters.AddWithValue("@SourceId", scope.SourceId);
+        command.Parameters.AddWithValue("@EventCode", eventCode);
+        command.Parameters.AddWithValue("@Attempt", (object?)attempt ?? DBNull.Value);
+        command.Parameters.AddWithValue("@Count", (object?)count ?? DBNull.Value);
+        command.Parameters.AddWithValue("@Diagnostic", (object?)diagnostic ?? DBNull.Value);
+        await command.ExecuteNonQueryAsync(token);
+    }
+}

+ 6 - 0
server/Admin.NET.DataPlatform.Worker/PurchaseDispatcher.cs

@@ -107,6 +107,12 @@ internal sealed class PurchaseDispatcher(string connectionString, IAidopPackageH
             evidence.Parameters.AddWithValue("@Isolated", isolated);
             await evidence.ExecuteNonQueryAsync(token);
         }
+        if (accepted.HasValue && isolated > isolatedCount)
+            await PurchaseBatchJournal.AppendAsync(connection, tx, scope, IngestBatchJournal.RowsIsolated, token,
+                count: isolated - isolatedCount);
+        var eventCode = accepted.HasValue ? IngestBatchJournal.DeliveryConfirmed
+            : final == "FAILED" ? IngestBatchJournal.DeliveryFailed : IngestBatchJournal.DeliveryRetry;
+        await PurchaseBatchJournal.AppendAsync(connection, tx, scope, eventCode, token, attempts + 1, accepted, error);
         await tx.CommitAsync(token);
         Console.WriteLine($"Dispatch {scope.BatchId:D}: {final} {error}");
         return true;

+ 21 - 4
server/Admin.NET.DataPlatform.Worker/PurchaseWorkerStore.cs

@@ -18,7 +18,7 @@ internal sealed class PurchaseWorkerStore(string connectionString)
         using var query = new MySqlCommand(
             """
             SELECT t.batch_id, t.tenant_id, t.factory_id, t.source_id, t.dataset_id, t.attempt_count,
-                   t.handoff_package_json, t.handoff_package_sha256
+                   t.handoff_package_json, t.handoff_package_sha256, t.status
             FROM mdp_ingest_receive_task t
             WHERE (t.status = 'PENDING'
                 OR (t.status = 'RETRY_PENDING' AND t.next_attempt_at_utc <= UTC_TIMESTAMP(6))
@@ -42,6 +42,7 @@ internal sealed class PurchaseWorkerStore(string connectionString)
         query.Parameters.AddWithValue("@LegacyKey", PurchaseOrderSchemaRegistry.DatasetKey);
 
         PurchaseTaskLease lease;
+        string priorStatus;
         await using (var reader = await query.ExecuteReaderAsync(cancellationToken))
         {
             if (!await reader.ReadAsync(cancellationToken))
@@ -50,6 +51,7 @@ internal sealed class PurchaseWorkerStore(string connectionString)
             lease = new PurchaseTaskLease(reader.GetGuid(0), reader.GetInt64(1), reader.GetInt64(2),
                 reader.GetInt64(3), reader.GetInt64(4), reader.GetInt32(5) + 1, Guid.NewGuid().ToString("D"),
                 reader.IsDBNull(6) ? null : reader.GetFieldValue<byte[]>(6), reader.IsDBNull(7) ? null : reader.GetString(7));
+            priorStatus = reader.GetString(8);
         }
 
         using var change = new MySqlCommand(lease.AttemptNumber > MaxAttempts
@@ -71,6 +73,9 @@ internal sealed class PurchaseWorkerStore(string connectionString)
             change.Parameters.AddWithValue("@LeaseToken", lease.Token);
         }
         await change.ExecuteNonQueryAsync(cancellationToken);
+        var eventCode = lease.AttemptNumber > MaxAttempts ? IngestBatchJournal.WorkerLeaseExpired
+            : priorStatus == "PROCESSING" ? IngestBatchJournal.WorkerReclaimed : IngestBatchJournal.WorkerClaimed;
+        await PurchaseBatchJournal.AppendAsync(connection, transaction, lease, eventCode, cancellationToken, lease.AttemptNumber);
         await transaction.CommitAsync(cancellationToken);
         return lease.AttemptNumber <= MaxAttempts ? lease : null;
     }
@@ -79,7 +84,7 @@ internal sealed class PurchaseWorkerStore(string connectionString)
         UpdateLiveLeaseAsync(lease, $"""
             UPDATE mdp_ingest_receive_task SET lease_until_utc = TIMESTAMPADD(SECOND, 60, UTC_TIMESTAMP(6)),
                 updated_at_utc = UTC_TIMESTAMP(6) WHERE {LiveLease}
-            """, cancellationToken);
+            """, cancellationToken, null, null);
 
     public async Task<PreparedIngestBatch> ReadRawAsync(PurchaseTaskLease lease, CancellationToken cancellationToken)
     {
@@ -176,7 +181,11 @@ internal sealed class PurchaseWorkerStore(string connectionString)
             return false;
         await insert.ExecuteNonQueryAsync(token);
         if (isolated.Count > 0)
+        {
             await InsertIsolationsAsync(connection, tx, lease, isolated, token);
+            await PurchaseBatchJournal.AppendAsync(connection, tx, lease, IngestBatchJournal.RowsIsolated, token,
+                lease.AttemptNumber, isolated.Count);
+        }
         using var release = FencedCommand(connection, lease, $"""
             UPDATE mdp_ingest_receive_task SET status='HANDOFF_READY', handoff_package_json=@Package,
               handoff_package_sha256=@Digest, lease_token=NULL, lease_until_utc=NULL, updated_at_utc=UTC_TIMESTAMP(6)
@@ -186,6 +195,8 @@ internal sealed class PurchaseWorkerStore(string connectionString)
         release.Parameters.AddWithValue("@Digest", digest);
         if (await release.ExecuteNonQueryAsync(token) != 1)
             return false;
+        await PurchaseBatchJournal.AppendAsync(connection, tx, lease, IngestBatchJournal.PackageFrozen, token,
+            lease.AttemptNumber, package.Items.Count);
         await tx.CommitAsync(token);
         return true;
     }
@@ -199,7 +210,8 @@ internal sealed class PurchaseWorkerStore(string connectionString)
                 next_attempt_at_utc = IF(@RetrySeconds > 0, TIMESTAMPADD(SECOND, @RetrySeconds, UTC_TIMESTAMP(6)), NULL),
                 updated_at_utc = UTC_TIMESTAMP(6)
             WHERE {LiveLease}
-            """, cancellationToken, ("@Status", retrySeconds > 0 ? "RETRY_PENDING" : "FAILED"),
+            """, cancellationToken, retrySeconds > 0 ? IngestBatchJournal.WorkerRetry : IngestBatchJournal.WorkerFailed,
+            code, ("@Status", retrySeconds > 0 ? "RETRY_PENDING" : "FAILED"),
             ("@Error", code), ("@RetrySeconds", retrySeconds));
     }
 
@@ -225,12 +237,14 @@ internal sealed class PurchaseWorkerStore(string connectionString)
         if (await finish.ExecuteNonQueryAsync(cancellationToken) != 1)
             return false;
 
+        await PurchaseBatchJournal.AppendAsync(connection, transaction, lease, IngestBatchJournal.RowsIsolated,
+            cancellationToken, lease.AttemptNumber, isolations.Count);
         await transaction.CommitAsync(cancellationToken);
         return true;
     }
 
     private async Task<bool> UpdateLiveLeaseAsync(PurchaseTaskLease lease, string sql,
-        CancellationToken cancellationToken, params (string Name, object Value)[] parameters)
+        CancellationToken cancellationToken, string? eventCode, string? diagnostic, params (string Name, object Value)[] parameters)
     {
         await using var connection = await OpenAsync(cancellationToken);
         await using var transaction = await connection.BeginTransactionAsync(IsolationLevel.ReadCommitted, cancellationToken);
@@ -248,6 +262,9 @@ internal sealed class PurchaseWorkerStore(string connectionString)
         if (await update.ExecuteNonQueryAsync(cancellationToken) != 1)
             return false;
 
+        if (eventCode is not null)
+            await PurchaseBatchJournal.AppendAsync(connection, transaction, lease, eventCode, cancellationToken,
+                lease.AttemptNumber, diagnostic: diagnostic);
         await transaction.CommitAsync(cancellationToken);
         return true;
     }

+ 12 - 0
server/Admin.NET.DataPlatform.Worker/README.md

@@ -56,3 +56,15 @@
 新凭据沿用接收接口的 HMAC 签名协议,签名密钥以 Base64 解码,摘要覆盖完整请求体。报文顶层增加 `factoryId`,建议采用十进制字符串以保留长 ID 精度。租户从凭据解析。每批属于一个有效工厂;行内如另有 `factoryId`,须与批次一致。来源沿用所选数据集的已启用版本,在本租户不同工厂间复用同一份配置和凭据。接收回执、原文、采购交接及标准订单保留批次的实际工厂。相同幂等键在同一工厂重试时沿用原批次,不同工厂各自处理。来源授权与版本启用分别管理。
 
 启动新版本 API 前应确保 `1.0.610.sql` 和 `1.0.611.sql` 已校验通过。API 对证据表需要 SELECT、INSERT。发布记录按本批接收时的绑定固定;回执确认与投递完成在同一事务中提交。旧数据仅在归属可证实时补录。
+
+## 批次追溯、原文保留与采购恢复
+
+先在接收和数据层应用 `1.0.624.sql`,并执行 `1.0.624.verify.sql` 核验迁移。先升级库,再部署配套 API、处理 Worker 和投递 Worker。旧批次会显示现有的接收、状态、交接等历史证据。
+
+- 处理和投递身份额外需要 `mdp_ingest_batch_event` 的 INSERT。状态变更和事件在同一个事务中提交,租约心跳继续维护任务行,避免长期处理产生大量重复事件。
+- 管理身份需要读取 Raw、事件、隔离及保留策略,并按发布按钮权限维护 `mdp_ingest_raw_policy`。正常接收写入身份需要将接收事件添入时间线。清理身份需要读取候选关联表、写批次事件,以及更新 Raw 的 `payload` 和 `payload_expired_at` 两列。
+- 普通保留期限为 90 天。发布权限用户可在接收数据集将期限设为 7 到 3650 天。准备好备份和恢复验证后,在调度宿主设 `MdpRawRetention:Enabled=true` 启用到期处置。处置按批保留批次、摘要、幂等键及行定位,将原文字节清空并登记处置时间。在途、失败待决、迁移冻结和采集阻断引用保留原文。
+- 运营页面用批次号查询追溯。试跑权限可以按冻结版本复算并核对二级包摘要。已确认交接的批次可预演缺失两层的影响。发布权限用户提交本次预演指纹及原因后,接收端复核原回执、当前来源写入权和业务行。已存在的匹配结果保持现状,恢复只补缺失的采购行。版本变化、冲突和失效预演会阻断相应补写。
+- 接收身份另外需要读写 `mdp_ingest_purchase_recovery` 的 SELECT、INSERT,并在版本化采购恢复时更新 `mdp_std_purchase_order_version` 的 `stage_id`、`standard_id`。两层写入、版本指针与恢复审计同事务。查询的行级落层 ID 来自交接及恢复回执,并可在相应层按业务键对账。
+
+回切应用前关闭到期处置作业。保留迁移表和历史证据。已按策略处置的原文随备份恢复流程处理。

+ 11 - 3
server/Admin.NET.Web.Entry/Admin.NET.Web.Entry.csproj

@@ -11,9 +11,9 @@
     <GenerateSatelliteAssembliesForCore>true</GenerateSatelliteAssembliesForCore>
     <Copyright>Admin.NET</Copyright>
     <Description>Admin.NET 通用权限开发平台</Description>
-    <AssemblyVersion>1.0.623</AssemblyVersion>
-    <FileVersion>1.0.623</FileVersion>
-    <Version>1.0.623</Version>
+    <AssemblyVersion>1.0.624</AssemblyVersion>
+    <FileVersion>1.0.624</FileVersion>
+    <Version>1.0.624</Version>
   </PropertyGroup>
 
   <ItemGroup>
@@ -1078,6 +1078,14 @@
       <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
       <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
     </None>
+    <None Update="UpdateScripts\1.0.624.sql">
+      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
+    </None>
+    <None Update="UpdateScripts\1.0.624.verify.sql">
+      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
+    </None>
     <None Update="UpdateScripts\MDP-PURCHASE-DISPATCH-GUARDS.ops.sql" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
     <None Update="UpdateScripts\UAT-PLACEHOLDER-MENU-HIDE.ops.sql">
       <CopyToOutputDirectory>Always</CopyToOutputDirectory>

+ 46 - 0
server/Admin.NET.Web.Entry/UpdateScripts/1.0.624.sql

@@ -0,0 +1,46 @@
+-- Apply after the unified ingress, API pull and Edge migrations.
+SET @mdp_raw_expiry_ddl = IF(
+    EXISTS (SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE()
+        AND TABLE_NAME='mdp_ingest_raw_batch' AND COLUMN_NAME='payload_expired_at'),
+    'DO 0', 'ALTER TABLE mdp_ingest_raw_batch ADD COLUMN payload_expired_at DATETIME(6) NULL');
+PREPARE mdp_raw_expiry_stmt FROM @mdp_raw_expiry_ddl;
+EXECUTE mdp_raw_expiry_stmt;
+DEALLOCATE PREPARE mdp_raw_expiry_stmt;
+
+SET @mdp_raw_expiry_index_ddl = IF(
+    EXISTS (SELECT 1 FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=DATABASE()
+        AND TABLE_NAME='mdp_ingest_raw_batch' AND INDEX_NAME='ix_ingest_raw_expiry'),
+    'DO 0', 'ALTER TABLE mdp_ingest_raw_batch ADD INDEX ix_ingest_raw_expiry (payload_expired_at,received_at,batch_id)');
+PREPARE mdp_raw_expiry_index_stmt FROM @mdp_raw_expiry_index_ddl;
+EXECUTE mdp_raw_expiry_index_stmt;
+DEALLOCATE PREPARE mdp_raw_expiry_index_stmt;
+
+CREATE TABLE IF NOT EXISTS mdp_ingest_raw_policy (
+    tenant_id BIGINT NOT NULL, factory_id BIGINT NOT NULL, dataset_id BIGINT NOT NULL,
+    retention_days SMALLINT UNSIGNED NOT NULL, actor_id BIGINT NOT NULL,
+    updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
+    PRIMARY KEY (tenant_id,factory_id,dataset_id),
+    CHECK (retention_days BETWEEN 7 AND 3650)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+CREATE TABLE IF NOT EXISTS mdp_ingest_batch_event (
+    id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
+    batch_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+    tenant_id BIGINT NOT NULL, factory_id BIGINT NOT NULL, dataset_id BIGINT NOT NULL, source_id BIGINT NOT NULL,
+    event_code VARCHAR(40) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+    attempt_number INT NULL, record_count INT NULL,
+    diagnostic VARCHAR(80) CHARACTER SET ascii COLLATE ascii_bin NULL,
+    created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
+    KEY ix_ingest_batch_event (batch_id,tenant_id,factory_id,dataset_id,source_id,id)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+CREATE TABLE IF NOT EXISTS mdp_ingest_purchase_recovery (
+    id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
+    batch_id CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+    tenant_id BIGINT NOT NULL, factory_id BIGINT NOT NULL, dataset_id BIGINT NOT NULL, source_id BIGINT NOT NULL,
+    actor_id BIGINT NOT NULL,
+    preview_digest CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
+    reason VARCHAR(240) NOT NULL, line_results JSON NOT NULL,
+    created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
+    UNIQUE KEY uk_ingest_purchase_recovery (batch_id,preview_digest)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

+ 12 - 0
server/Admin.NET.Web.Entry/UpdateScripts/1.0.624.verify.sql

@@ -0,0 +1,12 @@
+SELECT IF(COUNT(*)=1,1,0) AS ingest_raw_expiry_column
+FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE()
+  AND TABLE_NAME='mdp_ingest_raw_batch' AND COLUMN_NAME='payload_expired_at' AND COLUMN_TYPE='datetime(6)' AND IS_NULLABLE='YES';
+SELECT IF(GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX)='payload_expired_at,received_at,batch_id',1,0) AS ingest_raw_expiry_index
+FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=DATABASE()
+  AND TABLE_NAME='mdp_ingest_raw_batch' AND INDEX_NAME='ix_ingest_raw_expiry';
+SELECT IF(COUNT(*)=3,1,0) AS ingest_lifecycle_tables
+FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB'
+  AND TABLE_NAME IN ('mdp_ingest_raw_policy','mdp_ingest_batch_event','mdp_ingest_purchase_recovery');
+SELECT IF(GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX)='batch_id,preview_digest',1,0) AS ingest_recovery_once
+FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=DATABASE() AND NON_UNIQUE=0
+  AND TABLE_NAME='mdp_ingest_purchase_recovery' AND INDEX_NAME='uk_ingest_purchase_recovery';

+ 26 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/IngestBatchJournal.cs

@@ -0,0 +1,26 @@
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+
+public static class IngestBatchJournal
+{
+    public const string Insert = """
+        INSERT INTO mdp_ingest_batch_event
+            (batch_id,tenant_id,factory_id,dataset_id,source_id,event_code,attempt_number,record_count,diagnostic,created_at)
+        VALUES (@BatchId,@TenantId,@FactoryId,@DatasetId,@SourceId,@EventCode,@Attempt,@Count,@Diagnostic,UTC_TIMESTAMP(6))
+        """;
+
+    public const string RawStored = "RAW_STORED";
+    public const string RawAccepted = "RAW_ACCEPTED";
+    public const string RawRejected = "RAW_REJECTED";
+    public const string RawEmpty = "RAW_EMPTY";
+    public const string RawExpired = "RAW_EXPIRED";
+    public const string WorkerClaimed = "WORKER_CLAIMED";
+    public const string WorkerReclaimed = "WORKER_RECLAIMED";
+    public const string WorkerLeaseExpired = "WORKER_LEASE_EXPIRED";
+    public const string WorkerRetry = "WORKER_RETRY";
+    public const string WorkerFailed = "WORKER_FAILED";
+    public const string RowsIsolated = "ROWS_ISOLATED";
+    public const string PackageFrozen = "PACKAGE_FROZEN";
+    public const string DeliveryRetry = "DELIVERY_RETRY";
+    public const string DeliveryFailed = "DELIVERY_FAILED";
+    public const string DeliveryConfirmed = "DELIVERY_CONFIRMED";
+}

+ 7 - 2
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpApiPullService.Capture.cs

@@ -14,7 +14,7 @@ public sealed partial class MdpApiPullService
         return await Tx(db, async () =>
         {
             var capture = await db.Ado.SqlQuerySingleAsync<ExportRow>("""
-                SELECT b.batch_id AS BatchId,b.payload AS Payload,b.payload_sha256 AS Digest,c.release_id AS ReleaseId
+                SELECT b.batch_id AS BatchId,b.payload AS Payload,b.payload_sha256 AS Digest,c.release_id AS ReleaseId,b.payload_expired_at AS ExpiredAt
                 FROM mdp_connector_api_pull_capture c JOIN mdp_connector_api_pull_run r ON r.run_id=c.run_id
                 JOIN mdp_ingest_raw_batch b ON b.batch_id=c.batch_id AND b.tenant_id=r.tenant_id
                     AND b.factory_id=r.factory_id AND b.dataset_id=r.dataset_id AND b.source_id=r.source_id
@@ -22,6 +22,7 @@ public sealed partial class MdpApiPullService
                     AND r.run_id=@runId AND c.ordinal=@ordinal AND c.attempt=@attempt
                 """, new { tenant, factory, dataset, runId, ordinal, attempt })
                 ?? throw new MdpApiPullException("PULL_CAPTURE_NOT_FOUND");
+            Require(!capture.ExpiredAt.HasValue, "RAW_PAYLOAD_EXPIRED");
             Require(capture.Digest == Hash(capture.Payload), "PULL_FROZEN_PAGE_INVALID");
             await db.Ado.ExecuteCommandAsync("""
                 INSERT INTO mdp_ingest_release_log (dataset_id,release_id,action,actor,detail,created_at)
@@ -34,6 +35,7 @@ public sealed partial class MdpApiPullService
 
     private sealed class ExportRow
     {
+        public DateTime? ExpiredAt { get; set; }
         public string BatchId { get; set; } = "";
         public byte[] Payload { get; set; } = [];
         public string Digest { get; set; } = "";
@@ -76,7 +78,7 @@ public sealed partial class MdpApiPullService
         var captureKey = Encoding.ASCII.GetBytes("\0api-pull-" + captureId);
         var capturedAt = page.FrozenAt is { } frozen ? DateTime.SpecifyKind(frozen, DateTimeKind.Utc) : raw.ReceivedAt.UtcDateTime;
         var receivedAt = new DateTimeOffset(capturedAt.Ticks / 10 * 10, TimeSpan.Zero);
-        await MdpIngestReceiveService.PersistRawAsync(db, raw, [], page.Body!, captureKey, receivedAt, token);
+        await MdpIngestReceiveService.PersistRawWithJournalAsync(db, raw, [], page.Body!, captureKey, receivedAt, token);
         var args = new { runId, ordinal, Attempt = checked(page.Attempt + 1), captureId, profile.Id, profile.ReleaseId,
             page.PositionDigest, page.Digest, page.Effective, page.NextLink, page.LinkDiagnostic, FrozenAt = receivedAt.UtcDateTime };
         await db.Ado.ExecuteCommandAsync("""
@@ -132,7 +134,10 @@ public sealed partial class MdpApiPullService
             """, new { runId, ordinal, page.CaptureId, state = prepared.Events.Count == 0 ? "EMPTY" : "ACCEPTED" });
         Require(changed == 1, "PULL_CAPTURE_CHANGED");
         if (prepared.Events.Count == 0)
+        {
+            await MdpIngestBatchJournal.AppendAsync(db, id, prepared.Batch.Identity, IngestBatchJournal.RawEmpty, 0);
             return;
+        }
 
         var batch = prepared.Batch with { BatchId = id, ReceivedAt = new(DateTime.SpecifyKind(page.ReceivedAt!.Value, DateTimeKind.Utc)) };
         var events = prepared.Events.Select(row => row with { BatchId = id }).ToArray();

+ 7 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpApiPullService.Run.cs

@@ -191,6 +191,13 @@ public sealed partial class MdpApiPullService
                         UPDATE mdp_connector_api_pull_page SET diagnostic=@code
                         WHERE run_id=@runId AND ordinal=@ordinal AND raw_batch_id IS NULL
                         """, failed);
+                    await db.Ado.ExecuteCommandAsync("""
+                        INSERT INTO mdp_ingest_batch_event
+                            (batch_id,tenant_id,factory_id,dataset_id,source_id,event_code,diagnostic,created_at)
+                        SELECT c.batch_id,r.tenant_id,r.factory_id,r.dataset_id,r.source_id,@eventCode,@code,UTC_TIMESTAMP(6)
+                        FROM mdp_connector_api_pull_capture c JOIN mdp_connector_api_pull_run r ON r.run_id=c.run_id
+                        WHERE c.run_id=@runId AND c.ordinal=@ordinal AND c.state='CAPTURED'
+                        """, new { failed.runId, failed.ordinal, failed.code, eventCode = IngestBatchJournal.RawRejected });
                     await db.Ado.ExecuteCommandAsync("""
                         UPDATE mdp_connector_api_pull_capture SET state='REJECTED',diagnostic=@code,changed_at=UTC_TIMESTAMP(6)
                         WHERE run_id=@runId AND ordinal=@ordinal AND state='CAPTURED'

+ 4 - 1
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpEdgeDeviceService.Receive.cs

@@ -138,7 +138,7 @@ public sealed partial class MdpEdgeDeviceService
             };
             var archiveKey = Encoding.ASCII.GetBytes("\0edge-" + batch.BatchId.ToString("D"));
             var captured = preparer.CaptureApiPage(scope, task.SchemaVersion, batch.Body, limits, window) with { BatchId = batch.BatchId };
-            await MdpIngestReceiveService.PersistRawAsync(db, captured, [], batch.Body, archiveKey, captured.ReceivedAt, token);
+            await MdpIngestReceiveService.PersistRawWithJournalAsync(db, captured, [], batch.Body, archiveKey, captured.ReceivedAt, token);
             var confirmation = batch.NextPosition;
             var isCompleted = false;
             PreparedIngestBatch? prepared = null;
@@ -207,6 +207,9 @@ public sealed partial class MdpEdgeDeviceService
                 await MdpIngestReceiveService.PersistAcceptedBatchAsync(db, accepted, key, device.FactoryId, token, useCapturedRaw: true);
             }
 
+            if (count == 0)
+                await MdpIngestBatchJournal.AppendAsync(db, batch.BatchId, scope,
+                    code is null ? IngestBatchJournal.RawEmpty : IngestBatchJournal.RawRejected, 0, code);
             var status = code is not null ? EdgeProtocol.Rejected : count == 0 ? EdgeProtocol.Empty : EdgeProtocol.Accepted;
             var receipt = new EdgeReceipt(batch.BatchId, batch.Digest, status, batch.BatchId, code is null ? confirmation : batch.Position, code, batch.Position);
             await db.Ado.ExecuteCommandAsync("""

+ 14 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestBatchJournal.cs

@@ -0,0 +1,14 @@
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+internal static class MdpIngestBatchJournal
+{
+    internal static Task<int> AppendAsync(ISqlSugarClient db, Guid batchId, IngestDatasetIdentity identity,
+        string eventCode, int? count = null, string? diagnostic = null) =>
+        db.Ado.ExecuteCommandAsync(IngestBatchJournal.Insert, new
+        {
+            BatchId = batchId.ToString("D"), identity.TenantId, identity.FactoryId, identity.DatasetId, identity.SourceId,
+            EventCode = eventCode, Attempt = (int?)null, Count = count, Diagnostic = diagnostic
+        });
+}

+ 144 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestBatchTraceService.cs

@@ -0,0 +1,144 @@
+using System.Globalization;
+using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+public sealed class MdpIngestBatchTraceService(ISqlSugarClient host, MdpPurchaseHandoffService handoff) : ITransient
+{
+    internal static readonly JsonSerializerOptions Wire = new(JsonSerializerDefaults.Web);
+
+    internal async Task<object> ReadAsync(BatchAccess scope, bool canRestore, CancellationToken token)
+    {
+        using var db = MdpIngestDatabase.Open(host);
+        db.Ado.CancellationToken = token;
+        var batch = await ReadBatchAsync(db, scope);
+        var version = JsonSerializer.Deserialize<IngestVersionSnapshot>(batch.VersionSnapshot, Wire);
+        var events = await db.Ado.SqlQueryAsync<TraceEvent>("""
+            SELECT event_code AS Code,attempt_number AS Attempt,record_count AS RecordCount,
+                diagnostic AS Diagnostic,created_at AS OccurredAt
+            FROM mdp_ingest_batch_event
+            WHERE batch_id=@BatchId AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId
+            ORDER BY created_at,id
+            """, batch.SqlArguments);
+
+        var captured = events.Any(row => row.Code == IngestBatchJournal.RawStored);
+        if (!captured)
+            events.Insert(0, new() { Code = "RAW_STORED_HISTORICAL", OccurredAt = batch.ReceivedAt });
+        var lines = await db.Ado.SqlQueryAsync<TraceLine>("""
+            SELECT e.raw_event_id AS RawEventId,e.record_ordinal AS Ordinal,e.source_position AS SourcePosition,
+                e.source_business_key AS BusinessKey,e.payload_sha256 AS Sha256,e.source_updated_at AS SourceUpdatedAt
+            FROM mdp_ingest_raw_event e WHERE e.batch_id=@BatchId ORDER BY e.record_ordinal
+            """, batch.SqlArguments);
+        var isolations = await db.Ado.SqlQueryAsync<TraceIsolation>("""
+            SELECT raw_event_id AS RawEventId,field_name AS Field,reason_code AS Code
+            FROM mdp_ingest_worker_quarantine
+            WHERE batch_id=@BatchId AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId
+            ORDER BY record_ordinal,field_name,reason_code
+            """, batch.SqlArguments);
+
+        var delivery = await handoff.ReadTraceAsync(batch, token);
+        if (!captured && batch.WorkerStatus is not null && batch.WorkerUpdatedAt is { } updated
+            && !events.Any(row => row.Code.StartsWith("WORKER_", StringComparison.Ordinal)))
+            events.Add(new() { Code = "WORKER_STATE_HISTORICAL", OccurredAt = updated, Diagnostic = batch.WorkerStatus });
+        if (batch.AcknowledgedAt is { } acknowledged && !events.Any(row => row.Code == IngestBatchJournal.DeliveryConfirmed))
+            events.Add(new() { Code = "DELIVERY_CONFIRMED_HISTORICAL", OccurredAt = acknowledged });
+        if (delivery?.CreatedAt is { } landed)
+            events.Add(new() { Code = "PURCHASE_LANDED", OccurredAt = landed });
+        if (delivery is not null)
+            events.AddRange(delivery.Recoveries.Select(row => new TraceEvent
+                { Code = "PURCHASE_RECOVERED", OccurredAt = row.CreatedAt }));
+        return new
+        {
+            batch.BatchId, batch.SourceCode, batch.DatasetKey, batch.PayloadSha256, batch.WorkerStatus,
+            factoryId = batch.FactoryId.ToString(CultureInfo.InvariantCulture),
+            receivedAt = Utc(batch.ReceivedAt), payloadExpiredAt = UtcOptional(batch.PayloadExpiredAt),
+            leaseUntil = UtcOptional(batch.LeaseUntil), workerUpdatedAt = UtcOptional(batch.WorkerUpdatedAt),
+            sourceWindow = batch.SourceWindow is null ? null : JsonSerializer.Deserialize<IngestSourceWindow>(batch.SourceWindow, Wire),
+            sourceSchema = version?.SourceSchema, rawSchema = version?.RawSchema, handoffSchema = version?.HandoffSchema,
+            version?.MappingVersion, version?.ConfigVersion, version?.RuleVersion,
+            partialHistory = !captured,
+            timeline = events.OrderBy(row => row.OccurredAt).Select(row => new
+                { row.Code, row.Attempt, row.RecordCount, row.Diagnostic, occurredAt = Utc(row.OccurredAt) }),
+            lines, isolations, delivery, canRestore
+        };
+    }
+
+    internal static async Task<StoredIngestBatch> ReadBatchAsync(ISqlSugarClient db, BatchAccess scope, bool lockBatch = false)
+    {
+        var batch = await db.Ado.SqlQuerySingleAsync<StoredIngestBatch>("""
+            SELECT b.batch_id AS BatchId,b.tenant_id AS TenantId,b.factory_id AS FactoryId,b.dataset_id AS DatasetId,
+                b.source_id AS SourceId,b.source_code AS SourceCode,b.dataset_key AS DatasetKey,b.received_at AS ReceivedAt,
+                b.payload_sha256 AS PayloadSha256,b.version_snapshot AS VersionSnapshot,b.source_window AS SourceWindow,
+                b.accepted_record_count AS RecordCount,b.payload_expired_at AS PayloadExpiredAt,
+                t.status AS WorkerStatus,t.lease_until_utc AS LeaseUntil,t.updated_at_utc AS WorkerUpdatedAt,
+                r.acknowledged_at AS AcknowledgedAt
+            FROM mdp_ingest_raw_batch b
+            JOIN mdp_ingest_dataset d ON d.id=b.dataset_id AND d.tenant_id=b.tenant_id AND d.factory_id=@ConfigurationFactory
+            LEFT JOIN mdp_ingest_receive_task t ON t.batch_id=b.batch_id AND t.tenant_id=b.tenant_id AND t.factory_id=b.factory_id
+                AND t.source_id=b.source_id AND t.dataset_id=b.dataset_id
+            LEFT JOIN mdp_ingest_release_batch r ON r.batch_id=b.batch_id AND r.tenant_id=b.tenant_id AND r.factory_id=b.factory_id
+                AND r.source_id=b.source_id AND r.dataset_id=b.dataset_id
+            WHERE b.batch_id=@BatchId AND b.tenant_id=@TenantId AND b.dataset_id=@DatasetId
+                AND FIND_IN_SET(CAST(b.factory_id AS CHAR),@AllowedFactories)>0
+            """ + (lockBatch ? " FOR UPDATE OF b" : ""), scope.SqlArguments);
+        return batch ?? throw new MdpIngestHttpException(404, "RAW_BATCH_NOT_FOUND");
+    }
+
+    private static DateTime Utc(DateTime value) => DateTime.SpecifyKind(value, DateTimeKind.Utc);
+    private static DateTime? UtcOptional(DateTime? value) => value.HasValue ? Utc(value.Value) : null;
+
+    private sealed class TraceEvent
+    {
+        public string Code { get; set; } = "";
+        public int? Attempt { get; set; }
+        public int? RecordCount { get; set; }
+        public string? Diagnostic { get; set; }
+        public DateTime OccurredAt { get; set; }
+    }
+
+    private sealed class TraceLine
+    {
+        public Guid RawEventId { get; set; }
+        public int Ordinal { get; set; }
+        public string SourcePosition { get; set; } = "";
+        public string? BusinessKey { get; set; }
+        public string Sha256 { get; set; } = "";
+        public string? SourceUpdatedAt { get; set; }
+    }
+
+    private sealed class TraceIsolation
+    {
+        public Guid RawEventId { get; set; }
+        public string Field { get; set; } = "";
+        public string Code { get; set; } = "";
+    }
+}
+
+internal sealed record BatchAccess(string BatchId, long TenantId, long ConfigurationFactory, long DatasetId, string AllowedFactories)
+{
+    internal object SqlArguments => new { BatchId, TenantId, ConfigurationFactory, DatasetId, AllowedFactories };
+}
+
+internal sealed class StoredIngestBatch
+{
+    public string BatchId { get; set; } = "";
+    public long TenantId { get; set; }
+    public long FactoryId { get; set; }
+    public long SourceId { get; set; }
+    public long DatasetId { get; set; }
+    public string SourceCode { get; set; } = "";
+    public string DatasetKey { get; set; } = "";
+    public string PayloadSha256 { get; set; } = "";
+    public string VersionSnapshot { get; set; } = "";
+    public string? SourceWindow { get; set; }
+    public int RecordCount { get; set; }
+    public DateTime ReceivedAt { get; set; }
+    public DateTime? PayloadExpiredAt { get; set; }
+    public string? WorkerStatus { get; set; }
+    public DateTime? LeaseUntil { get; set; }
+    public DateTime? WorkerUpdatedAt { get; set; }
+    public DateTime? AcknowledgedAt { get; set; }
+
+    internal object SqlArguments => new { BatchId, TenantId, FactoryId, DatasetId, SourceId };
+}

+ 1 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestDatasetController.ApiPull.cs

@@ -108,6 +108,7 @@ public sealed partial class MdpIngestDatasetController
                 var status = error.Code switch
                 {
                     "PULL_PROFILE_NOT_FOUND" or "PULL_CAPTURE_NOT_FOUND" => 404,
+                    "RAW_PAYLOAD_EXPIRED" => 410,
                     "PULL_TARGET_FORBIDDEN" or "PULL_ADDRESS_FORBIDDEN" or "PULL_SOURCE_NOT_AUTHORIZED" or "PULL_CREDENTIAL_FORBIDDEN" => 403,
                     "PULL_LOCAL_RATE_LIMITED" or "PULL_SOURCE_RATE_LIMITED" => 429,
                     "PULL_TIMEOUT" => 504,

+ 73 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestDatasetController.Trace.cs

@@ -0,0 +1,73 @@
+using System.Data.Common;
+using System.Globalization;
+using System.Text.Json;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+public sealed partial class MdpIngestDatasetController
+{
+    [HttpGet("{id:long}/raw-retention")]
+    public Task<IActionResult> ReadRawRetention(long id, long? factoryId, [FromServices] MdpIngestRawRetentionService retention) =>
+        LifecycleQuery(id, factoryId, TrialPermission, async scope => new
+        {
+            days = await retention.ReadDaysAsync(scope.TenantId, scope.FactoryId, id),
+            canChange = await Can(PublishPermission)
+        });
+
+    [HttpPut("{id:long}/raw-retention"), RequestSizeLimit(4096)]
+    public Task<IActionResult> SetRawRetention(long id, long? factoryId, RawRetentionInput input,
+        [FromServices] MdpIngestRawRetentionService retention) =>
+        LifecycleQuery(id, factoryId, PublishPermission, async scope =>
+        {
+            await retention.SetDaysAsync(scope.TenantId, scope.FactoryId, id, input.Days, user.UserId);
+            return new { input.Days };
+        });
+
+    [HttpGet("{id:long}/batches/{batchId:guid}/trace")]
+    public Task<IActionResult> ReadBatchTrace(long id, Guid batchId, long? factoryId,
+        [FromServices] MdpIngestBatchTraceService trace, CancellationToken token) =>
+        LifecycleQuery(id, factoryId, TrialPermission,
+            async scope => await trace.ReadAsync(await BatchScope(scope, id, batchId), await Can(PublishPermission), token));
+
+    [HttpPost("{id:long}/batches/{batchId:guid}/replay-preview")]
+    public Task<IActionResult> PreviewBatchReplay(long id, Guid batchId, long? factoryId,
+        [FromServices] MdpIngestReplayService replay, CancellationToken token) =>
+        LifecycleQuery(id, factoryId, TrialPermission,
+            async scope => await replay.PreviewAsync(await BatchScope(scope, id, batchId), token));
+
+    [HttpPost("{id:long}/batches/{batchId:guid}/restore"), RequestSizeLimit(4096)]
+    public Task<IActionResult> RestoreBatch(long id, Guid batchId, long? factoryId, IngestReplayApproval input,
+        [FromServices] MdpIngestReplayService replay, CancellationToken token) =>
+        LifecycleQuery(id, factoryId, PublishPermission,
+            async scope => await replay.RestoreAsync(await BatchScope(scope, id, batchId), input, user.UserId, token));
+
+    private Task<IActionResult> LifecycleQuery(long id, long? factoryId, string permission, Func<DatasetScope, Task<object>> action) =>
+        WithScope(factoryId, async scope =>
+        {
+            if (!await Can(permission)) return Forbid();
+            if (!await Datasets(scope).AnyAsync(row => row.Id == id)) return NotFound();
+            Response.Headers.CacheControl = "no-store";
+            try
+            {
+                var value = await action(scope);
+                return Content(JsonSerializer.Serialize(value, MdpIngestBatchTraceService.Wire), "application/json; charset=utf-8");
+            }
+            catch (MdpIngestHttpException error)
+            {
+                return StatusCode(error.StatusCode, new { error.Code });
+            }
+            catch (Exception error) when (error is DbException or SqlSugarException)
+            {
+                return StatusCode(503, new { code = "RAW_LIFECYCLE_UNAVAILABLE" });
+            }
+        });
+
+    private async Task<BatchAccess> BatchScope(DatasetScope scope, long datasetId, Guid batchId)
+    {
+        var factories = await AuthorizedFactories(scope.TenantId);
+        return new(batchId.ToString("D"), scope.TenantId, scope.FactoryId, datasetId,
+            string.Join(',', factories.Select(row => row.Id.ToString(CultureInfo.InvariantCulture))));
+    }
+}
+
+public sealed record RawRetentionInput(int Days);

+ 94 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestRawRetentionService.cs

@@ -0,0 +1,94 @@
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+public sealed class MdpIngestRawRetentionService(ISqlSugarClient host) : ITransient
+{
+    public const int DefaultDays = 90;
+    internal const int BatchLimit = 50;
+
+    public async Task<int> ReadDaysAsync(long tenantId, long factoryId, long datasetId)
+    {
+        using var db = MdpIngestDatabase.Open(host);
+        return await db.Ado.SqlQuerySingleAsync<int?>("""
+            SELECT retention_days FROM mdp_ingest_raw_policy
+            WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId
+            """, new { tenantId, factoryId, datasetId }) ?? DefaultDays;
+    }
+
+    public async Task SetDaysAsync(long tenantId, long factoryId, long datasetId, int days, long actor)
+    {
+        if (days is < 7 or > 3650)
+            throw new MdpIngestHttpException(400, "RAW_RETENTION_INVALID");
+        using var db = MdpIngestDatabase.Open(host);
+        await db.Ado.ExecuteCommandAsync("""
+            INSERT INTO mdp_ingest_raw_policy (tenant_id,factory_id,dataset_id,retention_days,actor_id)
+            VALUES (@TenantId,@FactoryId,@DatasetId,@Days,@Actor)
+            ON DUPLICATE KEY UPDATE retention_days=@Days,actor_id=@Actor,updated_at=UTC_TIMESTAMP(6)
+            """, new { tenantId, factoryId, datasetId, days, actor });
+    }
+
+    public async Task<int> ExpireAsync(CancellationToken token)
+    {
+        using var db = MdpIngestDatabase.Open(host);
+        db.Ado.CancellationToken = token;
+        var result = await db.Ado.UseTranAsync(async () =>
+        {
+            var candidates = await db.Ado.SqlQueryAsync<ExpiryCandidate>("""
+                SELECT b.batch_id AS BatchId,b.tenant_id AS TenantId,b.factory_id AS FactoryId,
+                    b.source_id AS SourceId,b.dataset_id AS DatasetId
+                FROM mdp_ingest_raw_batch b
+                JOIN mdp_ingest_dataset d ON d.id=b.dataset_id AND d.tenant_id=b.tenant_id
+                LEFT JOIN mdp_ingest_raw_policy p ON p.tenant_id=d.tenant_id AND p.factory_id=d.factory_id AND p.dataset_id=d.id
+                LEFT JOIN mdp_ingest_receive_task t ON t.batch_id=b.batch_id
+                    AND t.tenant_id=b.tenant_id AND t.factory_id=b.factory_id AND t.dataset_id=b.dataset_id AND t.source_id=b.source_id
+                WHERE b.payload_expired_at IS NULL
+                  AND b.received_at < DATE_SUB(UTC_TIMESTAMP(6), INTERVAL 7 DAY)
+                  AND b.received_at < DATE_SUB(UTC_TIMESTAMP(6), INTERVAL COALESCE(p.retention_days,@DefaultDays) DAY)
+                  AND (t.status IN ('SUCCEEDED','PARTIAL','QUARANTINED') OR (t.batch_id IS NULL AND b.accepted_record_count=0))
+                  AND NOT EXISTS (
+                      SELECT 1 FROM mdp_ingest_purchase_dispatch x WHERE x.batch_id=b.batch_id AND x.status<>'DONE')
+                  AND NOT EXISTS (
+                      SELECT 1 FROM mdp_connector_api_pull_capture c
+                      JOIN mdp_connector_api_pull_run r ON r.run_id=c.run_id
+                      WHERE c.batch_id=b.batch_id AND r.active_slot=1 AND c.state IN ('CAPTURED','REJECTED'))
+                  AND NOT EXISTS (
+                      SELECT 1 FROM mdp_edge_api_rejected_page e WHERE e.batch_id=b.batch_id AND e.settlement IS NULL)
+                  AND NOT EXISTS (
+                      SELECT 1 FROM mdp_connector_relational_sync_run r WHERE r.tenant_id=b.tenant_id AND r.factory_id=b.factory_id
+                          AND r.dataset_id=b.dataset_id AND r.source_id=b.source_id AND r.active_slot=1)
+                  AND NOT EXISTS (
+                      SELECT 1 FROM mdp_purchase_migration_scope m WHERE m.tenant_id=b.tenant_id AND m.factory_id=b.factory_id
+                          AND m.dataset_id=b.dataset_id AND m.new_source_id=b.source_id AND m.frozen=1)
+                ORDER BY b.received_at,b.batch_id LIMIT @BatchLimit FOR UPDATE OF b SKIP LOCKED
+                """, new { DefaultDays, BatchLimit });
+
+            foreach (var row in candidates)
+            {
+                token.ThrowIfCancellationRequested();
+                await db.Ado.ExecuteCommandAsync("""
+                    UPDATE mdp_ingest_raw_batch SET payload=X'',payload_expired_at=UTC_TIMESTAMP(6)
+                    WHERE batch_id=@BatchId AND payload_expired_at IS NULL
+                    """, new { row.BatchId });
+                await db.Ado.ExecuteCommandAsync(IngestBatchJournal.Insert, new
+                {
+                    row.BatchId, row.TenantId, row.FactoryId, row.DatasetId, row.SourceId,
+                    EventCode = IngestBatchJournal.RawExpired, Attempt = (int?)null, Count = (int?)null, Diagnostic = (string?)null
+                });
+            }
+            return candidates.Count;
+        });
+        if (!result.IsSuccess)
+            throw result.ErrorException ?? new InvalidOperationException("Raw retention transaction failed.");
+        return result.Data;
+    }
+
+    private sealed class ExpiryCandidate
+    {
+        public string BatchId { get; set; } = "";
+        public long TenantId { get; set; }
+        public long FactoryId { get; set; }
+        public long SourceId { get; set; }
+        public long DatasetId { get; set; }
+    }
+}

+ 9 - 1
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestReceiveService.cs

@@ -205,7 +205,7 @@ public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpInges
         }
         else
         {
-            await PersistRawAsync(db, batch, prepared.Events, batch.Payload.ToArray(), idempotencyKey, receivedAt, cancellationToken);
+            await PersistRawWithJournalAsync(db, batch, prepared.Events, batch.Payload.ToArray(), idempotencyKey, receivedAt, cancellationToken);
         }
 
         // 发布与接收都锁定同一数据集行;同版本重新发布后也能追溯本批当时的发布记录。
@@ -235,9 +235,17 @@ public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpInges
             });
 
         cancellationToken.ThrowIfCancellationRequested();
+        await MdpIngestBatchJournal.AppendAsync(db, batch.BatchId, batch.Identity, IngestBatchJournal.RawAccepted, batch.AcceptedRowCount);
         return new MdpIngestReceipt(batch.BatchId, Accepted, batch.AcceptedRowCount, batch.Versions.SourceSchema.Version, receivedAt);
     }
 
+    internal static async Task PersistRawWithJournalAsync(ISqlSugarClient db, RawIngestBatch batch,
+        IReadOnlyList<RawIngestEvent> events, byte[] payload, byte[] idempotencyKey, DateTimeOffset receivedAt, CancellationToken token)
+    {
+        await PersistRawAsync(db, batch, events, payload, idempotencyKey, receivedAt, token);
+        await MdpIngestBatchJournal.AppendAsync(db, batch.BatchId, batch.Identity, IngestBatchJournal.RawStored);
+    }
+
     internal static async Task PersistRawAsync(ISqlSugarClient db, RawIngestBatch batch,
         IReadOnlyList<RawIngestEvent> events, byte[] payload, byte[] idempotencyKey, DateTimeOffset receivedAt, CancellationToken token)
     {

+ 115 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestReplayService.cs

@@ -0,0 +1,115 @@
+using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+public sealed class MdpIngestReplayService(ISqlSugarClient host, MdpPurchaseHandoffService handoff) : ITransient
+{
+    internal Task<IngestReplayPreview> PreviewAsync(BatchAccess scope, CancellationToken token) =>
+        WithFrozenAsync(scope, async (batch, converted, digest) =>
+        {
+            var package = converted.Package;
+            var snapshotMatches = string.Equals(digest, package.ComputeDigest(), StringComparison.Ordinal);
+            var recovery = snapshotMatches
+                ? await handoff.PreviewRestoreAsync(batch, package, token)
+                : null;
+            return new IngestReplayPreview(package.PackageVersion, package.SourceSchemaVersion, package.MappingVersion,
+                converted.Quarantines.Count, package.Items.Count, digest, package.ComputeDigest(), snapshotMatches, recovery);
+        }, token);
+
+    internal Task<PurchaseRecoveryResult> RestoreAsync(BatchAccess scope, IngestReplayApproval approval, long actor, CancellationToken token)
+    {
+        var reason = approval.Reason?.Trim();
+        if (approval.PreviewDigest is not { Length: 64 } || !approval.PreviewDigest.All(Uri.IsHexDigit)
+            || reason is not { Length: > 0 and <= 240 } || reason.Any(char.IsControl) || actor <= 0)
+            throw new MdpIngestHttpException(400, "RAW_REPLAY_APPROVAL_INVALID");
+
+        return WithFrozenAsync(scope, async (batch, converted, digest) =>
+        {
+            if (digest != converted.Package.ComputeDigest())
+                throw new MdpIngestHttpException(409, "RAW_REPLAY_DIGEST_MISMATCH");
+            return await handoff.RestoreAsync(batch, converted.Package, approval.PreviewDigest, reason, actor, token);
+        }, token);
+    }
+
+    private async Task<T> WithFrozenAsync<T>(BatchAccess scope,
+        Func<StoredIngestBatch, PurchaseBatchProcessingResult, string?, Task<T>> action, CancellationToken token)
+    {
+        using var db = MdpIngestDatabase.Open(host);
+        db.Ado.CancellationToken = token;
+        // Retention and replay serialize on the Raw row. The receiver locks the original
+        // receipt and target rows on its separate, least-privilege connection.
+        var tx = await db.Ado.UseTranAsync(async () =>
+        {
+            var batch = await MdpIngestBatchTraceService.ReadBatchAsync(db, scope, lockBatch: true);
+            if (batch.PayloadExpiredAt.HasValue)
+                throw new MdpIngestHttpException(410, "RAW_PAYLOAD_EXPIRED");
+            if (batch.WorkerStatus is not ("SUCCEEDED" or "PARTIAL" or "QUARANTINED"))
+                throw new MdpIngestHttpException(409, "RAW_REPLAY_BATCH_NOT_COMPLETE");
+
+            var body = await db.Ado.SqlQuerySingleAsync<FrozenPayload>("""
+                SELECT b.payload AS Payload,t.handoff_package_sha256 AS Digest
+                FROM mdp_ingest_raw_batch b JOIN mdp_ingest_receive_task t ON t.batch_id=b.batch_id
+                  AND t.tenant_id=b.tenant_id AND t.factory_id=b.factory_id AND t.dataset_id=b.dataset_id AND t.source_id=b.source_id
+                WHERE b.batch_id=@BatchId
+                """, batch.SqlArguments);
+            var rows = await db.Ado.SqlQueryAsync<FrozenRow>("""
+                SELECT raw_event_id AS RawEventId,record_ordinal AS Ordinal,object_code AS ObjectCode,
+                    source_position AS SourcePosition,payload_offset AS PayloadOffset,payload_length AS PayloadLength,
+                    payload_sha256 AS PayloadSha256,source_business_key AS BusinessKey,source_updated_at AS SourceUpdatedAt
+                FROM mdp_ingest_raw_event WHERE batch_id=@BatchId ORDER BY record_ordinal
+                """, batch.SqlArguments);
+            var id = Guid.Parse(batch.BatchId);
+            var identity = new IngestDatasetIdentity(batch.TenantId, batch.FactoryId, batch.SourceId, batch.DatasetId,
+                batch.SourceCode, batch.DatasetKey);
+            PurchaseBatchProcessingResult converted;
+            try
+            {
+                if (body is null || rows.Count == 0 || rows.Any(row => row.ObjectCode != "PURCHASE_ORDER"))
+                    throw new MdpIngestHttpException(409, "RAW_REPLAY_OBJECT_UNSUPPORTED");
+                var versions = JsonSerializer.Deserialize<IngestVersionSnapshot>(batch.VersionSnapshot, MdpIngestBatchTraceService.Wire)
+                    ?? throw new InvalidDataException("Raw version snapshot is missing.");
+                var window = batch.SourceWindow is null ? null
+                    : JsonSerializer.Deserialize<IngestSourceWindow>(batch.SourceWindow, MdpIngestBatchTraceService.Wire);
+                var rawBatch = new RawIngestBatch(id, identity, new DateTimeOffset(DateTime.SpecifyKind(batch.ReceivedAt, DateTimeKind.Utc)),
+                    versions, batch.RecordCount, body.Payload, batch.PayloadSha256, window);
+                var rawEvents = rows.Select(row => new RawIngestEvent(row.RawEventId, id, row.Ordinal, row.ObjectCode,
+                    row.SourcePosition, row.PayloadOffset, row.PayloadLength, row.PayloadSha256, row.BusinessKey, row.SourceUpdatedAt)).ToArray();
+                converted = PurchaseBatchProcessor.Process(new(rawBatch, rawEvents), string.Empty);
+            }
+            catch (Exception error) when (error is JsonException or InvalidDataException or ArgumentException or IngestContractException)
+            {
+                throw new MdpIngestHttpException(409, "RAW_FROZEN_SNAPSHOT_UNAVAILABLE");
+            }
+            token.ThrowIfCancellationRequested();
+            return await action(batch, converted, body.Digest);
+        });
+        if (!tx.IsSuccess)
+            throw tx.ErrorException ?? new InvalidOperationException("Raw replay read transaction failed.");
+        return tx.Data;
+    }
+
+    private sealed class FrozenPayload
+    {
+        public byte[] Payload { get; set; } = [];
+        public string? Digest { get; set; }
+    }
+
+    private sealed class FrozenRow
+    {
+        public Guid RawEventId { get; set; }
+        public int Ordinal { get; set; }
+        public string ObjectCode { get; set; } = "";
+        public string SourcePosition { get; set; } = "";
+        public int PayloadOffset { get; set; }
+        public int PayloadLength { get; set; }
+        public string PayloadSha256 { get; set; } = "";
+        public string? BusinessKey { get; set; }
+        public string? SourceUpdatedAt { get; set; }
+    }
+}
+
+public sealed record IngestReplayApproval(string PreviewDigest, string Reason);
+
+internal sealed record IngestReplayPreview(string PackageVersion, string SourceSchemaVersion, string MappingVersion,
+    int IsolatedCount, int AcceptedCount, string? OriginalDigest, string CalculatedDigest, bool DigestMatches, PurchaseRecoveryPreview? Recovery);

+ 3 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestServiceCollectionExtensions.cs

@@ -13,6 +13,9 @@ public static class MdpIngestServiceCollectionExtensions
         services.AddScoped<MdpApiPullService>();
         services.AddScoped<MdpEdgeDeviceService>();
         services.AddTransient<MdpIngestBatchStatusService>();
+        services.AddTransient<MdpIngestBatchTraceService>();
+        services.AddTransient<MdpIngestRawRetentionService>();
+        services.AddTransient<MdpIngestReplayService>();
         services.AddScoped<MdpIngestAdmissionStore>();
         services.AddSingleton<MdpIngestExternalIdentities>();
         services.AddHttpClient(MdpIngestExternalIdentities.MetadataClient, client => client.Timeout = TimeSpan.FromSeconds(8))

+ 261 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpPurchaseHandoffService.Recovery.cs

@@ -0,0 +1,261 @@
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+public sealed partial class MdpPurchaseHandoffService
+{
+    private const string RecoveryReceiptSql = """
+        SELECT payload_sha256 AS PayloadSha256,digest_format AS DigestFormat,line_results AS LineResults,
+            package_version AS PackageVersion,created_at AS CreatedAt
+        FROM mdp_ingest_handoff_receipt
+        WHERE batch_id=@BatchId AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId
+        """;
+
+    internal async Task<PurchaseTrace?> ReadTraceAsync(StoredIngestBatch batch, CancellationToken token)
+    {
+        if (string.IsNullOrWhiteSpace(settings["MDP_PURCHASE_RECEIVER_MYSQL"]))
+            return null;
+        using var db = OpenBusinessDatabase();
+        db.Ado.CancellationToken = token;
+        var receipt = await db.Ado.SqlQuerySingleAsync<RecoveryReceipt>(RecoveryReceiptSql, batch.SqlArguments);
+        if (receipt is null) return null;
+        var history = await db.Ado.SqlQueryAsync<RecoveryAudit>("""
+            SELECT CAST(actor_id AS CHAR) AS Actor,reason AS Reason,line_results AS LineResults,created_at AS CreatedAt
+            FROM mdp_ingest_purchase_recovery
+            WHERE batch_id=@BatchId AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId
+            ORDER BY id DESC LIMIT 100
+            """, batch.SqlArguments);
+        return new(receipt.PackageVersion, receipt.PayloadSha256, Utc(receipt.CreatedAt), ReceiptLines(receipt).Select(ToTrace).ToList(),
+            history.Select(row => new PurchaseRecoveryTrace(row.Actor, row.Reason, Utc(row.CreatedAt),
+                (JsonSerializer.Deserialize<List<LineResult>>(row.LineResults, WireJson) ?? []).Select(ToTrace).ToList())).ToList());
+    }
+
+    internal async Task<PurchaseRecoveryPreview?> PreviewRestoreAsync(StoredIngestBatch batch, PurchaseHandoffPackage package,
+        CancellationToken token)
+    {
+        if (string.IsNullOrWhiteSpace(settings["MDP_PURCHASE_RECEIVER_MYSQL"]))
+            return null;
+        using var db = OpenBusinessDatabase();
+        db.Ado.CancellationToken = token;
+        var tx = await db.Ado.UseTranAsync(async () =>
+        {
+            var receipt = await db.Ado.SqlQuerySingleAsync<RecoveryReceipt>(RecoveryReceiptSql + " FOR SHARE", batch.SqlArguments);
+            if (receipt is null) return null;
+            VerifyRecoveryReceipt(package, receipt);
+            var lines = await InspectRecoveryAsync(db, package, receipt, token);
+            return Preview(package, lines, await RecoveryRevisionAsync(db, batch));
+        });
+        if (!tx.IsSuccess) throw tx.ErrorException ?? Unavailable();
+        return tx.Data;
+    }
+
+    internal async Task<PurchaseRecoveryResult> RestoreAsync(StoredIngestBatch batch, PurchaseHandoffPackage package,
+        string previewDigest, string reason, long actor, CancellationToken token)
+    {
+        using var db = OpenBusinessDatabase();
+        db.Ado.CancellationToken = token;
+        var tx = await db.Ado.UseTranAsync(async () =>
+        {
+            var receipt = await db.Ado.SqlQuerySingleAsync<RecoveryReceipt>(RecoveryReceiptSql + " FOR UPDATE", batch.SqlArguments)
+                ?? throw Error(409, "RAW_REPLAY_RECEIPT_MISSING");
+            VerifyRecoveryReceipt(package, receipt);
+
+            var prior = await db.Ado.SqlQuerySingleAsync<string>("""
+                SELECT line_results FROM mdp_ingest_purchase_recovery WHERE batch_id=@BatchId AND preview_digest=@PreviewDigest
+                  AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId
+                """, new { batch.BatchId, batch.TenantId, batch.FactoryId, batch.DatasetId, batch.SourceId, previewDigest });
+            if (prior is not null)
+                return Result(prior);
+
+            // Lock the original source authority before taking business row locks (same order as ordinary handoff).
+            var migration = await ValidateWriterAsync(db, package);
+            MdpPurchaseMigrationStore.RequireAdmission(migration, MdpPurchaseMigrationStore.Unified);
+            var lines = await InspectRecoveryAsync(db, package, receipt, token);
+            var preview = Preview(package, lines, await RecoveryRevisionAsync(db, batch));
+            if (preview.Digest != previewDigest || !preview.CanRestore)
+                throw Error(409, "RAW_REPLAY_PREVIEW_CHANGED");
+
+            var restored = new List<LineResult>();
+            foreach (var line in lines.Where(row => row.NeedsRestore))
+            {
+                token.ThrowIfCancellationRequested();
+                var outcome = await WriteLineAsync(db, package, batch.BatchId, line.Item);
+                if (outcome.Status != "WRITTEN" || outcome.StageId is null || outcome.StandardId is null)
+                    throw Error(409, "RAW_REPLAY_TARGET_CONFLICT");
+
+                if (line.Item.SourceChange is { } change)
+                {
+                    var updated = await db.Ado.ExecuteCommandAsync("""
+                        UPDATE mdp_std_purchase_order_version SET stage_id=@StageId,standard_id=@StandardId
+                        WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND po_no=@PoNo AND po_line=@PoLine
+                          AND source_id=@SourceId AND dataset_id=@DatasetId AND source_generation=@Generation
+                          AND source_version=@Version AND is_deleted=0
+                        """, new { outcome.StageId, outcome.StandardId, package.TenantId, package.FactoryId,
+                            line.Item.PoNo, line.Item.PoLine, package.SourceId, package.DatasetId, change.Generation, change.Version });
+                    if (updated != 1)
+                        throw Error(409, "RAW_REPLAY_VERSION_CHANGED");
+                }
+
+                if (migration is not null)
+                {
+                    var traceKey = "restore-" + Convert.ToHexString(SHA256.HashData(
+                        System.Text.Encoding.UTF8.GetBytes(previewDigest + line.Item.RawEventId.ToString("D")))).ToLowerInvariant();
+                    await MdpPurchaseMigrationWriter.RecordVersionedAsync(db, migration, line.Item, batch.BatchId, outcome, traceKey);
+                }
+                restored.Add(new(line.Item.RawEventId, "RESTORED", outcome.StageId, outcome.StandardId));
+            }
+
+            var json = JsonSerializer.Serialize(restored, WireJson);
+            await db.Ado.ExecuteCommandAsync("""
+                INSERT INTO mdp_ingest_purchase_recovery
+                  (batch_id,tenant_id,factory_id,dataset_id,source_id,actor_id,preview_digest,reason,line_results,created_at)
+                VALUES (@BatchId,@TenantId,@FactoryId,@DatasetId,@SourceId,@Actor,@PreviewDigest,@Reason,@Json,UTC_TIMESTAMP(6))
+                """, new { batch.BatchId, batch.TenantId, batch.FactoryId, batch.DatasetId, batch.SourceId, actor, previewDigest, reason, json });
+            token.ThrowIfCancellationRequested();
+            return Result(json);
+        });
+        if (!tx.IsSuccess) throw tx.ErrorException ?? Unavailable();
+        return tx.Data;
+    }
+
+    private void VerifyRecoveryReceipt(PurchaseHandoffPackage package, RecoveryReceipt receipt)
+    {
+        if (receipt.PackageVersion != package.PackageVersion
+            || (receipt.PayloadSha256 != package.ComputeDigest()
+                && !(receipt.DigestFormat == 1 && MatchesLegacyReceipt(package, receipt.PayloadSha256))))
+            throw Error(409, "RAW_REPLAY_RECEIPT_MISMATCH");
+    }
+
+    private static async Task<List<RecoveryLine>> InspectRecoveryAsync(ISqlSugarClient db, PurchaseHandoffPackage package,
+        RecoveryReceipt receipt, CancellationToken token)
+    {
+        var originals = ReceiptLines(receipt).ToDictionary(row => row.RawEventId);
+        if (!package.Items.All(item => originals.ContainsKey(item.RawEventId)) || originals.Count != package.Items.Count)
+            throw Error(409, "RAW_REPLAY_RECEIPT_MISMATCH");
+        var result = new List<RecoveryLine>(package.Items.Count);
+        foreach (var item in package.Items.OrderBy(row => row.PoNo, StringComparer.Ordinal)
+                     .ThenBy(row => row.PoLine, StringComparer.Ordinal).ThenBy(row => row.SourceChange?.Version))
+        {
+            token.ThrowIfCancellationRequested();
+            var original = originals[item.RawEventId];
+            if (original.Status is not ("WRITTEN" or "REUSED") || item.SourceChange is { Deleted: true })
+            {
+                result.Add(new(item, "EXCLUDED", null, null));
+                continue;
+            }
+
+            var scope = new { package.TenantId, package.FactoryId, package.SourceId, package.DatasetId,
+                package.SourceCode, item.PoNo, item.PoLine,
+                ScopedKey = FormattableString.Invariant($"{package.TenantId}#{package.FactoryId}#{item.BusinessKey}") };
+            var fields = new StageFields(item.PoNo, item.PoLine, item.ItemCode, item.SupplierCode, item.OrderQty,
+                item.DueDate, item.OrderDate, item.Status, item.SourceUpdatedAt);
+            var version = await db.Ado.SqlQuerySingleAsync<PurchaseLineVersion>("""
+                SELECT source_id AS SourceId,dataset_id AS DatasetId,source_system AS SourceSystem,
+                    source_generation AS Generation,source_version AS Version,is_deleted AS Deleted,
+                    content_sha256 AS Digest,standard_id AS StandardId,stage_id AS StageId
+                FROM mdp_std_purchase_order_version
+                WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND po_no=@PoNo AND po_line=@PoLine FOR UPDATE
+                """, scope);
+            if (item.SourceChange is { } change)
+            {
+                var expected = VersionedDigest(fields, false, package.PackageVersion == PurchaseHandoffPackage.ApiChangeVersion);
+                if (version is null || version.SourceId != package.SourceId || version.DatasetId != package.DatasetId
+                    || version.SourceSystem != package.SourceCode || version.Deleted || version.Generation != change.Generation
+                    || version.Version != change.Version || version.Digest != expected)
+                {
+                    result.Add(new(item, "VERSION_CHANGED", null, null));
+                    continue;
+                }
+            }
+            else if (version is not null)
+            {
+                result.Add(new(item, "VERSION_CHANGED", null, null));
+                continue;
+            }
+
+            var standard = await db.Ado.SqlQueryAsync<StandardRow>("""
+                SELECT id AS Id,factory_id AS FactoryId,source_system AS SourceSystem,source_biz_key AS SourceBizKey,
+                       po_no AS PoNo,po_line AS PoLine,item_code AS ItemCode,supplier_code AS SupplierCode,
+                       order_qty AS OrderQty,due_date AS DueDate,order_date AS OrderDate,status AS Status
+                FROM mdp_std_purchase_order
+                WHERE tenant_id=@TenantId AND (((factory_id=@FactoryId OR factory_id IS NULL OR factory_id=0)
+                    AND po_no=@PoNo AND po_line=@PoLine)
+                    OR (source_system=@SourceCode AND source_biz_key=@ScopedKey)) FOR UPDATE
+                """, scope);
+            var stage = await db.Ado.SqlQuerySingleAsync<StageRow>("""
+                SELECT id AS Id,tenant_id AS TenantId,factory_id AS FactoryId,source_system AS SourceSystem,
+                    source_biz_key AS SourceBizKey,raw_data AS RawData
+                FROM mdp_stg_purchase_order
+                WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_system=@SourceCode
+                  AND source_table='S3_PURCHASE_ORDER' AND source_biz_key=@ScopedKey FOR UPDATE
+                """, scope);
+            var currentStandard = standard.FirstOrDefault();
+            var conflict = standard.Count > 1 || currentStandard is not null && !currentStandard.Matches(package, item, scope.ScopedKey)
+                || stage is not null && !stage.Matches(package, scope.ScopedKey, fields)
+                || version?.StandardId is long expectedStandard && currentStandard is not null && expectedStandard != currentStandard.Id
+                || version?.StageId is long expectedStage && stage is not null && expectedStage != stage.Id;
+            var status = conflict ? "CONFLICT" : stage is null && currentStandard is null ? "MISSING_BOTH"
+                : stage is null ? "MISSING_STAGE" : currentStandard is null ? "MISSING_STANDARD" : "COMPLETE";
+            result.Add(new(item, status, stage?.Id, currentStandard?.Id));
+        }
+        return result;
+    }
+
+    private static Task<long> RecoveryRevisionAsync(ISqlSugarClient db, StoredIngestBatch batch) =>
+        db.Ado.GetLongAsync("""
+            SELECT COALESCE(MAX(id),0) FROM mdp_ingest_purchase_recovery
+            WHERE batch_id=@BatchId AND tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@DatasetId AND source_id=@SourceId
+            """, batch.SqlArguments);
+
+    private static PurchaseRecoveryPreview Preview(PurchaseHandoffPackage package, List<RecoveryLine> rows, long revision)
+    {
+        var lines = rows.Select(row => ToTrace(new(row.Item.RawEventId, row.Status, row.StageId, row.StandardId))).ToList();
+        var digest = Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(new
+        {
+            Package = package.ComputeDigest(), Revision = revision, Lines = lines
+        }, WireJson))).ToLowerInvariant();
+        return new(digest, rows.Any(row => row.NeedsRestore) && rows.All(row => row.Status is not ("CONFLICT" or "VERSION_CHANGED")), lines);
+    }
+
+    private static List<LineResult> ReceiptLines(RecoveryReceipt row) =>
+        JsonSerializer.Deserialize<List<LineResult>>(row.LineResults, WireJson) ?? throw Unavailable();
+
+    private static PurchaseRecoveryResult Result(string json) => new(
+        (JsonSerializer.Deserialize<List<LineResult>>(json, WireJson) ?? throw Unavailable()).Select(ToTrace).ToList());
+
+    private static PurchaseLineTrace ToTrace(LineResult row) => new(row.RawEventId, row.Status,
+        row.StageId?.ToString(CultureInfo.InvariantCulture), row.StandardId?.ToString(CultureInfo.InvariantCulture));
+
+    private static DateTime Utc(DateTime value) => DateTime.SpecifyKind(value, DateTimeKind.Utc);
+
+    private sealed record RecoveryLine(PurchaseHandoffLine Item, string Status, long? StageId, long? StandardId)
+    {
+        public bool NeedsRestore => Status is "MISSING_BOTH" or "MISSING_STAGE" or "MISSING_STANDARD";
+    }
+
+    private sealed class RecoveryReceipt
+    {
+        public string PayloadSha256 { get; set; } = "";
+        public int DigestFormat { get; set; }
+        public string LineResults { get; set; } = "";
+        public string PackageVersion { get; set; } = "";
+        public DateTime CreatedAt { get; set; }
+    }
+
+    private sealed class RecoveryAudit
+    {
+        public string Actor { get; set; } = "";
+        public string Reason { get; set; } = "";
+        public string LineResults { get; set; } = "";
+        public DateTime CreatedAt { get; set; }
+    }
+}
+
+internal sealed record PurchaseLineTrace(Guid RawEventId, string Status, string? StageId, string? StandardId);
+internal sealed record PurchaseTrace(string PackageVersion, string Digest, DateTime CreatedAt, List<PurchaseLineTrace> Lines, List<PurchaseRecoveryTrace> Recoveries);
+internal sealed record PurchaseRecoveryTrace(string Actor, string Reason, DateTime CreatedAt, List<PurchaseLineTrace> Lines);
+internal sealed record PurchaseRecoveryPreview(string Digest, bool CanRestore, List<PurchaseLineTrace> Lines);
+internal sealed record PurchaseRecoveryResult(List<PurchaseLineTrace> Restored);

+ 2 - 2
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpPurchaseMigrationWriter.cs

@@ -112,7 +112,7 @@ internal static class MdpPurchaseMigrationWriter
     }
 
     internal static async Task RecordVersionedAsync(ISqlSugarClient db, PurchaseMigrationScope scope, PurchaseHandoffLine line,
-        string batchId, PurchaseMigrationLineResult result)
+        string batchId, PurchaseMigrationLineResult result, string? traceId = null)
     {
         var digest = Hash(OrderContent.From(line));
         if (result.Status == "WRITTEN" && result.StageId is long stageId && result.StandardId is long standardId)
@@ -123,7 +123,7 @@ internal static class MdpPurchaseMigrationWriter
                 ON DUPLICATE KEY UPDATE content_sha256=VALUES(content_sha256),stage_id=VALUES(stage_id),standard_id=VALUES(standard_id)
                 """, new { ScopeId = scope.Id, line.PoNo, line.PoLine, Digest = digest, StageId = stageId, StandardId = standardId });
         }
-        await ObserveAsync(db, scope, MdpPurchaseMigrationStore.Unified, line, batchId, line.RawEventId.ToString("D"),
+        await ObserveAsync(db, scope, MdpPurchaseMigrationStore.Unified, line, batchId, traceId ?? line.RawEventId.ToString("D"),
             digest, result);
     }
 

+ 34 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/Job/MdpRawRetentionJob.cs

@@ -0,0 +1,34 @@
+using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+using Furion.Schedule;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+
+namespace Admin.NET.Plugin.AiDOP.Job;
+
+[JobDetail("job_mdp_raw_retention", Description = "数据中台 Raw 保留到期处置", GroupName = "default", Concurrent = false)]
+[PeriodSeconds(900, TriggerId = "trigger_mdp_raw_retention", Description = "分批清理已到期的 Raw 原文", RunOnStart = false)]
+public sealed class MdpRawRetentionJob(IServiceScopeFactory scopes, IConfiguration config, ILogger<MdpRawRetentionJob> logger) : IJob
+{
+    public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
+    {
+        if (!AidopJobGate.ShouldRun(nameof(MdpRawRetentionJob), logger)
+            || !config.GetValue<bool>("MdpRawRetention:Enabled")) return;
+
+        using var scope = scopes.CreateScope();
+        var retention = scope.ServiceProvider.GetRequiredService<MdpIngestRawRetentionService>();
+        var total = 0;
+        const int maxBatches = 12;
+        for (var batch = 0; batch < maxBatches && !stoppingToken.IsCancellationRequested; batch++)
+        {
+            var count = await retention.ExpireAsync(stoppingToken);
+            total += count;
+            if (count < MdpIngestRawRetentionService.BatchLimit)
+                break;
+        }
+        if (total > 0)
+            logger.LogInformation("数据中台已处置 {Count} 个到期 Raw 原文,保留批次与追溯证据。", total);
+        if (total == maxBatches * MdpIngestRawRetentionService.BatchLimit)
+            logger.LogWarning("Raw 到期处置已达到单次上限,剩余批次由后续任务处理。");
+    }
+}