Sample code for 30+ languages & platforms
B4X Requires Chilkat v11.6.0+

S3 Http: Resume and Recover a Multipart Upload

See more S3 - HTTP Examples

Uses Chilkat.Http with Amazon S3 general purpose buckets and Signature Version 4. These examples do not cover directory buckets/S3 Express, access-point ARNs, Outposts, or other specialized endpoints. They target the commercial AWS partition; other partitions need their documented endpoint suffix.

Load private qa_data/aws/s3.json containing nonempty string fields access_key and secret_key, plus session_token for temporary credentials. Prefer short-lived role credentials. These samples do not discover AWS profiles or refresh credentials. Set the bucket's actual region and replace sample bucket names and object keys. TLS certificate verification is explicitly enabled. Keep detailed HTTP diagnostics private because they can contain credentials or presigned URLs.

Uses explicit signed Http requests to preserve query parameters, conditional headers, and full responses. The included SigV4 block signs the exact path, sorted encoded query and headers used by this example; it is not a general-purpose HTTP signing library. Keep the clock accurate and do not change signed data after signing. Code requires Chilkat 11.6.0 or later; locally tested with 11.8.0.

Uses a private checkpoint directory for one upload and an immutable source file. Run one process per checkpoint; never run upload/resume concurrently with abort. The fixed 8 MiB part size limits this demonstration to nonempty files of at most 10,000 parts (78.125 GiB). It does not impose that limit on S3 itself; choose larger valid part sizes for larger objects.

Uses SHA-256 COMPOSITE multipart checksums, validates part checksums, and verifies the returned composite checksum. ETags are retained for completion but never treated as MD5. Completion can return an error inside HTTP 200; the XML result is checked. Source identity is SHA-256, not just filename/length. The checkpoint contains no AWS credentials.

Requires s3:PutObject, s3:ListMultipartUploadParts for resume, and s3:GetObject for uncertain-completion recovery, plus relevant KMS permissions if bucket defaults use KMS. Incomplete parts incur storage charges until completed or aborted. Configure a suitable incomplete-multipart lifecycle rule as an operational safeguard. Timeout during initiation may leave an upload without a checkpoint; list uploads and investigate before initiating another.

Lists all uploaded parts and reuses only parts whose SHA-256 and byte count match the local source; mismatched parts are replaced. If ListParts returns NoSuchUpload after a recorded completion attempt, a checksum-enabled HEAD must match the unique upload token, source hash, composite checksum and size before recovery is reported. A missing upload alone is never treated as completion. If another write has replaced the current object, inspect version history manually.

AWS reference

Chilkat B4X Downloads

B4X
Dim success As Boolean = False

Dim stringCompare As ChilkatStringBuilder
stringCompare.Initialize
'  This example requires the Chilkat API to have been previously unlocked.
'  See Global Unlock Sample for sample code.
'  Load private credentials; never put access keys or session tokens in source.
Dim credentials As ChilkatJsonObject
credentials.Initialize
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/s3.json")
If success <> True Then
    Log("Could not load private S3 credentials.")
    Return
End If

stringCompare.SetString(credentials.StringOf("access_key"))
Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = True) Then
    Log("Missing or invalid access_key.")
    Return
End If

stringCompare.SetString(credentials.StringOf("secret_key"))
Dim stringMatch2 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = True) Then
    Log("Missing or invalid secret_key.")
    Return
End If

Dim http As ChilkatHttp
http.Initialize("http")
http.AwsAccessKey = credentials.StringOf("access_key")
http.AwsSecretKey = credentials.StringOf("secret_key")
If credentials.HasMember("session_token") = True Then
    stringCompare.SetString(credentials.StringOf("session_token"))
    Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("", True)
    If (credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch3 = True) Then
        Log("session_token must be a nonempty string when supplied.")
        Return
    End If

    http.AwsSessionToken = credentials.StringOf("session_token")
End If

'  Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
'  Set the actual bucket region, not the caller's location.
Dim region As String = "us-west-2"
http.AwsRegion = region
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
endpoint.Append("s3.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
http.AwsEndpoint = endpoint.GetAsString
http.RequireSslCertVerify = True
http.FollowRedirects = False
'  A region redirect is not success. Correct the endpoint and signing region.
Dim bucketName As String = "your-bucket-name"
Dim objectKey As String = "examples/archive.bin"
Dim response As ChilkatHttpResponse
response.Initialize
Dim signer As ChilkatCrypt2
signer.Initialize("signer")
signer.Charset = "utf-8"
signer.HashAlgorithm = "sha256"
signer.EncodingMode = "hexlower"
signer.MacAlgorithm = "hmac"
Dim now As ChilkatDateTime
now.Initialize
Dim timestamp As ChilkatStringBuilder
timestamp.Initialize
Dim canonical As ChilkatStringBuilder
canonical.Initialize
Dim canonicalHeaders As ChilkatStringBuilder
canonicalHeaders.Initialize
Dim signedHeaders As ChilkatStringBuilder
signedHeaders.Initialize
Dim scope As ChilkatStringBuilder
scope.Initialize
Dim stringToSign As ChilkatStringBuilder
stringToSign.Initialize
Dim signingKey As ChilkatStringBuilder
signingKey.Initialize
Dim authorization As ChilkatStringBuilder
authorization.Initialize
Dim url As ChilkatStringBuilder
url.Initialize
Dim query As ChilkatStringBuilder
query.Initialize
Dim number As ChilkatStringBuilder
number.Initialize
Dim host As ChilkatStringBuilder
host.Initialize
Dim uri As ChilkatStringBuilder
uri.Initialize
Dim xml As ChilkatXml
xml.Initialize
Dim amzDate As String
Dim dateStamp As String
Dim payloadHash As String
Dim canonicalHash As String
Dim derivedKey As String
Dim signature As String
Dim replaceCount As Int
host.Append(bucketName)
host.Append(".")
host.Append(endpoint.GetAsString)
'  Encode the original key exactly once, preserving S3 path separators.
uri.SetString(http.UrlEncode(objectKey))
replaceCount = uri.ReplaceNoCase("%2f", "/")
If (uri.StartsWith("/", True) = True) Or (uri.Contains("/../", True) = True) Or (uri.Contains("/./", True) = True) Then
    Log("Use a key without a leading slash or dot path segments for these examples.")
    Return
End If

uri.Prepend("/")
Dim files As ChilkatFileAccess
files.Initialize
Dim filePath As String = "qa_data/bin/archive.bin"
Dim fileSize As String = files.FileSizeStr(filePath)
If files.LastMethodSuccess <> True Then
    Log("Could not read source file size.")
    Return
End If

Dim digest As ChilkatCrypt2
digest.Initialize("digest")
digest.HashAlgorithm = "sha256"
digest.EncodingMode = "hexlower"
Dim sourceHash As String = digest.HashFileENC(filePath)
If digest.LastMethodSuccess <> True Then
    Log("Could not hash source file.")
    Return
End If

digest.EncodingMode = "base64"
Dim sourceChecksum As String = digest.HashFileENC(filePath)
If digest.LastMethodSuccess <> True Then
    Log("Could not compute checksum.")
    Return
End If

Dim statePath As String = "qa_output/s3-multipart/state.json"
Dim pendingPath As String = "qa_output/s3-multipart/completion.json"
Dim receiptPath As String = "qa_output/s3-multipart/completed.json"
Dim state As ChilkatJsonObject
state.Initialize
state.Strict = True
Dim pending As ChilkatJsonObject
pending.Initialize
pending.Strict = True
Dim uploadId As String
Dim uploadToken As String
Dim compositeChecksum As String
success = files.OpenForRead(filePath)
If success <> True Then
    Log("Could not open immutable source file.")
    Return
End If

Dim partSize As Int = 8388608
Dim numParts As Int = files.GetNumBlocks(partSize)
If (numParts < 1) Or (numParts > 10000) Then
    Log("Use a nonempty source of at most 10,000 fixed 8 MiB parts.")
    Return
End If

Dim remoteEtags As ChilkatHashtable
remoteEtags.Initialize
Dim remoteSizes As ChilkatHashtable
remoteSizes.Initialize
Dim remoteChecksums As ChilkatHashtable
remoteChecksums.Initialize
Dim partNumbers As ChilkatHashtable
partNumbers.Initialize
Dim partNumberText As ChilkatStringBuilder
partNumberText.Initialize
success = state.LoadFile(statePath)
If success <> True Then
    Log("Could not load multipart checkpoint.")
    Return
End If

stringCompare.SetString(state.StringOf("schema"))
Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("1", True)
If stringMatch4 <> True Then
    Log("Checkpoint/source identity differs. Do not resume another file or destination.")
    Return
End If

stringCompare.SetString(state.StringOf("bucket"))
Dim stringMatch5 As Boolean = stringCompare.ContentsEqual(bucketName, True)
If stringMatch5 <> True Then
    Log("Checkpoint/source identity differs. Do not resume another file or destination.")
    Return
End If

stringCompare.SetString(state.StringOf("key"))
Dim stringMatch6 As Boolean = stringCompare.ContentsEqual(objectKey, True)
If stringMatch6 <> True Then
    Log("Checkpoint/source identity differs. Do not resume another file or destination.")
    Return
End If

stringCompare.SetString(state.StringOf("region"))
Dim stringMatch7 As Boolean = stringCompare.ContentsEqual(region, True)
If stringMatch7 <> True Then
    Log("Checkpoint/source identity differs. Do not resume another file or destination.")
    Return
End If

stringCompare.SetString(state.StringOf("filePath"))
Dim stringMatch8 As Boolean = stringCompare.ContentsEqual(filePath, True)
If stringMatch8 <> True Then
    Log("Checkpoint/source identity differs. Do not resume another file or destination.")
    Return
End If

stringCompare.SetString(state.StringOf("fileSize"))
Dim stringMatch9 As Boolean = stringCompare.ContentsEqual(fileSize, True)
If stringMatch9 <> True Then
    Log("Checkpoint/source identity differs. Do not resume another file or destination.")
    Return
End If

stringCompare.SetString(state.StringOf("sourceHash"))
Dim stringMatch10 As Boolean = stringCompare.ContentsEqual(sourceHash, True)
If stringMatch10 <> True Then
    Log("Checkpoint/source identity differs. Do not resume another file or destination.")
    Return
End If

stringCompare.SetString(state.StringOf("partSize"))
Dim stringMatch11 As Boolean = stringCompare.ContentsEqual("8388608", True)
If stringMatch11 <> True Then
    Log("Checkpoint/source identity differs. Do not resume another file or destination.")
    Return
End If

uploadId = state.StringOf("uploadId")
uploadToken = state.StringOf("uploadToken")
stringCompare.SetString(uploadId)
Dim stringMatch12 As Boolean = stringCompare.ContentsEqual("", True)
stringCompare.SetString(uploadToken)
Dim stringMatch13 As Boolean = stringCompare.ContentsEqual("", True)
If (stringMatch12 = True) Or (stringMatch13 = True) Or (state.JsonTypeOf("uploadId") <> 1) Or (state.JsonTypeOf("uploadToken") <> 1) Then
    Log("Checkpoint has no upload identity.")
    Return
End If

If files.FileExists(receiptPath) = True Then
    success = pending.LoadFile(receiptPath)
    If success <> True Then
        Log("Invalid completion receipt.")
        Return
    End If

    stringCompare.SetString(pending.StringOf("uploadId"))
    Dim stringMatch14 As Boolean = stringCompare.ContentsEqual(uploadId, True)
    stringCompare.SetString(pending.StringOf("sourceHash"))
    Dim stringMatch15 As Boolean = stringCompare.ContentsEqual(sourceHash, True)
    If (stringMatch14 <> True) Or (stringMatch15 <> True) Then
        Log("Completion receipt belongs to another upload.")
        Return
    End If

    Log("Multipart upload already completed; receipt retained.")
    Return
End If

Dim seen As ChilkatHashtable
seen.Initialize
Dim more As Boolean = True
Dim page As Int = 0
Dim marker As String = ""
Dim truncated As String
Dim item As String
Do While (more = True)
    If page = 10000 Then
        Log("Page bound reached; results are incomplete.")
        Return
    End If

    page = page + 1
    query.Clear
    If query.Length > 0 Then
        query.Append("&")
    End If

    query.Append("max-parts=")
    query.Append(http.UrlEncode("1000"))
    stringCompare.SetString(marker)
    Dim stringMatch16 As Boolean = stringCompare.ContentsEqual("", True)
    If stringMatch16 <> True Then
        If query.Length > 0 Then
            query.Append("&")
        End If

        query.Append("part-number-marker=")
        query.Append(http.UrlEncode(marker))
    End If

    If query.Length > 0 Then
        query.Append("&")
    End If

    query.Append("uploadId=")
    query.Append(http.UrlEncode(uploadId))
    http.ClearHeaders
    success = now.SetFromCurrentSystemTime
    If success <> True Then
        Log("Could not read system time.")
        Return
    End If

    timestamp.SetString(now.GetAsTimestamp(False))
    replaceCount = timestamp.Replace("-", "")
    replaceCount = timestamp.Replace(":", "")
    amzDate = timestamp.GetAsString
    dateStamp = timestamp.GetRange(0, 8, False)
    payloadHash = signer.HashStringENC("")
    If signer.LastMethodSuccess <> True Then
        Log("Could not hash payload.")
        Return
    End If

    canonicalHeaders.Clear
    signedHeaders.Clear
    If signedHeaders.Length > 0 Then
        signedHeaders.Append(";")
    End If

    signedHeaders.Append("host")
    canonicalHeaders.Append("host:")
    canonicalHeaders.Append(host.GetAsString)
    canonicalHeaders.Append(Chr(10))
    http.SetRequestHeader("host", host.GetAsString)
    If signedHeaders.Length > 0 Then
        signedHeaders.Append(";")
    End If

    signedHeaders.Append("x-amz-content-sha256")
    canonicalHeaders.Append("x-amz-content-sha256:")
    canonicalHeaders.Append(payloadHash)
    canonicalHeaders.Append(Chr(10))
    http.SetRequestHeader("x-amz-content-sha256", payloadHash)
    If signedHeaders.Length > 0 Then
        signedHeaders.Append(";")
    End If

    signedHeaders.Append("x-amz-date")
    canonicalHeaders.Append("x-amz-date:")
    canonicalHeaders.Append(amzDate)
    canonicalHeaders.Append(Chr(10))
    http.SetRequestHeader("x-amz-date", amzDate)
    If credentials.HasMember("session_token") = True Then
        If signedHeaders.Length > 0 Then
            signedHeaders.Append(";")
        End If

        signedHeaders.Append("x-amz-security-token")
        canonicalHeaders.Append("x-amz-security-token:")
        canonicalHeaders.Append(credentials.StringOf("session_token"))
        canonicalHeaders.Append(Chr(10))
        http.SetRequestHeader("x-amz-security-token", credentials.StringOf("session_token"))
    End If

    canonical.Clear
    canonical.Append("GET" & Chr(10))
    canonical.Append(uri.GetAsString)
    canonical.Append(Chr(10))
    canonical.Append(query.GetAsString)
    canonical.Append(Chr(10))
    canonical.Append(canonicalHeaders.GetAsString)
    canonical.Append(Chr(10))
    canonical.Append(signedHeaders.GetAsString)
    canonical.Append(Chr(10))
    canonical.Append(payloadHash)
    canonicalHash = signer.HashStringENC(canonical.GetAsString)
    If signer.LastMethodSuccess <> True Then
        Log("Could not hash canonical request.")
        Return
    End If

    scope.Clear
    scope.Append(dateStamp)
    scope.Append("/")
    scope.Append(region)
    scope.Append("/s3/aws4_request")
    stringToSign.Clear
    stringToSign.Append("AWS4-HMAC-SHA256" & Chr(10))
    stringToSign.Append(amzDate)
    stringToSign.Append(Chr(10))
    stringToSign.Append(scope.GetAsString)
    stringToSign.Append(Chr(10))
    stringToSign.Append(canonicalHash)
    signingKey.SetString("AWS4")
    signingKey.Append(credentials.StringOf("secret_key"))
    success = signer.SetMacKeyString(signingKey.GetAsString)
    If success <> True Then
        Log("Could not set signing key.")
        Return
    End If

    derivedKey = signer.MacStringENC(dateStamp)
    If signer.LastMethodSuccess <> True Then
        Log("Could not derive signing key.")
        Return
    End If

    success = signer.SetMacKeyEncoded(derivedKey, "hex")
    If success <> True Then
        Log("Could not set signing key.")
        Return
    End If

    derivedKey = signer.MacStringENC(region)
    If signer.LastMethodSuccess <> True Then
        Log("Could not derive signing key.")
        Return
    End If

    success = signer.SetMacKeyEncoded(derivedKey, "hex")
    If success <> True Then
        Log("Could not set signing key.")
        Return
    End If

    derivedKey = signer.MacStringENC("s3")
    If signer.LastMethodSuccess <> True Then
        Log("Could not derive signing key.")
        Return
    End If

    success = signer.SetMacKeyEncoded(derivedKey, "hex")
    If success <> True Then
        Log("Could not set signing key.")
        Return
    End If

    derivedKey = signer.MacStringENC("aws4_request")
    If signer.LastMethodSuccess <> True Then
        Log("Could not derive signing key.")
        Return
    End If

    success = signer.SetMacKeyEncoded(derivedKey, "hex")
    If success <> True Then
        Log("Could not set signing key.")
        Return
    End If

    signature = signer.MacStringENC(stringToSign.GetAsString)
    If signer.LastMethodSuccess <> True Then
        Log("Could not sign request.")
        Return
    End If

    authorization.Clear
    authorization.Append("AWS4-HMAC-SHA256 Credential=")
    authorization.Append(credentials.StringOf("access_key"))
    authorization.Append("/")
    authorization.Append(scope.GetAsString)
    authorization.Append(", SignedHeaders=")
    authorization.Append(signedHeaders.GetAsString)
    authorization.Append(", Signature=")
    authorization.Append(signature)
    http.SetRequestHeader("Authorization", authorization.GetAsString)
    url.SetString("https://")
    url.Append(host.GetAsString)
    url.Append(uri.GetAsString)
    If query.Length > 0 Then
        url.Append("?")
        url.Append(query.GetAsString)
    End If

    success = http.HttpNoBody("GET", url.GetAsString, response)
    If response.StatusCode = 404 Then
        success = xml.LoadXml(response.BodyStr)
        If success <> True Then
            Log("Could not parse missing-upload response.")
            Return
        End If

        stringCompare.SetString(xml.GetChildContent("Code"))
        Dim stringMatch17 As Boolean = stringCompare.ContentsEqual("NoSuchUpload", True)
        If stringMatch17 <> True Then
            Log("404 was not NoSuchUpload; inspect target bucket/key.")
            Return
        End If

        success = pending.LoadFile(pendingPath)
        If success <> True Then
            Log("Upload no longer exists. No valid pending completion record; inspect object state manually.")
            Return
        End If

        stringCompare.SetString(pending.StringOf("uploadId"))
        Dim stringMatch18 As Boolean = stringCompare.ContentsEqual(uploadId, True)
        If stringMatch18 <> True Then
            Log("Pending completion does not match this upload.")
            Return
        End If

        stringCompare.SetString(pending.StringOf("sourceHash"))
        Dim stringMatch19 As Boolean = stringCompare.ContentsEqual(sourceHash, True)
        If stringMatch19 <> True Then
            Log("Pending completion does not match this upload.")
            Return
        End If

        stringCompare.SetString(pending.StringOf("uploadToken"))
        Dim stringMatch20 As Boolean = stringCompare.ContentsEqual(uploadToken, True)
        If stringMatch20 <> True Then
            Log("Pending completion does not match this upload.")
            Return
        End If

        compositeChecksum = pending.StringOf("checksum")
        stringCompare.SetString(compositeChecksum)
        Dim stringMatch21 As Boolean = stringCompare.ContentsEqual("", True)
        If (pending.LastMethodSuccess <> True) Or (stringMatch21 = True) Then
            Log("Missing pending checksum.")
            Return
        End If

        query.Clear
        http.ClearHeaders
        success = now.SetFromCurrentSystemTime
        If success <> True Then
            Log("Could not read system time.")
            Return
        End If

        timestamp.SetString(now.GetAsTimestamp(False))
        replaceCount = timestamp.Replace("-", "")
        replaceCount = timestamp.Replace(":", "")
        amzDate = timestamp.GetAsString
        dateStamp = timestamp.GetRange(0, 8, False)
        payloadHash = signer.HashStringENC("")
        If signer.LastMethodSuccess <> True Then
            Log("Could not hash payload.")
            Return
        End If

        canonicalHeaders.Clear
        signedHeaders.Clear
        If signedHeaders.Length > 0 Then
            signedHeaders.Append(";")
        End If

        signedHeaders.Append("host")
        canonicalHeaders.Append("host:")
        canonicalHeaders.Append(host.GetAsString)
        canonicalHeaders.Append(Chr(10))
        http.SetRequestHeader("host", host.GetAsString)
        If signedHeaders.Length > 0 Then
            signedHeaders.Append(";")
        End If

        signedHeaders.Append("x-amz-checksum-mode")
        canonicalHeaders.Append("x-amz-checksum-mode:")
        canonicalHeaders.Append("ENABLED")
        canonicalHeaders.Append(Chr(10))
        http.SetRequestHeader("x-amz-checksum-mode", "ENABLED")
        If signedHeaders.Length > 0 Then
            signedHeaders.Append(";")
        End If

        signedHeaders.Append("x-amz-content-sha256")
        canonicalHeaders.Append("x-amz-content-sha256:")
        canonicalHeaders.Append(payloadHash)
        canonicalHeaders.Append(Chr(10))
        http.SetRequestHeader("x-amz-content-sha256", payloadHash)
        If signedHeaders.Length > 0 Then
            signedHeaders.Append(";")
        End If

        signedHeaders.Append("x-amz-date")
        canonicalHeaders.Append("x-amz-date:")
        canonicalHeaders.Append(amzDate)
        canonicalHeaders.Append(Chr(10))
        http.SetRequestHeader("x-amz-date", amzDate)
        If credentials.HasMember("session_token") = True Then
            If signedHeaders.Length > 0 Then
                signedHeaders.Append(";")
            End If

            signedHeaders.Append("x-amz-security-token")
            canonicalHeaders.Append("x-amz-security-token:")
            canonicalHeaders.Append(credentials.StringOf("session_token"))
            canonicalHeaders.Append(Chr(10))
            http.SetRequestHeader("x-amz-security-token", credentials.StringOf("session_token"))
        End If

        canonical.Clear
        canonical.Append("HEAD" & Chr(10))
        canonical.Append(uri.GetAsString)
        canonical.Append(Chr(10))
        canonical.Append(query.GetAsString)
        canonical.Append(Chr(10))
        canonical.Append(canonicalHeaders.GetAsString)
        canonical.Append(Chr(10))
        canonical.Append(signedHeaders.GetAsString)
        canonical.Append(Chr(10))
        canonical.Append(payloadHash)
        canonicalHash = signer.HashStringENC(canonical.GetAsString)
        If signer.LastMethodSuccess <> True Then
            Log("Could not hash canonical request.")
            Return
        End If

        scope.Clear
        scope.Append(dateStamp)
        scope.Append("/")
        scope.Append(region)
        scope.Append("/s3/aws4_request")
        stringToSign.Clear
        stringToSign.Append("AWS4-HMAC-SHA256" & Chr(10))
        stringToSign.Append(amzDate)
        stringToSign.Append(Chr(10))
        stringToSign.Append(scope.GetAsString)
        stringToSign.Append(Chr(10))
        stringToSign.Append(canonicalHash)
        signingKey.SetString("AWS4")
        signingKey.Append(credentials.StringOf("secret_key"))
        success = signer.SetMacKeyString(signingKey.GetAsString)
        If success <> True Then
            Log("Could not set signing key.")
            Return
        End If

        derivedKey = signer.MacStringENC(dateStamp)
        If signer.LastMethodSuccess <> True Then
            Log("Could not derive signing key.")
            Return
        End If

        success = signer.SetMacKeyEncoded(derivedKey, "hex")
        If success <> True Then
            Log("Could not set signing key.")
            Return
        End If

        derivedKey = signer.MacStringENC(region)
        If signer.LastMethodSuccess <> True Then
            Log("Could not derive signing key.")
            Return
        End If

        success = signer.SetMacKeyEncoded(derivedKey, "hex")
        If success <> True Then
            Log("Could not set signing key.")
            Return
        End If

        derivedKey = signer.MacStringENC("s3")
        If signer.LastMethodSuccess <> True Then
            Log("Could not derive signing key.")
            Return
        End If

        success = signer.SetMacKeyEncoded(derivedKey, "hex")
        If success <> True Then
            Log("Could not set signing key.")
            Return
        End If

        derivedKey = signer.MacStringENC("aws4_request")
        If signer.LastMethodSuccess <> True Then
            Log("Could not derive signing key.")
            Return
        End If

        success = signer.SetMacKeyEncoded(derivedKey, "hex")
        If success <> True Then
            Log("Could not set signing key.")
            Return
        End If

        signature = signer.MacStringENC(stringToSign.GetAsString)
        If signer.LastMethodSuccess <> True Then
            Log("Could not sign request.")
            Return
        End If

        authorization.Clear
        authorization.Append("AWS4-HMAC-SHA256 Credential=")
        authorization.Append(credentials.StringOf("access_key"))
        authorization.Append("/")
        authorization.Append(scope.GetAsString)
        authorization.Append(", SignedHeaders=")
        authorization.Append(signedHeaders.GetAsString)
        authorization.Append(", Signature=")
        authorization.Append(signature)
        http.SetRequestHeader("Authorization", authorization.GetAsString)
        url.SetString("https://")
        url.Append(host.GetAsString)
        url.Append(uri.GetAsString)
        If query.Length > 0 Then
            url.Append("?")
            url.Append(query.GetAsString)
        End If

        success = http.HttpNoBody("HEAD", url.GetAsString, response)
        If (success <> True) Or (response.StatusCode <> 200) Then
            Log("Request failed or returned unexpected HTTP status: " & response.StatusCode)
            '  Preserve progress. Inspect full diagnostics privately; do not log secrets.
            Return
        End If

        stringCompare.SetString(response.GetHeaderField("x-amz-meta-upload-token"))
        Dim stringMatch22 As Boolean = stringCompare.ContentsEqual(uploadToken, True)
        If stringMatch22 <> True Then
            Log("Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state.")
            Return
        End If

        stringCompare.SetString(response.GetHeaderField("x-amz-meta-source-sha256"))
        Dim stringMatch23 As Boolean = stringCompare.ContentsEqual(sourceHash, True)
        If stringMatch23 <> True Then
            Log("Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state.")
            Return
        End If

        stringCompare.SetString(response.GetHeaderField("x-amz-checksum-sha256"))
        Dim stringMatch24 As Boolean = stringCompare.ContentsEqual(compositeChecksum, True)
        If stringMatch24 <> True Then
            Log("Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state.")
            Return
        End If

        stringCompare.SetString(response.GetHeaderField("x-amz-checksum-type"))
        Dim stringMatch25 As Boolean = stringCompare.ContentsEqual("COMPOSITE", True)
        If stringMatch25 <> True Then
            Log("Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state.")
            Return
        End If

        stringCompare.SetString(response.GetHeaderField("Content-Length"))
        Dim stringMatch26 As Boolean = stringCompare.ContentsEqual(fileSize, True)
        If stringMatch26 <> True Then
            Log("Cannot confirm uncertain completion. Keep checkpoint and inspect versions/object state.")
            Return
        End If

        success = state.UpdateString("compositeChecksum", compositeChecksum)
        If success <> True Then
            Log("Could not save compositeChecksum.")
            Return
        End If

        success = state.WriteFile("qa_output/s3-multipart/completed.json.tmp")
        If success <> True Then
            Log("Completion succeeded but receipt could not be saved; preserve the checkpoint.")
            Return
        End If

        success = files.FileRename("qa_output/s3-multipart/completed.json.tmp", receiptPath)
        If success <> True Then
            Log("Completion receipt remains at its temporary path.")
            Return
        End If

        Log("Multipart upload completed and verified.")
        Return
    End If

    If (success <> True) Or (response.StatusCode <> 200) Then
        Log("Request failed or returned unexpected HTTP status: " & response.StatusCode)
        '  Preserve progress. Inspect full diagnostics privately; do not log secrets.
        Return
    End If

    success = xml.LoadXml(response.BodyStr)
    If success <> True Then
        Log("Invalid XML response.")
        Return
    End If

    stringCompare.SetString(xml.Tag)
    Dim stringMatch27 As Boolean = stringCompare.ContentsEqual("ListPartsResult", True)
    If stringMatch27 <> True Then
        Log("Unexpected XML result, possibly an embedded S3 error. Inspect privately.")
        Return
    End If

    Dim i As Int = 0
    Do While (i < xml.NumChildrenHavingTag("Part"))
        xml.I = i
        Dim remoteNumber As Int = xml.GetChildIntValue("Part[i]|PartNumber")
        If (xml.LastMethodSuccess <> True) Or (remoteNumber < 1) Or (remoteNumber > numParts) Then
            Log("Unexpected remote part number.")
            Return
        End If

        partNumberText.Clear
        partNumberText.AppendInt(remoteNumber)
        If partNumbers.Contains(partNumberText.GetAsString) = True Then
            Log("Duplicate remote part number.")
            Return
        End If

        success = partNumbers.AddStr(partNumberText.GetAsString, "seen")
        If success <> True Then
            Log("Could not track remote part.")
            Return
        End If

        item = xml.GetChildContent("Part[i]|ETag")
        stringCompare.SetString(item)
        Dim stringMatch28 As Boolean = stringCompare.ContentsEqual("", True)
        If (xml.LastMethodSuccess <> True) Or (stringMatch28 = True) Then
            Log("Missing required Part[i]|ETag.")
            Return
        End If

        success = remoteEtags.AddStr(partNumberText.GetAsString, item)
        If success <> True Then
            Log("Could not retain part ETag.")
            Return
        End If

        item = xml.GetChildContent("Part[i]|Size")
        stringCompare.SetString(item)
        Dim stringMatch29 As Boolean = stringCompare.ContentsEqual("", True)
        If (xml.LastMethodSuccess <> True) Or (stringMatch29 = True) Then
            Log("Missing required Part[i]|Size.")
            Return
        End If

        success = remoteSizes.AddStr(partNumberText.GetAsString, item)
        If success <> True Then
            Log("Could not retain part size.")
            Return
        End If

        item = xml.GetChildContent("Part[i]|ChecksumSHA256")
        If xml.LastMethodSuccess = True Then
            success = remoteChecksums.AddStr(partNumberText.GetAsString, item)
            If success <> True Then
                Log("Could not retain part checksum.")
                Return
            End If

        End If

        i = i + 1
    Loop
    truncated = xml.GetChildContent("IsTruncated")
    stringCompare.SetString(truncated)
    Dim stringMatch30 As Boolean = stringCompare.ContentsEqual("", True)
    If (xml.LastMethodSuccess <> True) Or (stringMatch30 = True) Then
        Log("Missing required IsTruncated.")
        Return
    End If

    stringCompare.SetString(truncated)
    Dim stringMatch31 As Boolean = stringCompare.ContentsEqual("true", True)
    stringCompare.SetString(truncated)
    Dim stringMatch32 As Boolean = stringCompare.ContentsEqual("false", True)
    If (stringMatch31 <> True) And (stringMatch32 <> True) Then
        Log("Invalid IsTruncated; results are incomplete.")
        Return
    End If

    more = False
    stringCompare.SetString(truncated)
    Dim stringMatch33 As Boolean = stringCompare.ContentsEqual("true", True)
    If stringMatch33 = True Then
        marker = xml.GetChildContent("NextPartNumberMarker")
        stringCompare.SetString(marker)
        Dim stringMatch34 As Boolean = stringCompare.ContentsEqual("", True)
        If (xml.LastMethodSuccess <> True) Or (stringMatch34 = True) Then
            Log("Missing required NextPartNumberMarker.")
            Return
        End If

        If seen.Contains(marker) = True Then
            Log("Repeated pagination marker; results are incomplete.")
            Return
        End If

        success = seen.AddStr(marker, "seen")
        If success <> True Then
            Log("Could not track marker.")
            Return
        End If

        more = True
    End If

Loop
Dim part As ChilkatBinData
part.Initialize
Dim concatenatedDigests As ChilkatBinData
concatenatedDigests.Initialize
Dim completion As ChilkatXml
completion.Initialize
completion.Tag = "CompleteMultipartUpload"
completion.AddAttribute("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/")
Dim partIndex As Int = 0
Dim partChecksum As String
Dim partEtag As String
Dim partHash As String
Dim confirmed As String
Dim sizeText As String
Do While (partIndex < numParts)
    part.Clear
    success = files.ReadBlockBd(partIndex, partSize, part)
    If success <> True Then
        Log("Could not read source part; preserve checkpoint.")
        Return
    End If

    If (part.NumBytes = 0) Or ((partIndex < numParts - 1) And (part.NumBytes <> partSize)) Then
        Log("Source changed or part read was incomplete.")
        Return
    End If

    partChecksum = digest.HashBdENC(part)
    If digest.LastMethodSuccess <> True Then
        Log("Could not checksum part.")
        Return
    End If

    partHash = signer.HashBdENC(part)
    If signer.LastMethodSuccess <> True Then
        Log("Could not hash part.")
        Return
    End If

    success = concatenatedDigests.AppendEncoded(partChecksum, "base64")
    If success <> True Then
        Log("Could not accumulate part digests.")
        Return
    End If

    partNumberText.Clear
    partNumberText.AppendInt(partIndex + 1)
    number.Clear
    number.AppendInt(part.NumBytes)
    sizeText = number.GetAsString
    Dim partNumberKey As String = partNumberText.GetAsString
    Dim reuse As Boolean = False
    partEtag = ""
    If remoteChecksums.Contains(partNumberKey) = True Then
        stringCompare.SetString(remoteChecksums.LookupStr(partNumberKey))
        Dim stringMatch35 As Boolean = stringCompare.ContentsEqual(partChecksum, True)
        stringCompare.SetString(remoteSizes.LookupStr(partNumberKey))
        Dim stringMatch36 As Boolean = stringCompare.ContentsEqual(sizeText, True)
        If (stringMatch35 = True) And (stringMatch36 = True) Then
            partEtag = remoteEtags.LookupStr(partNumberKey)
            stringCompare.SetString(partEtag)
            Dim stringMatch37 As Boolean = stringCompare.ContentsEqual("", True)
            If (remoteEtags.LastMethodSuccess = True) And (stringMatch37 <> True) Then
                reuse = True
            End If

        End If

    End If

    If reuse <> True Then
        query.Clear
        If query.Length > 0 Then
            query.Append("&")
        End If

        query.Append("partNumber=")
        query.Append(http.UrlEncode(partNumberText.GetAsString))
        If query.Length > 0 Then
            query.Append("&")
        End If

        query.Append("uploadId=")
        query.Append(http.UrlEncode(uploadId))
        http.ClearHeaders
        success = now.SetFromCurrentSystemTime
        If success <> True Then
            Log("Could not read system time.")
            Return
        End If

        timestamp.SetString(now.GetAsTimestamp(False))
        replaceCount = timestamp.Replace("-", "")
        replaceCount = timestamp.Replace(":", "")
        amzDate = timestamp.GetAsString
        dateStamp = timestamp.GetRange(0, 8, False)
        payloadHash = partHash
        canonicalHeaders.Clear
        signedHeaders.Clear
        If signedHeaders.Length > 0 Then
            signedHeaders.Append(";")
        End If

        signedHeaders.Append("host")
        canonicalHeaders.Append("host:")
        canonicalHeaders.Append(host.GetAsString)
        canonicalHeaders.Append(Chr(10))
        http.SetRequestHeader("host", host.GetAsString)
        If signedHeaders.Length > 0 Then
            signedHeaders.Append(";")
        End If

        signedHeaders.Append("x-amz-checksum-sha256")
        canonicalHeaders.Append("x-amz-checksum-sha256:")
        canonicalHeaders.Append(partChecksum)
        canonicalHeaders.Append(Chr(10))
        http.SetRequestHeader("x-amz-checksum-sha256", partChecksum)
        If signedHeaders.Length > 0 Then
            signedHeaders.Append(";")
        End If

        signedHeaders.Append("x-amz-content-sha256")
        canonicalHeaders.Append("x-amz-content-sha256:")
        canonicalHeaders.Append(payloadHash)
        canonicalHeaders.Append(Chr(10))
        http.SetRequestHeader("x-amz-content-sha256", payloadHash)
        If signedHeaders.Length > 0 Then
            signedHeaders.Append(";")
        End If

        signedHeaders.Append("x-amz-date")
        canonicalHeaders.Append("x-amz-date:")
        canonicalHeaders.Append(amzDate)
        canonicalHeaders.Append(Chr(10))
        http.SetRequestHeader("x-amz-date", amzDate)
        If credentials.HasMember("session_token") = True Then
            If signedHeaders.Length > 0 Then
                signedHeaders.Append(";")
            End If

            signedHeaders.Append("x-amz-security-token")
            canonicalHeaders.Append("x-amz-security-token:")
            canonicalHeaders.Append(credentials.StringOf("session_token"))
            canonicalHeaders.Append(Chr(10))
            http.SetRequestHeader("x-amz-security-token", credentials.StringOf("session_token"))
        End If

        canonical.Clear
        canonical.Append("PUT" & Chr(10))
        canonical.Append(uri.GetAsString)
        canonical.Append(Chr(10))
        canonical.Append(query.GetAsString)
        canonical.Append(Chr(10))
        canonical.Append(canonicalHeaders.GetAsString)
        canonical.Append(Chr(10))
        canonical.Append(signedHeaders.GetAsString)
        canonical.Append(Chr(10))
        canonical.Append(payloadHash)
        canonicalHash = signer.HashStringENC(canonical.GetAsString)
        If signer.LastMethodSuccess <> True Then
            Log("Could not hash canonical request.")
            Return
        End If

        scope.Clear
        scope.Append(dateStamp)
        scope.Append("/")
        scope.Append(region)
        scope.Append("/s3/aws4_request")
        stringToSign.Clear
        stringToSign.Append("AWS4-HMAC-SHA256" & Chr(10))
        stringToSign.Append(amzDate)
        stringToSign.Append(Chr(10))
        stringToSign.Append(scope.GetAsString)
        stringToSign.Append(Chr(10))
        stringToSign.Append(canonicalHash)
        signingKey.SetString("AWS4")
        signingKey.Append(credentials.StringOf("secret_key"))
        success = signer.SetMacKeyString(signingKey.GetAsString)
        If success <> True Then
            Log("Could not set signing key.")
            Return
        End If

        derivedKey = signer.MacStringENC(dateStamp)
        If signer.LastMethodSuccess <> True Then
            Log("Could not derive signing key.")
            Return
        End If

        success = signer.SetMacKeyEncoded(derivedKey, "hex")
        If success <> True Then
            Log("Could not set signing key.")
            Return
        End If

        derivedKey = signer.MacStringENC(region)
        If signer.LastMethodSuccess <> True Then
            Log("Could not derive signing key.")
            Return
        End If

        success = signer.SetMacKeyEncoded(derivedKey, "hex")
        If success <> True Then
            Log("Could not set signing key.")
            Return
        End If

        derivedKey = signer.MacStringENC("s3")
        If signer.LastMethodSuccess <> True Then
            Log("Could not derive signing key.")
            Return
        End If

        success = signer.SetMacKeyEncoded(derivedKey, "hex")
        If success <> True Then
            Log("Could not set signing key.")
            Return
        End If

        derivedKey = signer.MacStringENC("aws4_request")
        If signer.LastMethodSuccess <> True Then
            Log("Could not derive signing key.")
            Return
        End If

        success = signer.SetMacKeyEncoded(derivedKey, "hex")
        If success <> True Then
            Log("Could not set signing key.")
            Return
        End If

        signature = signer.MacStringENC(stringToSign.GetAsString)
        If signer.LastMethodSuccess <> True Then
            Log("Could not sign request.")
            Return
        End If

        authorization.Clear
        authorization.Append("AWS4-HMAC-SHA256 Credential=")
        authorization.Append(credentials.StringOf("access_key"))
        authorization.Append("/")
        authorization.Append(scope.GetAsString)
        authorization.Append(", SignedHeaders=")
        authorization.Append(signedHeaders.GetAsString)
        authorization.Append(", Signature=")
        authorization.Append(signature)
        http.SetRequestHeader("Authorization", authorization.GetAsString)
        url.SetString("https://")
        url.Append(host.GetAsString)
        url.Append(uri.GetAsString)
        If query.Length > 0 Then
            url.Append("?")
            url.Append(query.GetAsString)
        End If

        success = http.HttpBd("PUT", url.GetAsString, part, "application/octet-stream", response)
        If (success <> True) Or (response.StatusCode <> 200) Then
            Log("Request failed or returned unexpected HTTP status: " & response.StatusCode)
            '  Preserve progress. Inspect full diagnostics privately; do not log secrets.
            Return
        End If

        confirmed = response.GetHeaderField("x-amz-checksum-sha256")
        stringCompare.SetString(confirmed)
        Dim stringMatch38 As Boolean = stringCompare.ContentsEqual("", True)
        If (response.LastMethodSuccess <> True) Or (stringMatch38 = True) Then
            Log("Missing required response header x-amz-checksum-sha256.")
            Return
        End If

        stringCompare.SetString(confirmed)
        Dim stringMatch39 As Boolean = stringCompare.ContentsEqual(partChecksum, True)
        If stringMatch39 <> True Then
            Log("Part checksum mismatch; preserve checkpoint.")
            Return
        End If

        partEtag = response.GetHeaderField("ETag")
        stringCompare.SetString(partEtag)
        Dim stringMatch40 As Boolean = stringCompare.ContentsEqual("", True)
        If (response.LastMethodSuccess <> True) Or (stringMatch40 = True) Then
            Log("Missing required response header ETag.")
            Return
        End If

    Else
        Log("Reusing verified remote part: " & partNumberText.GetAsString)
    End If

    completion.I = partIndex
    completion.UpdateChildContent("Part[i]|PartNumber", partNumberText.GetAsString)
    completion.UpdateChildContent("Part[i]|ETag", partEtag)
    completion.UpdateChildContent("Part[i]|ChecksumSHA256", partChecksum)
    partIndex = partIndex + 1
Loop
files.FileClose
'  Recheck the entire immutable source before committing its parts.
Dim finalSourceHash As String = signer.HashFileENC(filePath)
stringCompare.SetString(finalSourceHash)
Dim stringMatch41 As Boolean = stringCompare.ContentsEqual(sourceHash, True)
If (signer.LastMethodSuccess <> True) Or (stringMatch41 <> True) Then
    Log("Source changed; completion was not sent.")
    Return
End If

compositeChecksum = digest.HashBdENC(concatenatedDigests)
If digest.LastMethodSuccess <> True Then
    Log("Could not compute composite checksum.")
    Return
End If

number.SetString(compositeChecksum)
number.Append("-")
number.AppendInt(numParts)
compositeChecksum = number.GetAsString
success = pending.UpdateString("uploadId", uploadId)
If success <> True Then
    Log("Could not save uploadId.")
    Return
End If

success = pending.UpdateString("sourceHash", sourceHash)
If success <> True Then
    Log("Could not save sourceHash.")
    Return
End If

success = pending.UpdateString("uploadToken", uploadToken)
If success <> True Then
    Log("Could not save uploadToken.")
    Return
End If

success = pending.UpdateString("checksum", compositeChecksum)
If success <> True Then
    Log("Could not save checksum.")
    Return
End If

success = pending.WriteFile(pendingPath)
If success <> True Then
    Log("Could not save completion recovery record.")
    Return
End If

Dim requestBody As String = completion.GetXml
query.Clear
If query.Length > 0 Then
    query.Append("&")
End If

query.Append("uploadId=")
query.Append(http.UrlEncode(uploadId))
http.ClearHeaders
success = now.SetFromCurrentSystemTime
If success <> True Then
    Log("Could not read system time.")
    Return
End If

timestamp.SetString(now.GetAsTimestamp(False))
replaceCount = timestamp.Replace("-", "")
replaceCount = timestamp.Replace(":", "")
amzDate = timestamp.GetAsString
dateStamp = timestamp.GetRange(0, 8, False)
payloadHash = signer.HashStringENC(requestBody)
If signer.LastMethodSuccess <> True Then
    Log("Could not hash payload.")
    Return
End If

canonicalHeaders.Clear
signedHeaders.Clear
If signedHeaders.Length > 0 Then
    signedHeaders.Append(";")
End If

signedHeaders.Append("host")
canonicalHeaders.Append("host:")
canonicalHeaders.Append(host.GetAsString)
canonicalHeaders.Append(Chr(10))
http.SetRequestHeader("host", host.GetAsString)
If signedHeaders.Length > 0 Then
    signedHeaders.Append(";")
End If

signedHeaders.Append("x-amz-checksum-type")
canonicalHeaders.Append("x-amz-checksum-type:")
canonicalHeaders.Append("COMPOSITE")
canonicalHeaders.Append(Chr(10))
http.SetRequestHeader("x-amz-checksum-type", "COMPOSITE")
If signedHeaders.Length > 0 Then
    signedHeaders.Append(";")
End If

signedHeaders.Append("x-amz-content-sha256")
canonicalHeaders.Append("x-amz-content-sha256:")
canonicalHeaders.Append(payloadHash)
canonicalHeaders.Append(Chr(10))
http.SetRequestHeader("x-amz-content-sha256", payloadHash)
If signedHeaders.Length > 0 Then
    signedHeaders.Append(";")
End If

signedHeaders.Append("x-amz-date")
canonicalHeaders.Append("x-amz-date:")
canonicalHeaders.Append(amzDate)
canonicalHeaders.Append(Chr(10))
http.SetRequestHeader("x-amz-date", amzDate)
If credentials.HasMember("session_token") = True Then
    If signedHeaders.Length > 0 Then
        signedHeaders.Append(";")
    End If

    signedHeaders.Append("x-amz-security-token")
    canonicalHeaders.Append("x-amz-security-token:")
    canonicalHeaders.Append(credentials.StringOf("session_token"))
    canonicalHeaders.Append(Chr(10))
    http.SetRequestHeader("x-amz-security-token", credentials.StringOf("session_token"))
End If

canonical.Clear
canonical.Append("POST" & Chr(10))
canonical.Append(uri.GetAsString)
canonical.Append(Chr(10))
canonical.Append(query.GetAsString)
canonical.Append(Chr(10))
canonical.Append(canonicalHeaders.GetAsString)
canonical.Append(Chr(10))
canonical.Append(signedHeaders.GetAsString)
canonical.Append(Chr(10))
canonical.Append(payloadHash)
canonicalHash = signer.HashStringENC(canonical.GetAsString)
If signer.LastMethodSuccess <> True Then
    Log("Could not hash canonical request.")
    Return
End If

scope.Clear
scope.Append(dateStamp)
scope.Append("/")
scope.Append(region)
scope.Append("/s3/aws4_request")
stringToSign.Clear
stringToSign.Append("AWS4-HMAC-SHA256" & Chr(10))
stringToSign.Append(amzDate)
stringToSign.Append(Chr(10))
stringToSign.Append(scope.GetAsString)
stringToSign.Append(Chr(10))
stringToSign.Append(canonicalHash)
signingKey.SetString("AWS4")
signingKey.Append(credentials.StringOf("secret_key"))
success = signer.SetMacKeyString(signingKey.GetAsString)
If success <> True Then
    Log("Could not set signing key.")
    Return
End If

derivedKey = signer.MacStringENC(dateStamp)
If signer.LastMethodSuccess <> True Then
    Log("Could not derive signing key.")
    Return
End If

success = signer.SetMacKeyEncoded(derivedKey, "hex")
If success <> True Then
    Log("Could not set signing key.")
    Return
End If

derivedKey = signer.MacStringENC(region)
If signer.LastMethodSuccess <> True Then
    Log("Could not derive signing key.")
    Return
End If

success = signer.SetMacKeyEncoded(derivedKey, "hex")
If success <> True Then
    Log("Could not set signing key.")
    Return
End If

derivedKey = signer.MacStringENC("s3")
If signer.LastMethodSuccess <> True Then
    Log("Could not derive signing key.")
    Return
End If

success = signer.SetMacKeyEncoded(derivedKey, "hex")
If success <> True Then
    Log("Could not set signing key.")
    Return
End If

derivedKey = signer.MacStringENC("aws4_request")
If signer.LastMethodSuccess <> True Then
    Log("Could not derive signing key.")
    Return
End If

success = signer.SetMacKeyEncoded(derivedKey, "hex")
If success <> True Then
    Log("Could not set signing key.")
    Return
End If

signature = signer.MacStringENC(stringToSign.GetAsString)
If signer.LastMethodSuccess <> True Then
    Log("Could not sign request.")
    Return
End If

authorization.Clear
authorization.Append("AWS4-HMAC-SHA256 Credential=")
authorization.Append(credentials.StringOf("access_key"))
authorization.Append("/")
authorization.Append(scope.GetAsString)
authorization.Append(", SignedHeaders=")
authorization.Append(signedHeaders.GetAsString)
authorization.Append(", Signature=")
authorization.Append(signature)
http.SetRequestHeader("Authorization", authorization.GetAsString)
url.SetString("https://")
url.Append(host.GetAsString)
url.Append(uri.GetAsString)
If query.Length > 0 Then
    url.Append("?")
    url.Append(query.GetAsString)
End If

success = http.HttpStr("POST", url.GetAsString, requestBody, "utf-8", "application/xml", response)
If (success <> True) Or (response.StatusCode <> 200) Then
    Log("Request failed or returned unexpected HTTP status: " & response.StatusCode)
    '  Preserve progress. Inspect full diagnostics privately; do not log secrets.
    Return
End If

success = xml.LoadXml(response.BodyStr)
If success <> True Then
    Log("Invalid XML response.")
    Return
End If

stringCompare.SetString(xml.Tag)
Dim stringMatch42 As Boolean = stringCompare.ContentsEqual("CompleteMultipartUploadResult", True)
If stringMatch42 <> True Then
    Log("Unexpected XML result, possibly an embedded S3 error. Inspect privately.")
    Return
End If

confirmed = xml.GetChildContent("ChecksumSHA256")
stringCompare.SetString(confirmed)
Dim stringMatch43 As Boolean = stringCompare.ContentsEqual("", True)
If (xml.LastMethodSuccess <> True) Or (stringMatch43 = True) Then
    Log("Missing required ChecksumSHA256.")
    Return
End If

stringCompare.SetString(confirmed)
Dim stringMatch44 As Boolean = stringCompare.ContentsEqual(compositeChecksum, True)
If stringMatch44 <> True Then
    Log("Completion checksum differs; preserve checkpoint and inspect object.")
    Return
End If

success = state.UpdateString("compositeChecksum", compositeChecksum)
If success <> True Then
    Log("Could not save compositeChecksum.")
    Return
End If

success = state.WriteFile("qa_output/s3-multipart/completed.json.tmp")
If success <> True Then
    Log("Completion succeeded but receipt could not be saved; preserve the checkpoint.")
    Return
End If

success = files.FileRename("qa_output/s3-multipart/completed.json.tmp", receiptPath)
If success <> True Then
    Log("Completion receipt remains at its temporary path.")
    Return
End If

Log("Multipart upload completed and verified.")