Prechádzať zdrojové kódy

feat(data-platform): 交付 1.1.3 连接器 SDK 与能力矩阵

YY968XX 3 dní pred
rodič
commit
c5e16b285e

BIN
doc/plan/系统集成/数据中台/Ai-DOP数据中台一期项目进度管理.xlsx


+ 15 - 0
doc/plan/系统集成/数据中台/连接器SDK能力矩阵.md

@@ -0,0 +1,15 @@
+# 1.1.3 连接器 SDK 与能力矩阵
+
+内部 SDK 由宿主提供已授权的租户、工厂、来源和数据集。Manifest 描述连接器、版本和能力。SDK 在调适配器前校验授权作用域、配置版本、来源 Schema、路径和能力。Manifest 中的凭据字段只使用引用。
+
+| 接入方式 | 云端直连样例 | 工厂助手样例 | 来源位置 |
+| --- | --- | --- | --- |
+| 数据库全量与增量 | DB-D | DB-E | 有序水位和并列排序键,增量须由驱动探测确认 |
+| API 推送 | PUSH-D | PUSH-E | 发送方批次号、幂等键和原报文摘要 |
+| API 拉取 | PULL-D | PULL-E | 页游标,以最后收到持久确认的位置为准 |
+
+六组为采购契约样例。待确认批次保留原标识、幂等键和字节。切换云边路径时,缺少原批次和持久回执则暂停续接。工厂助手本地缓存确认后可以原样重试。取得范围一致的持久接收回执后才推进位置。
+
+SDK 和续接接口见仓库的 [Connectors 目录](../../../../server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Connectors)。采购 [Manifest 样例](../../../../server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/Fixtures/purchase-order-connector-manifest-v1.json) 与 [参考适配器及契约测试](../../../../server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpConnectorSdkTests.cs) 可以一起复现。
+
+2026-11-21,公司开发库专项验收用测试夹具提交这六批。原样重试返回同一批次。每批均有两行入库、一行隔离。夸克页面验证了接收数据集、版本与审批、刷新交接状态及操作记录。数据库驱动、实际第三方 API 及真实工厂助手的生产支持状态由 1.2 至 1.4 各工作包验证。

+ 3 - 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.611</AssemblyVersion>
-    <FileVersion>1.0.611</FileVersion>
-    <Version>1.0.611</Version>
+    <AssemblyVersion>1.0.612</AssemblyVersion>
+    <FileVersion>1.0.612</FileVersion>
+    <Version>1.0.612</Version>
   </PropertyGroup>
 
   <ItemGroup>

+ 58 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Connectors/ConnectorContracts.cs

@@ -0,0 +1,58 @@
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+
+/// <summary>The host provides the authenticated binding. Manifest values never grant access.</summary>
+public sealed record ConnectorBinding(IngestDatasetIdentity Identity, string SourceSchemaVersion, string ConfigVersion);
+
+public sealed record ConnectorExecution(
+    ConnectorBinding Binding, string ConnectorId, string ConnectorVersion, string Path, string Mode);
+
+public sealed record ConnectorProbeResult(bool Supported, string? Reason);
+
+public sealed record ConnectorReadRequest(string? LastCommittedCheckpoint, int BatchSize, bool Incremental = false);
+
+public sealed record ConnectorPushRequest(
+    string SenderBatchId,
+    string IdempotencyKey,
+    ReadOnlyMemory<byte> Payload,
+    string SourcePosition,
+    string? NextCheckpoint);
+
+public sealed record ConnectorBatchCandidate(
+    string SenderBatchId,
+    string IdempotencyKey,
+    ReadOnlyMemory<byte> Payload,
+    string SourcePosition,
+    string? NextCheckpoint,
+    bool HasMore);
+
+public interface IConnector
+{
+    ConnectorManifest Describe();
+
+    Task<ConnectorProbeResult> ProbeAsync(ConnectorExecution execution, CancellationToken cancellationToken);
+
+    /// <summary>Returns a candidate for submission, or null when no records are available.</summary>
+    Task<ConnectorBatchCandidate?> ReadAsync(
+        ConnectorExecution execution, ConnectorReadRequest request, CancellationToken cancellationToken);
+
+    /// <summary>Prepares the original source bytes for the unified receiving contract.</summary>
+    Task<ConnectorBatchCandidate> PreparePushAsync(
+        ConnectorExecution execution, ConnectorPushRequest request, CancellationToken cancellationToken);
+}
+
+public enum ConnectorError
+{
+    InvalidManifest,
+    UnsupportedVersion,
+    UnsupportedPath,
+    UnsupportedCapability,
+    ScopeMismatch,
+    InvalidBatch,
+    BatchMismatch,
+    SourceUnavailable
+}
+
+public sealed class ConnectorContractException(ConnectorError code) : Exception(code.ToString())
+{
+    public ConnectorError Code { get; } = code;
+}

+ 106 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Connectors/ConnectorManifest.cs

@@ -0,0 +1,106 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+
+public sealed record ConnectorCredentials(string SecretRef);
+
+public sealed record ConnectorCapability(string Position, bool Full = false, bool Incremental = false, string? Pagination = null);
+
+public sealed record ConnectorVerification(string Scope, string Status, IReadOnlyList<string> Cases);
+
+public sealed record ConnectorManifest(
+    string ManifestVersion,
+    string ConnectorId,
+    string ConnectorVersion,
+    string SdkContractVersion,
+    string DatasetKey,
+    string SourceSchemaVersion,
+    IReadOnlyList<string> SupportedPaths,
+    ConnectorCredentials CredentialRequirements,
+    IReadOnlyDictionary<string, ConnectorCapability> Capabilities,
+    ConnectorVerification Verification)
+{
+    public const string FormatVersion = "mdp-connector-manifest-v1";
+    public const string SdkVersion = "mdp-connector-sdk-v1";
+    public const string CloudDirect = "cloud-direct";
+    public const string FactoryAgent = "factory-agent";
+    public const string Database = "database";
+    public const string ApiPush = "api-push";
+    public const string ApiPull = "api-pull";
+
+    private static readonly JsonSerializerOptions JsonOptions = new()
+    {
+        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
+        UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow
+    };
+
+    public static ConnectorManifest Parse(ReadOnlyMemory<byte> utf8)
+    {
+        try
+        {
+            using var document = JsonDocument.Parse(utf8);
+            EnsureUniqueProperties(document.RootElement);
+            var manifest = document.RootElement.Deserialize<ConnectorManifest>(JsonOptions)
+                ?? throw new ConnectorContractException(ConnectorError.InvalidManifest);
+            manifest.Validate();
+            return manifest;
+        }
+        catch (JsonException)
+        {
+            throw new ConnectorContractException(ConnectorError.InvalidManifest);
+        }
+    }
+
+    internal void Validate()
+    {
+        if (Missing(ManifestVersion) || Missing(SdkContractVersion) || Missing(ConnectorId)
+            || Missing(ConnectorVersion) || Missing(DatasetKey) || Missing(SourceSchemaVersion)
+            || SupportedPaths is null || SupportedPaths.Count == 0
+            || SupportedPaths.Any(path => path is not (CloudDirect or FactoryAgent))
+            || SupportedPaths.Distinct(StringComparer.Ordinal).Count() != SupportedPaths.Count
+            || CredentialRequirements is null || Missing(CredentialRequirements.SecretRef)
+            || Capabilities is null || Capabilities.Count == 0 || Capabilities.Any(pair => !IsModeValid(pair.Key, pair.Value))
+            || Verification is null || Missing(Verification.Scope) || Missing(Verification.Status) || Verification.Cases is null
+            || Verification.Cases.Any(Missing) || Verification.Cases.Distinct(StringComparer.Ordinal).Count() != Verification.Cases.Count)
+        {
+            throw new ConnectorContractException(ConnectorError.InvalidManifest);
+        }
+        if (ManifestVersion != FormatVersion || SdkContractVersion != SdkVersion)
+            throw new ConnectorContractException(ConnectorError.UnsupportedVersion);
+    }
+
+    private static bool Missing(string? value) => string.IsNullOrWhiteSpace(value);
+
+    private static bool IsModeValid(string mode, ConnectorCapability? capability)
+    {
+        if (capability is null || Missing(capability.Position))
+            return false;
+        return mode switch
+        {
+            Database => (capability.Full || capability.Incremental) && capability.Pagination is null,
+            ApiPush => !capability.Full && !capability.Incremental && capability.Pagination is null,
+            ApiPull => !capability.Full && !capability.Incremental && !Missing(capability.Pagination),
+            _ => false
+        };
+    }
+
+    private static void EnsureUniqueProperties(JsonElement element)
+    {
+        if (element.ValueKind == JsonValueKind.Object)
+        {
+            var names = new HashSet<string>(StringComparer.Ordinal);
+            foreach (var property in element.EnumerateObject())
+            {
+                if (!names.Add(property.Name))
+                    throw new ConnectorContractException(ConnectorError.InvalidManifest);
+                EnsureUniqueProperties(property.Value);
+            }
+        }
+        else if (element.ValueKind == JsonValueKind.Array)
+        {
+            foreach (var child in element.EnumerateArray())
+                EnsureUniqueProperties(child);
+        }
+    }
+}

+ 93 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Connectors/ConnectorResume.cs

@@ -0,0 +1,93 @@
+using System.Security.Cryptography;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+
+public sealed record ConnectorBatchIdentity(
+    ConnectorBinding Binding, string SenderBatchId, string IdempotencyKey, string PayloadSha256);
+
+public sealed record ConnectorPendingBatch(
+    ConnectorBatchIdentity Id, string SourcePosition, string? NextCheckpoint);
+
+/// <summary>The sender persists Pending and Payload before submitting the batch.</summary>
+public sealed class ConnectorFrozenBatch
+{
+    private ConnectorFrozenBatch(ConnectorPendingBatch pending, byte[] payload)
+    {
+        Pending = pending;
+        Payload = payload;
+    }
+
+    public ConnectorPendingBatch Pending { get; }
+
+    public ReadOnlyMemory<byte> Payload { get; }
+
+    public static ConnectorFrozenBatch Capture(ConnectorBinding binding, ConnectorBatchCandidate candidate)
+    {
+        if (string.IsNullOrWhiteSpace(candidate.SenderBatchId) || string.IsNullOrWhiteSpace(candidate.IdempotencyKey)
+            || string.IsNullOrWhiteSpace(candidate.SourcePosition) || candidate.Payload.IsEmpty)
+        {
+            throw new ConnectorContractException(ConnectorError.InvalidBatch);
+        }
+
+        var payload = candidate.Payload.ToArray();
+        var id = new ConnectorBatchIdentity(binding, candidate.SenderBatchId, candidate.IdempotencyKey, Digest(payload));
+        return new ConnectorFrozenBatch(new ConnectorPendingBatch(id, candidate.SourcePosition, candidate.NextCheckpoint), payload);
+    }
+
+    /// <summary>Restores only the original bytes from the sender's authorized handoff.</summary>
+    public static ConnectorFrozenBatch Restore(ConnectorPendingBatch pending, ReadOnlySpan<byte> payload)
+    {
+        var snapshot = payload.ToArray();
+        if (Digest(snapshot) != pending.Id.PayloadSha256)
+            throw new ConnectorContractException(ConnectorError.BatchMismatch);
+
+        return new ConnectorFrozenBatch(pending, snapshot);
+    }
+
+    private static string Digest(ReadOnlySpan<byte> payload) =>
+        Convert.ToHexString(SHA256.HashData(payload)).ToLowerInvariant();
+}
+
+public enum ConnectorConfirmation
+{
+    LocallyCached,
+    CloudDurable,
+    Processed
+}
+
+/// <summary>The host obtains the receipt from the receiving service under the authorized scope.</summary>
+public sealed record ConnectorReceipt(ConnectorBatchIdentity Id, ConnectorConfirmation Confirmation, Guid? RawBatchId);
+
+public enum ConnectorResumeAction
+{
+    Pause,
+    RetryOriginal,
+    Advance,
+    RejectMismatch
+}
+
+public sealed record ConnectorResumeDecision(
+    ConnectorResumeAction Action, string? NextCheckpoint = null, Guid? RawBatchId = null);
+
+public static class ConnectorResume
+{
+    public static ConnectorResumeDecision Decide(
+        ConnectorBinding authorizedBinding, ConnectorPendingBatch pending, ConnectorReceipt? receipt, ConnectorFrozenBatch? original)
+    {
+        if (authorizedBinding != pending.Id.Binding || (receipt is not null && receipt.Id != pending.Id)
+            || (original is not null && original.Pending != pending))
+        {
+            return new ConnectorResumeDecision(ConnectorResumeAction.RejectMismatch);
+        }
+
+        if (receipt?.Confirmation == ConnectorConfirmation.CloudDurable)
+        {
+            if (receipt.RawBatchId is null || receipt.RawBatchId == Guid.Empty)
+                return new ConnectorResumeDecision(ConnectorResumeAction.RejectMismatch);
+
+            return new ConnectorResumeDecision(ConnectorResumeAction.Advance, pending.NextCheckpoint, receipt.RawBatchId);
+        }
+
+        return new ConnectorResumeDecision(original is null ? ConnectorResumeAction.Pause : ConnectorResumeAction.RetryOriginal);
+    }
+}

+ 103 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Connectors/ConnectorSdk.cs

@@ -0,0 +1,103 @@
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+
+/// <summary>Validates one approved execution before calling a source adapter.</summary>
+public sealed class ConnectorSdk
+{
+    private readonly IConnector _connector;
+    private readonly ConnectorExecution _execution;
+    private readonly ConnectorCapability _capability;
+    private ConnectorProbeResult? _probe;
+
+    public ConnectorSdk(IConnector connector, ConnectorExecution execution, ISchemaRegistry schemas)
+    {
+        _connector = connector;
+        _execution = execution;
+        Manifest = connector.Describe();
+        Manifest.Validate();
+
+        var identity = execution.Binding.Identity;
+        if (identity.TenantId <= 0 || identity.FactoryId <= 0 || identity.SourceId <= 0 || identity.DatasetId <= 0
+            || string.IsNullOrWhiteSpace(identity.SourceCode) || Manifest.DatasetKey != identity.DatasetKey)
+        {
+            throw new ConnectorContractException(ConnectorError.ScopeMismatch);
+        }
+
+        var contract = schemas.Find(identity.DatasetKey, Binding.SourceSchemaVersion);
+        if (execution.ConnectorId != Manifest.ConnectorId || execution.ConnectorVersion != Manifest.ConnectorVersion
+            || Binding.SourceSchemaVersion != Manifest.SourceSchemaVersion || contract is null
+            || Binding.ConfigVersion != contract.ConfigVersion)
+        {
+            throw new ConnectorContractException(ConnectorError.UnsupportedVersion);
+        }
+
+        if (!Manifest.SupportedPaths.Contains(execution.Path, StringComparer.Ordinal))
+            throw new ConnectorContractException(ConnectorError.UnsupportedPath);
+        if (execution.Mode is not (ConnectorManifest.Database or ConnectorManifest.ApiPush or ConnectorManifest.ApiPull)
+            || !Manifest.Capabilities.TryGetValue(execution.Mode, out var capability))
+            throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
+
+        _capability = capability;
+    }
+
+    public ConnectorManifest Manifest { get; }
+
+    public ConnectorBinding Binding => _execution.Binding;
+
+    /// <summary>The host passes the cancellation token with its operation time budget.</summary>
+    public async Task<ConnectorProbeResult> ProbeAsync(CancellationToken cancellationToken)
+    {
+        cancellationToken.ThrowIfCancellationRequested();
+        var result = await _connector.ProbeAsync(_execution, cancellationToken).WaitAsync(cancellationToken);
+        _probe = result;
+        return result;
+    }
+
+    public async Task<ConnectorBatchCandidate?> ReadAsync(ConnectorReadRequest request, CancellationToken cancellationToken)
+    {
+        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(request.BatchSize);
+        if (_execution.Mode == ConnectorManifest.ApiPush
+            || (request.Incremental && !_capability.Incremental)
+            || (_execution.Mode == ConnectorManifest.Database && !request.Incremental && !_capability.Full))
+        {
+            throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
+        }
+
+        await RequireSupportedAsync(cancellationToken);
+        var candidate = await _connector.ReadAsync(_execution, request, cancellationToken).WaitAsync(cancellationToken);
+        if (candidate is null)
+            return null;
+        if (((candidate.HasMore || request.Incremental) && string.IsNullOrWhiteSpace(candidate.NextCheckpoint))
+            || (candidate.NextCheckpoint is not null && candidate.NextCheckpoint == request.LastCommittedCheckpoint))
+        {
+            throw new ConnectorContractException(ConnectorError.InvalidBatch);
+        }
+        return candidate;
+    }
+
+    public async Task<ConnectorBatchCandidate> PreparePushAsync(ConnectorPushRequest request, CancellationToken cancellationToken)
+    {
+        if (_execution.Mode != ConnectorManifest.ApiPush)
+            throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
+
+        cancellationToken.ThrowIfCancellationRequested();
+        var original = request.Payload.ToArray();
+        await RequireSupportedAsync(cancellationToken);
+        var candidate = await _connector.PreparePushAsync(_execution, request with { Payload = original }, cancellationToken)
+            .WaitAsync(cancellationToken);
+        if (candidate.SenderBatchId != request.SenderBatchId || candidate.IdempotencyKey != request.IdempotencyKey
+            || candidate.SourcePosition != request.SourcePosition || candidate.NextCheckpoint != request.NextCheckpoint
+            || !candidate.Payload.Span.SequenceEqual(original))
+        {
+            throw new ConnectorContractException(ConnectorError.BatchMismatch);
+        }
+        return candidate with { Payload = original };
+    }
+
+    private async Task RequireSupportedAsync(CancellationToken cancellationToken)
+    {
+        cancellationToken.ThrowIfCancellationRequested();
+        var probe = _probe ?? await ProbeAsync(cancellationToken);
+        if (!probe.Supported)
+            throw new ConnectorContractException(ConnectorError.UnsupportedCapability);
+    }
+}

+ 20 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/Fixtures/purchase-order-connector-manifest-v1.json

@@ -0,0 +1,20 @@
+{
+  "manifestVersion": "mdp-connector-manifest-v1",
+  "connectorId": "lab.purchase.fixture",
+  "connectorVersion": "0.1.0-review.1",
+  "sdkContractVersion": "mdp-connector-sdk-v1",
+  "datasetKey": "lab.erp.purchase-order.v1",
+  "sourceSchemaVersion": "po-source-v1",
+  "supportedPaths": ["cloud-direct", "factory-agent"],
+  "credentialRequirements": { "secretRef": "fixture.purchase.source" },
+  "capabilities": {
+    "database": { "full": true, "incremental": true, "position": "ordered-watermark" },
+    "api-push": { "position": "sender-batch-id" },
+    "api-pull": { "pagination": "opaque-cursor", "position": "page-cursor" }
+  },
+  "verification": {
+    "scope": "contract-fixture",
+    "status": "contract-fixture-verified",
+    "cases": ["DB-D", "DB-E", "PUSH-D", "PUSH-E", "PULL-D", "PULL-E"]
+  }
+}

+ 272 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpConnectorSdkTests.cs

@@ -0,0 +1,272 @@
+using System.Text;
+using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
+using Xunit;
+using Xunit.Abstractions;
+
+namespace Admin.NET.Plugin.AiDOP.Tests.DataPlatform;
+
+public sealed class MdpConnectorSdkTests(ITestOutputHelper output)
+{
+    private static readonly PurchaseOrderSchemaRegistry Schemas = new();
+    private static readonly ConnectorBinding Binding = new(
+        new IngestDatasetIdentity(101, 102, 103, 104, "FIXTURE", PurchaseOrderSchemaRegistry.DatasetKey),
+        PurchaseOrderSchemaRegistry.SourceVersion, "po-config-v1");
+    private static readonly IngestLimits Limits = new(1024 * 1024, 100, 16);
+
+    [Theory]
+    [InlineData("DB-D", "database", "cloud-direct")]
+    [InlineData("DB-E", "database", "factory-agent")]
+    [InlineData("PUSH-D", "api-push", "cloud-direct")]
+    [InlineData("PUSH-E", "api-push", "factory-agent")]
+    [InlineData("PULL-D", "api-pull", "cloud-direct")]
+    [InlineData("PULL-E", "api-pull", "factory-agent")]
+    public async Task SixPaths_PreservePurchaseContract(string caseId, string mode, string path)
+    {
+        var source = Fixture("purchase-order-source-v1.json");
+        var sdk = Sdk(mode, path);
+        Assert.Contains(caseId, sdk.Manifest.Verification.Cases);
+        Assert.True((await sdk.ProbeAsync(CancellationToken.None)).Supported);
+        var batch = await CaptureAsync(sdk, mode, source);
+        if (mode != "database")
+            Assert.Equal(source, batch.Payload.ToArray());
+        var pending = batch.Pending;
+        var prepared = new IngestBatchPreparer(Schemas).Prepare(
+            Binding.Identity, Binding.SourceSchemaVersion, batch.Payload.Span, Limits);
+
+        Assert.Equal(Binding.Identity, prepared.Batch.Identity);
+        Assert.Equal(pending.Id.PayloadSha256, prepared.Batch.PayloadSha256);
+        Assert.Equal("raw-envelope-v1", prepared.Batch.Versions.RawSchema.Version);
+        Assert.Equal("po-map-v1", prepared.Batch.Versions.MappingVersion);
+        Assert.Equal("po-rule-v1", prepared.Batch.Versions.RuleVersion);
+        Assert.Equal("po-config-v1", prepared.Batch.Versions.ConfigVersion);
+        Assert.Equal("MDP-PO-001@1.0.0", prepared.Batch.Versions.HandoffSchema.Version);
+        Assert.Equal(3, prepared.Events.Count);
+
+        // This projection supplies the expected handoff for fixtures only.
+        var handoffRows = new List<(string BusinessKey, decimal Quantity)>();
+        RawIngestEvent? quarantined = null;
+        foreach (var item in prepared.Events)
+        {
+            using var row = JsonDocument.Parse(prepared.Batch.Payload.Slice(item.PayloadOffset, item.PayloadLength));
+            if (!row.RootElement.TryGetProperty("ItemCode", out _))
+            {
+                quarantined = item;
+                continue;
+            }
+            handoffRows.Add((Assert.IsType<string>(item.SourceBusinessKey),
+                row.RootElement.GetProperty("OrderQty").GetDecimal()));
+        }
+        using var expected = JsonDocument.Parse(Fixture("purchase-order-handoff-v1.json"));
+        Assert.Equal(expected.RootElement.GetProperty("items").EnumerateArray()
+            .Select(row => (row.GetProperty("businessKey").GetString(), row.GetProperty("orderQty").GetDecimal())), handoffRows);
+        Assert.Equal(15.5m, handoffRows.Sum(row => row.Quantity));
+        Assert.Equal(2, Assert.IsType<RawIngestEvent>(quarantined).RecordOrdinal);
+        Assert.EndsWith("#03", quarantined!.SourceBusinessKey);
+
+        if (path == "factory-agent")
+        {
+            var cached = new ConnectorReceipt(pending.Id, ConnectorConfirmation.LocallyCached, null);
+            Assert.Equal(ConnectorResumeAction.RetryOriginal, ConnectorResume.Decide(Binding, pending, cached, batch).Action);
+        }
+        output.WriteLine("{0} | Mode={1} | Path={2} | Raw=3 | FixtureHandoff=2 | FixtureQuarantine=1 | TotalQty=15.5",
+            caseId, mode, path);
+    }
+
+    [Theory]
+    [InlineData("database")]
+    [InlineData("api-push")]
+    [InlineData("api-pull")]
+    public async Task ThreeSwitches_RequireOriginalBatchOrDurableReceipt(string mode)
+    {
+        var incoming = Fixture("purchase-order-source-v1.json");
+        var before = Sdk(mode, "cloud-direct");
+        var after = Sdk(mode, "factory-agent");
+        var original = await CaptureAsync(before, mode, incoming);
+        var pending = original.Pending;
+        Assert.Equal("send-11", pending.Id.SenderBatchId);
+        Assert.Equal("idem-11", pending.Id.IdempotencyKey);
+        Assert.Equal("source-11", pending.SourcePosition);
+        Assert.Equal("source-11", pending.NextCheckpoint);
+
+        // Batch 10 is already confirmed. The sender journal retains batch 11 until a durable receipt.
+        var receiver = new FixtureReceiver();
+        var batch10 = ConnectorFrozenBatch.Capture(before.Binding,
+            new ConnectorBatchCandidate("send-10", "idem-10", incoming, "source-10", "source-10", true));
+        var checkpoint = ConnectorResume.Decide(before.Binding, batch10.Pending, receiver.Persist(batch10), null).NextCheckpoint;
+        Assert.Equal("source-10", checkpoint);
+        var cached = new ConnectorReceipt(pending.Id, ConnectorConfirmation.LocallyCached, null);
+        Assert.Null(ConnectorResume.Decide(after.Binding, pending, cached, original).NextCheckpoint);
+        var restored = ConnectorFrozenBatch.Restore(pending, original.Payload.Span);
+        var retry = ConnectorResume.Decide(after.Binding, pending, null, restored);
+        Assert.Equal(ConnectorResumeAction.RetryOriginal, retry.Action);
+        Assert.Null(retry.NextCheckpoint);
+        Assert.Equal(original.Payload.ToArray(), restored.Payload.ToArray());
+        Assert.Equal("source-10", checkpoint);
+
+        var pause = ConnectorResume.Decide(after.Binding, pending, null, null);
+        Assert.Equal(ConnectorResumeAction.Pause, pause.Action);
+        Assert.Null(pause.NextCheckpoint);
+        Assert.Equal(1, receiver.BatchCount);
+
+        // Batch 11 is now persisted. This branch simulates the sender losing that response.
+        var durable = receiver.Persist(original);
+        var confirmed = ConnectorResume.Decide(after.Binding, pending, durable, null);
+        Assert.Equal(ConnectorResumeAction.Advance, confirmed.Action);
+        Assert.Equal(durable.RawBatchId, confirmed.RawBatchId);
+        checkpoint = Assert.IsType<string>(confirmed.NextCheckpoint);
+        Assert.Equal("source-11", checkpoint);
+        Assert.Equal(durable, receiver.Persist(restored));
+        Assert.Equal(2, receiver.BatchCount);
+
+        var next = mode == "api-push"
+            ? await after.PreparePushAsync(new ConnectorPushRequest("send-12", "idem-12", incoming, "source-12", "source-12"), CancellationToken.None)
+            : (await after.ReadAsync(new ConnectorReadRequest(checkpoint, 100, mode == "database"), CancellationToken.None))!;
+        Assert.Equal("send-12", next.SenderBatchId);
+        Assert.Equal("source-12", next.NextCheckpoint);
+        var batch12 = ConnectorFrozenBatch.Capture(after.Binding, next);
+        Assert.Equal("source-12", ConnectorResume.Decide(after.Binding, batch12.Pending, receiver.Persist(batch12), null).NextCheckpoint);
+        Assert.Equal(3, receiver.BatchCount);
+        output.WriteLine("{0} | source-10 -> source-11 -> source-12 | CloudDurable=Advance | OriginalAvailable=RetryOriginal | OriginalMissing=Pause", mode);
+    }
+
+    [Fact]
+    public async Task ResumeRejectsScopeDigestAndReceiptMismatch()
+    {
+        var batch = await CaptureAsync(Sdk("api-push", "cloud-direct"), "api-push", Fixture("purchase-order-source-v1.json"));
+        var pending = batch.Pending;
+        var receipt = new ConnectorReceipt(pending.Id, ConnectorConfirmation.CloudDurable, Guid.NewGuid());
+        var wrongFactory = Binding with { Identity = Binding.Identity with { FactoryId = 999 } };
+        var wrongId = pending.Id with { IdempotencyKey = "other-key" };
+        Assert.Equal(ConnectorResumeAction.RejectMismatch, ConnectorResume.Decide(wrongFactory, pending, receipt, batch).Action);
+        Assert.Equal(ConnectorResumeAction.RejectMismatch,
+            ConnectorResume.Decide(Binding, pending, receipt with { Id = wrongId }, batch).Action);
+        Assert.Equal(ConnectorResumeAction.RejectMismatch,
+            ConnectorResume.Decide(Binding with { ConfigVersion = "po-config-v2" }, pending, receipt, batch).Action);
+        Assert.Equal(ConnectorResumeAction.RejectMismatch,
+            ConnectorResume.Decide(Binding, pending, receipt with { RawBatchId = null }, batch).Action);
+        Assert.Equal(ConnectorResumeAction.RetryOriginal,
+            ConnectorResume.Decide(Binding, pending, receipt with { Confirmation = ConnectorConfirmation.Processed }, batch).Action);
+        Assert.Equal(ConnectorError.BatchMismatch, Assert.Throws<ConnectorContractException>(() =>
+            ConnectorFrozenBatch.Restore(pending, "{}"u8)).Code);
+    }
+
+    [Fact]
+    public async Task ManifestRejectsUnsupportedPathModeAndVersion()
+    {
+        var fixture = Encoding.UTF8.GetString(Fixture("purchase-order-connector-manifest-v1.json"));
+        var manifest = ConnectorManifest.Parse(Encoding.UTF8.GetBytes(fixture));
+        Assert.Equal(6, manifest.Verification.Cases.Count);
+        Assert.Equal(ConnectorError.UnsupportedVersion,
+            Assert.Throws<ConnectorContractException>(() => Sdk("api-push", "cloud-direct", Binding with { SourceSchemaVersion = "po-source-v2" })).Code);
+        Assert.Equal(ConnectorError.UnsupportedPath,
+            Assert.Throws<ConnectorContractException>(() => Sdk("api-push", "unknown-path")).Code);
+        Assert.Equal(ConnectorError.UnsupportedCapability,
+            Assert.Throws<ConnectorContractException>(() => Sdk("unknown-mode", "cloud-direct")).Code);
+        Assert.Equal(ConnectorError.UnsupportedVersion, Assert.Throws<ConnectorContractException>(() =>
+            ConnectorManifest.Parse(Encoding.UTF8.GetBytes(fixture.Replace("mdp-connector-sdk-v1", "mdp-connector-sdk-v9")))).Code);
+        var duplicate = fixture.Replace("\"connectorId\":", "\"connectorId\": \"duplicate\", \"connectorId\":");
+        Assert.Equal(ConnectorError.InvalidManifest, Assert.Throws<ConnectorContractException>(() =>
+            ConnectorManifest.Parse(Encoding.UTF8.GetBytes(duplicate))).Code);
+        var direct = manifest with { SupportedPaths = new[] { "cloud-direct" } };
+        Assert.Equal(ConnectorError.UnsupportedPath, Assert.Throws<ConnectorContractException>(() =>
+            NewSdk(direct, "api-push", "factory-agent", Binding)).Code);
+        var pullWithoutProbe = new FixtureConnector(manifest, Fixture("purchase-order-source-v1.json"), false);
+        var sdk = new ConnectorSdk(pullWithoutProbe, Execution(manifest, "api-pull", "cloud-direct", Binding), Schemas);
+        Assert.False((await sdk.ProbeAsync(CancellationToken.None)).Supported);
+        var refused = await Assert.ThrowsAsync<ConnectorContractException>(() =>
+            sdk.ReadAsync(new ConnectorReadRequest("source-10", 100), CancellationToken.None));
+        Assert.Equal(ConnectorError.UnsupportedCapability, refused.Code);
+        Assert.Equal(0, pullWithoutProbe.ReadCalls);
+    }
+
+    [Fact]
+    public async Task PushRetainsSourceBytesAndCancellationHonored()
+    {
+        var manifest = ConnectorManifest.Parse(Fixture("purchase-order-connector-manifest-v1.json"));
+        var source = Fixture("purchase-order-source-v1.json");
+        var connector = new FixtureConnector(manifest, source, rewritePush: true);
+        var sdk = new ConnectorSdk(connector, Execution(manifest, "api-push", "cloud-direct", Binding), Schemas);
+        var request = new ConnectorPushRequest("send-11", "idem-11", source, "source-11", "source-11");
+        using var cancelled = new CancellationTokenSource();
+        cancelled.Cancel();
+        await Assert.ThrowsAnyAsync<OperationCanceledException>(() => sdk.ProbeAsync(cancelled.Token));
+        await Assert.ThrowsAnyAsync<OperationCanceledException>(() => sdk.PreparePushAsync(request, cancelled.Token));
+        var error = await Assert.ThrowsAsync<ConnectorContractException>(() => sdk.PreparePushAsync(request, CancellationToken.None));
+        Assert.Equal(ConnectorError.BatchMismatch, error.Code);
+    }
+
+    private static async Task<ConnectorFrozenBatch> CaptureAsync(ConnectorSdk sdk, string mode, byte[] source)
+    {
+        var candidate = mode == "api-push"
+            ? await sdk.PreparePushAsync(new ConnectorPushRequest("send-11", "idem-11", source, "source-11", "source-11"), CancellationToken.None)
+            : (await sdk.ReadAsync(new ConnectorReadRequest("source-10", 100, mode == "database"), CancellationToken.None))!;
+        return ConnectorFrozenBatch.Capture(sdk.Binding, candidate);
+    }
+
+    private static ConnectorSdk Sdk(string mode, string path, ConnectorBinding? binding = null) =>
+        NewSdk(ConnectorManifest.Parse(Fixture("purchase-order-connector-manifest-v1.json")), mode, path, binding ?? Binding);
+
+    private static ConnectorSdk NewSdk(ConnectorManifest manifest, string mode, string path, ConnectorBinding binding) =>
+        new(new FixtureConnector(manifest, Fixture("purchase-order-source-v1.json")),
+            Execution(manifest, mode, path, binding), Schemas);
+
+    private static ConnectorExecution Execution(ConnectorManifest manifest, string mode, string path, ConnectorBinding binding) =>
+        new(binding, manifest.ConnectorId, manifest.ConnectorVersion, path, mode);
+
+    private static byte[] Fixture(string name) => File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "DataPlatform", "Fixtures", name));
+
+    // Simulates a durable receiver for the contract tests. The real transaction belongs to 2.1.3.
+    private sealed class FixtureReceiver
+    {
+        private readonly Dictionary<(ConnectorBinding Scope, string IdempotencyKey), ConnectorReceipt> _receipts = new();
+
+        public int BatchCount => _receipts.Count;
+
+        public ConnectorReceipt Persist(ConnectorFrozenBatch batch)
+        {
+            var id = batch.Pending.Id;
+            var key = (id.Binding, id.IdempotencyKey);
+            if (_receipts.TryGetValue(key, out var existing))
+            {
+                Assert.Equal(id, existing.Id);
+                return existing;
+            }
+
+            var raw = new IngestBatchPreparer(Schemas).Prepare(
+                id.Binding.Identity, id.Binding.SourceSchemaVersion, batch.Payload.Span, Limits);
+            var receipt = new ConnectorReceipt(id, ConnectorConfirmation.CloudDurable, raw.Batch.BatchId);
+            _receipts.Add(key, receipt);
+            return receipt;
+        }
+    }
+
+    private sealed class FixtureConnector(ConnectorManifest manifest, byte[] source, bool supported = true, bool rewritePush = false) : IConnector
+    {
+        public int ReadCalls { get; private set; }
+        public ConnectorManifest Describe() => manifest;
+        public Task<ConnectorProbeResult> ProbeAsync(ConnectorExecution execution, CancellationToken token) =>
+            Task.FromResult(new ConnectorProbeResult(supported, supported ? null : "fixture unavailable"));
+
+        public Task<ConnectorBatchCandidate?> ReadAsync(ConnectorExecution execution, ConnectorReadRequest request, CancellationToken token)
+        {
+            ReadCalls++;
+            var next = request.LastCommittedCheckpoint == "source-11" ? 12 : 11;
+            var payload = source;
+            if (execution.Mode == "database")
+            {
+                using var json = JsonDocument.Parse(source);
+                var databaseRows = json.RootElement.GetProperty("data").GetProperty("list").EnumerateArray()
+                    .Select(row => row.EnumerateObject().ToDictionary(field => field.Name, field => field.Value.Clone()));
+                payload = JsonSerializer.SerializeToUtf8Bytes(new { data = new { list = databaseRows } });
+            }
+            var candidate = new ConnectorBatchCandidate($"send-{next}", $"idem-{next}", payload, $"source-{next}", $"source-{next}", next == 11);
+            return Task.FromResult<ConnectorBatchCandidate?>(candidate);
+        }
+
+        public Task<ConnectorBatchCandidate> PreparePushAsync(ConnectorExecution execution, ConnectorPushRequest request, CancellationToken token) =>
+            Task.FromResult(new ConnectorBatchCandidate(request.SenderBatchId, request.IdempotencyKey,
+                rewritePush ? "{}"u8.ToArray() : request.Payload, request.SourcePosition, request.NextCheckpoint, false));
+    }
+}