MB-X Bilibili Pipeline
5 days ago 8b94574583bb5d33faf4d3cec465e3fbcdcf40d3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
 
function Invoke-AnaSemiL1ContractValidationV001 {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)][string]$ProjectRoot,
        [Parameter(Mandatory = $true)][string]$RunnerAssemblyPath,
        [Parameter(Mandatory = $true)][string]$ExpectedVectorsPath,
        [Parameter(Mandatory = $true)][string]$OutputPath
    )
 
    function Get-HexSha256Bytes([byte[]]$Bytes) {
        $sha = [Security.Cryptography.SHA256]::Create()
        try { return ([BitConverter]::ToString($sha.ComputeHash($Bytes)).Replace('-', '').ToLowerInvariant()) }
        finally { $sha.Dispose() }
    }
    function Get-HexSha256File([string]$Path) {
        $stream = [IO.File]::Open($Path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
        try {
            $sha = [Security.Cryptography.SHA256]::Create()
            try { return ([BitConverter]::ToString($sha.ComputeHash($stream)).Replace('-', '').ToLowerInvariant()) }
            finally { $sha.Dispose() }
        }
        finally { $stream.Dispose() }
    }
    function Get-ArgvFingerprint([string[]]$LogicalArgv) {
        $stream = New-Object IO.MemoryStream
        try {
            $domain = [Text.Encoding]::UTF8.GetBytes('ANA-SEMI-ARGV-V001')
            $stream.Write($domain, 0, $domain.Length)
            foreach ($token in $LogicalArgv) {
                $stream.WriteByte(0)
                $bytes = [Text.Encoding]::UTF8.GetBytes($token)
                $stream.Write($bytes, 0, $bytes.Length)
            }
            return (Get-HexSha256Bytes $stream.ToArray())
        }
        finally { $stream.Dispose() }
    }
    function Decode-EscapedBytes([string]$Escaped) {
        $stream = New-Object IO.MemoryStream
        try {
            for ($index = 0; $index -lt $Escaped.Length; $index++) {
                $ch = $Escaped[$index]
                if ($ch -ne '\') {
                    $stream.WriteByte([byte][char]$ch)
                    continue
                }
                if ($index + 1 -ge $Escaped.Length) { throw 'ESCAPE_EOF' }
                $index++
                switch -CaseSensitive ($Escaped[$index]) {
                    't' { $stream.WriteByte(9) }
                    'n' { $stream.WriteByte(10) }
                    '\' { $stream.WriteByte(92) }
                    default { throw 'ESCAPE_INVALID' }
                }
            }
            return $stream.ToArray()
        }
        finally { $stream.Dispose() }
    }
    function Get-ContractStopCode($ErrorRecord) {
        $cursor = $ErrorRecord.Exception
        while ($null -ne $cursor) {
            $property = $cursor.GetType().GetProperty('StopCode')
            if ($null -ne $property) { return [string]$property.GetValue($cursor, $null) }
            $cursor = $cursor.InnerException
        }
        return $null
    }
 
    $jcsModulePath = [IO.Path]::GetFullPath((Join-Path $ProjectRoot 'dev/ana-dev/AnaSemi.JcsEvidenceWriterV001.psm1'))
    $loadedJcs = @(Get-Module | Where-Object { [IO.Path]::GetFullPath($_.Path) -ceq $jcsModulePath })
    if ($loadedJcs.Count -eq 0) {
        [void](Import-Module -Name $jcsModulePath -DisableNameChecking -PassThru -ErrorAction Stop)
        $loadedJcs = @(Get-Module | Where-Object { [IO.Path]::GetFullPath($_.Path) -ceq $jcsModulePath })
    }
    if ($loadedJcs.Count -ne 1) { throw 'STOP_JCS_MODULE_LOAD_OR_API_DRIFT' }
    $exports = @($loadedJcs[0].ExportedFunctions.Keys)
    [Array]::Sort($exports, [StringComparer]::Ordinal)
    $expectedExports = @('ConvertTo-AnaSemiJcsUtf8BytesV001','Test-AnaSemiJcsFileV001','Write-AnaSemiJcsCreateNewV001')
    [Array]::Sort($expectedExports, [StringComparer]::Ordinal)
    if ([string]::Join([char]0,$exports) -cne [string]::Join([char]0,$expectedExports)) { throw 'STOP_JCS_MODULE_LOAD_OR_API_DRIFT' }
 
    function New-Check([string]$Id, [string]$Expected, [string]$Actual, [string]$Result, $StopCode) {
        return [ordered]@{ check_id = $Id; expected = $Expected; actual = $Actual; result = $Result; stop_code = $StopCode }
    }
 
    $vectors = [IO.File]::ReadAllText($ExpectedVectorsPath, [Text.Encoding]::UTF8) | ConvertFrom-Json
    $checks = New-Object Collections.Generic.List[object]
    $spec = @(
        [pscustomobject]@{ Id = 'ARGV_QUOTING'; Stop = 'STOP_L1_ARGV_QUOTING'; Action = {
            $actual = [AnaSemi.WindowsCommandLineV006]::QuoteAndJoin([string[]]@('plain','space value',''))
            if ($actual -cne 'plain "space value" ""') { throw ('QUOTE:' + $actual) }
        }},
        [pscustomobject]@{ Id = 'ARGV_FINGERPRINT'; Stop = 'STOP_L1_ARGV_FINGERPRINT'; Action = {
            $sample = [string[]]@('one','two words','three')
            if ([AnaSemi.WindowsCommandLineV006]::Fingerprint($sample) -cne (Get-ArgvFingerprint $sample)) { throw 'FINGERPRINT' }
        }},
        [pscustomobject]@{ Id = 'ENVELOPE_EXTRA'; Stop = 'STOP_L1_ENVELOPE_EXTRA'; Action = {
            $caught = $null
            try { [void][AnaSemi.ProcessResultEnvelopeValidatorV006]::ValidateSingle([object[]]@('sentinel','second')) }
            catch { $caught = Get-ContractStopCode $_ }
            if ($caught -cne 'STOP_PROCESS_RESULT_COUNT_TYPE_OR_PROPERTY_DRIFT') { throw ('ACTUAL:' + $caught) }
        }},
        [pscustomobject]@{ Id = 'ENVELOPE_MISSING'; Stop = 'STOP_L1_ENVELOPE_MISSING'; Action = {
            $bad = [pscustomobject]@{ schema_id = 'ANA-SEMI-NATIVE-PROCESS-RESULT-V005' }
            $caught = $null
            try { [void][AnaSemi.ProcessResultEnvelopeValidatorV006]::ValidateSingle([object[]]@($bad)) }
            catch { $caught = Get-ContractStopCode $_ }
            if ($caught -cne 'STOP_PROCESS_RESULT_COUNT_TYPE_OR_PROPERTY_DRIFT') { throw ('ACTUAL:' + $caught) }
        }},
        [pscustomobject]@{ Id = 'RESULT_STATE_MATRIX'; Stop = 'STOP_L1_RESULT_STATE_MATRIX'; Action = {
            if ([string]::Join('|', @($vectors.property_contract.wrapper_status)) -cne 'RETURNED|PROCESS_START_FAILED|TIMED_OUT|COPY_FAILED') { throw 'WRAPPER' }
            if ([string]::Join('|', @($vectors.property_contract.child_liveness)) -cne 'EXITED|NOT_STARTED') { throw 'LIVENESS' }
            if ([uint16]$vectors.property_contract.property_count -ne 22 -or @($vectors.property_contract.property_names).Count -ne 22) { throw 'PROPERTY' }
        }},
        [pscustomobject]@{ Id = 'RAW_PREIMAGE'; Stop = 'STOP_L1_RAW_PREIMAGE'; Action = {
            foreach ($property in $vectors.raw_preimages.PSObject.Properties) {
                $item = $property.Value
                $stdout = Decode-EscapedBytes ([string]$item.stdout_escaped)
                $stderr = Decode-EscapedBytes ([string]$item.stderr_escaped)
                if ([uint64]$stdout.Length -ne [uint64]$item.stdout_bytes -or (Get-HexSha256Bytes $stdout) -cne [string]$item.stdout_sha256) { throw ('STDOUT:' + $property.Name) }
                if ([uint64]$stderr.Length -ne [uint64]$item.stderr_bytes -or (Get-HexSha256Bytes $stderr) -cne [string]$item.stderr_sha256) { throw ('STDERR:' + $property.Name) }
            }
        }},
        [pscustomobject]@{ Id = 'REAL_13_TARGET_CONTRACT'; Stop = 'STOP_L1_REAL_13_TARGET_CONTRACT'; Action = {
            $ids = 1..13 | ForEach-Object { 'T{0:d2}' -f $_ }
            if (@($ids | Select-Object -Unique).Count -ne 13) { throw 'TARGET_IDS' }
            $statuses = @('INPUT_READY','PROCESS_OUTPUT_PASS','PROCESS_OUTPUT_FAIL','EMPTY_STDERR_PASS','NOT_RUN_UPSTREAM_STOP','RECEIPT_FINALIZED','MANIFEST_SELF_EXTERNAL_HASH','PROCESS_RESULT_READY','PROCESS_RESULT_CONTRACT_FAILED','PROCESS_RESULT_SIDECAR_FAILED')
            if (@($statuses | Select-Object -Unique).Count -ne 10) { throw 'STATUS_ENUM' }
        }},
        [pscustomobject]@{ Id = 'SYNTHETIC_30_TARGET_CONTRACT'; Stop = 'STOP_L1_SYNTHETIC_30_TARGET_CONTRACT'; Action = {
            $rows = @($vectors.manifest_contract.rows)
            if ($rows.Count -ne 30 -or [uint16]$vectors.manifest_contract.target_count -ne 30) { throw 'COUNT' }
            for ($index = 0; $index -lt 30; $index++) { if ($rows[$index].target_id -cne ('ST{0:d2}' -f ($index + 1))) { throw 'ORDER' } }
            if (@($rows.path | Select-Object -Unique).Count -ne 30) { throw 'PATH_UNIQUE' }
            $expectedCounts = @{ DESCRIPTOR_READY = 3; FIXTURE_READY = 1; RAW_READY = 12; SIDECAR_READY = 5; PROBE_PASS = 4; SENTINEL_UNCHANGED = 2; SUMMARY_PASS = 1; RECEIPT_FINALIZED = 1; MANIFEST_SELF_EXTERNAL_HASH = 1 }
            foreach ($key in $expectedCounts.Keys) { if (@($rows | Where-Object { $_.status -ceq $key }).Count -ne $expectedCounts[$key]) { throw ('STATUS:' + $key) } }
        }},
        [pscustomobject]@{ Id = 'CREATE_NEW_DECISION'; Stop = 'STOP_L1_CREATE_NEW_DECISION'; Action = {
            function Get-Decision([bool]$Exists, [bool]$EscapesRoot) { if ($Exists -or $EscapesRoot) { return 'STOP_TARGET_ALREADY_EXISTS' }; return 'ALLOW_CREATE_NEW' }
            if ((Get-Decision $false $false) -cne 'ALLOW_CREATE_NEW') { throw 'ABSENT' }
            if ((Get-Decision $true $false) -cne 'STOP_TARGET_ALREADY_EXISTS') { throw 'EXISTS' }
            if ((Get-Decision $false $true) -cne 'STOP_TARGET_ALREADY_EXISTS') { throw 'ESCAPE' }
        }}
    )
 
    $firstFailure = $null
    foreach ($item in $spec) {
        if ($null -ne $firstFailure) {
            $checks.Add((New-Check $item.Id 'PASS' 'NOT_RUN_UPSTREAM_STOP' 'NOT_RUN' 'STOP_UPSTREAM_NOT_RUN'))
            continue
        }
        try {
            [void](& $item.Action)
            $checks.Add((New-Check $item.Id 'PASS' 'PASS' 'PASS' $null))
        }
        catch {
            $firstFailure = $item.Stop
            $checks.Add((New-Check $item.Id 'PASS' ('FAIL:' + $_.Exception.Message) 'FAIL' $firstFailure))
        }
    }
 
    $sourceHashes = [ordered]@{}
    $sourcePaths = @('dev/ana-dev/AnaSemi.NativeProcessRunnerV006.R1.cs','dev/ana-dev/AnaSemi.JcsEvidenceWriterV001.psm1','dev/ana-dev/Invoke-AnaSemiWrapperSelftestV006.R1.ps1','dev/ana-dev/synthetic-child-v006-r1.ps1','dev/ana-dev/test/Test-AnaSemiNativeProcessRunnerV006.R1.Static.ps1','dev/ana-dev/test/Test-InvokeAnaSemiWrapperSelftestV006.R1.Static.ps1','dev/ana-dev/test/V007ExpectedVectors.R1.json','dev/ana-dev/test/Invoke-AnaSemiImplementationValidationV002.ps1')
    for ($index = 0; $index -lt $sourcePaths.Count; $index++) { $sourceHashes[('R{0:d2}' -f ($index + 1))] = Get-HexSha256File (Join-Path $ProjectRoot $sourcePaths[$index]) }
    $publishedInfo = Get-Item -LiteralPath $RunnerAssemblyPath
    $publishedHash = Get-HexSha256File $RunnerAssemblyPath
    $passCount = @($checks | Where-Object { $_.result -ceq 'PASS' }).Count
    $failCount = @($checks | Where-Object { $_.result -ceq 'FAIL' }).Count
    $notRunCount = @($checks | Where-Object { $_.result -ceq 'NOT_RUN' }).Count
    $failedCheck = @($checks | Where-Object { $_.result -ceq 'FAIL' } | Select-Object -First 1)
    $vectorsInfo = Get-Item -LiteralPath $ExpectedVectorsPath
    $result = [ordered]@{
        check_count = [uint16]$checks.Count
        checks = $checks.ToArray()
        created_at = [DateTimeOffset]::Now.ToString('o')
        expected_vectors_bytes = [uint64]$vectorsInfo.Length
        expected_vectors_path = [IO.Path]::GetFullPath($ExpectedVectorsPath)
        expected_vectors_sha256 = Get-HexSha256File $ExpectedVectorsPath
        failed_check_count = [uint16]$failCount
        failed_check_id = if ($failedCheck.Count -eq 0) { $null } else { [string]$failedCheck[0].check_id }
        passed_check_count = [uint16]$passCount
        primary_stop_code = $firstFailure
        run_id = 'RUN-DEV-ANA-SEMI-ROOT-PREFLIGHT-V007-REPAIR-IMPLEMENTATION-20260725-001'
        runner_assembly_bytes = [uint64]$publishedInfo.Length
        runner_assembly_path = [IO.Path]::GetFullPath($RunnerAssemblyPath)
        runner_assembly_sha256 = $publishedHash
        schema_id = 'ANA-SEMI-IMPLEMENTATION-L1-JCS-V003'
        source_hashes = $sourceHashes
        status = if ($failCount -eq 0) { 'TEST_PASS' } else { 'TEST_FAIL' }
    }
    [void](Write-AnaSemiJcsCreateNewV001 -Path $OutputPath -Value $result)
    if ($null -ne $firstFailure) {
        $failure = New-Object InvalidOperationException($firstFailure)
        $failure.Data['StopCode'] = $firstFailure
        $failure.Data['FailedCheckId'] = [string]$failedCheck[0].check_id
        throw $failure
    }
}