From f7db4161ac28c2bbbe902f0febfdcb7a04e0ff68 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Mon, 16 Nov 2026 11:02:57 -0500 Subject: [PATCH] refactor(openai_api): give request bodies generic deferred and digest parts Request bodies carried albedo-named magic tuples: {albedo_image, Size, Read} for a stored image and {albedo_attest, ...} for Claude's billing attestation. request_body now owns a generic interface instead. `deferred(size, read)` is a part of known size read only while the body is written, and `digest(init, update, emit, placeholder)` is a part whose bytes are a digest of the whole body. Both return a StringTree to place anywhere in the body's iodata, so JSON encoders keep nesting them as before. `zstd` and `gzip` move here from the transport. The module owns the rules and reports them as a typed Invalid: at most one digest part, no deferred part after it, the digest as long as its placeholder (now checked), and no compression for a body with a deferred part. The writer takes a send function rather than a socket. Stored images become deferred parts in types.gleam, and attestation splices a digest part between raw JSON. The JSON coalescer passes any tuple through as a part rather than naming the image tag. --- src/albedo/daemon/images.gleam | 2 +- .../harness/extensions/claude/wire.gleam | 4 +- .../harness/extensions/codex/wire.gleam | 4 +- .../harness/extensions/openai/extension.gleam | 4 +- src/albedo/openai_api/albedo_openai_json.erl | 9 +- .../openai_api/albedo_openai_transport.erl | 17 +- src/albedo/openai_api/attestation.gleam | 41 +- src/albedo/openai_api/request_body.gleam | 407 ++++++++++++------ src/albedo/openai_api/transport.gleam | 81 +--- src/albedo/openai_api/types.gleam | 19 +- test/harness/claude_test.gleam | 10 +- test/harness/messages_cache_test.gleam | 11 +- .../albedo_openai_transport_test_server.erl | 6 +- test/openai_api/transport_test.gleam | 31 +- 14 files changed, 359 insertions(+), 287 deletions(-) diff --git a/src/albedo/daemon/images.gleam b/src/albedo/daemon/images.gleam index d1dad081f..09bb9d966 100644 --- a/src/albedo/daemon/images.gleam +++ b/src/albedo/daemon/images.gleam @@ -2,7 +2,7 @@ //// //// A transcript row keeps an image's hash and metadata; its decoded bytes live //// in `images`. Loading a session therefore reads references, and a payload is -//// read only while a request body is written (albedo_openai_transport.erl). +//// read only while a request body is written, as a deferred body part. //// Rows are content-addressed, so forks and repeated screenshots share one copy. //// Payload reads and inserts live in `albedo/harness/sdk/images`; this module //// keeps the schema, externalizing writes, release, and elision. diff --git a/src/albedo/harness/extensions/claude/wire.gleam b/src/albedo/harness/extensions/claude/wire.gleam index 3d19c825c..1094ac359 100644 --- a/src/albedo/harness/extensions/claude/wire.gleam +++ b/src/albedo/harness/extensions/claude/wire.gleam @@ -14,8 +14,8 @@ import albedo/openai_api import albedo/openai_api/cost import albedo/openai_api/decoding import albedo/openai_api/replay +import albedo/openai_api/request_body import albedo/openai_api/stream -import albedo/openai_api/transport import albedo/openai_api/types import albedo_bytes/scalars import gleam/bit_array @@ -58,7 +58,7 @@ pub fn stream_for_mode( let exchange = openai_api.Exchange( ..exchange, - body: transport.gzip(exchange.body), + body: request_body.gzip(exchange.body), refusal: fn(status, body) { case status >= 400 && status < 500 { True -> files.reject(home, owner(auth), body) diff --git a/src/albedo/harness/extensions/codex/wire.gleam b/src/albedo/harness/extensions/codex/wire.gleam index 8d8958e83..900e8e918 100644 --- a/src/albedo/harness/extensions/codex/wire.gleam +++ b/src/albedo/harness/extensions/codex/wire.gleam @@ -4,8 +4,8 @@ import albedo/openai_api import albedo/openai_api/cost import albedo/openai_api/refusal as openai_refusal import albedo/openai_api/request as shared +import albedo/openai_api/request_body import albedo/openai_api/stream -import albedo/openai_api/transport import albedo/openai_api/types import albedo_bytes/ids import albedo_clock @@ -81,7 +81,7 @@ pub fn stream( string.remove_suffix(connection.base_url, "/") <> "/codex/responses", headers(client, request.model, request.options.service_tier), // The Codex CLI sends this endpoint zstd bodies by default. - transport.zstd(body), + request_body.zstd(body), connection.timeout_ms, None, connection.max_event_bytes, diff --git a/src/albedo/harness/extensions/openai/extension.gleam b/src/albedo/harness/extensions/openai/extension.gleam index 477b9acbc..384f6ffd9 100644 --- a/src/albedo/harness/extensions/openai/extension.gleam +++ b/src/albedo/harness/extensions/openai/extension.gleam @@ -18,8 +18,8 @@ import albedo/openai_api/cost import albedo/openai_api/count import albedo/openai_api/refusal import albedo/openai_api/request as wire +import albedo/openai_api/request_body import albedo/openai_api/stream as reducer -import albedo/openai_api/transport import albedo/openai_api/types import albedo_bytes/digest import gleam/bool @@ -343,7 +343,7 @@ fn encoder( ) -> fn(types.Protocol, types.Request) -> Result(StringTree, types.Error) { case client.protocol == types.Responses && fast.canonical(client.base_url) { True -> fn(protocol, request) { - wire.encode(protocol, request) |> result.map(transport.zstd) + wire.encode(protocol, request) |> result.map(request_body.zstd) } False -> wire.encode } diff --git a/src/albedo/openai_api/albedo_openai_json.erl b/src/albedo/openai_api/albedo_openai_json.erl index 957e92314..17ebf5aab 100644 --- a/src/albedo/openai_api/albedo_openai_json.erl +++ b/src/albedo/openai_api/albedo_openai_json.erl @@ -2,8 +2,9 @@ %% Coalesces encoded request JSON. This stays Erlang because it walks untyped %% iodata, telling binaries, byte integers, nested lists, and the transport's -%% {albedo_image, Size, Read} placeholders apart with guards. A Gleam version -%% would test every fragment through Dynamic on the request-encoding hot path. +%% body parts (tuples, see request_body.gleam) apart with guards. A Gleam +%% version would test every fragment through Dynamic on the request-encoding +%% hot path. -export([flatten/1]). %% Binaries at least this large cross process boundaries by reference. @@ -23,8 +24,8 @@ coalesce([H | T], Stack, Small, Out) -> coalesce(H, [T | Stack], Small, Out); coalesce(B, Stack, Small, Out) when is_binary(B), byte_size(B) >= ?SHARED -> coalesce([], Stack, [], [B | emit(Small, Out)]); -coalesce({albedo_image, _, _} = Image, Stack, Small, Out) -> - coalesce([], Stack, [], [Image | emit(Small, Out)]); +coalesce(Part, Stack, Small, Out) when is_tuple(Part) -> + coalesce([], Stack, [], [Part | emit(Small, Out)]); coalesce(Piece, Stack, Small, Out) -> coalesce([], Stack, [Piece | Small], Out). diff --git a/src/albedo/openai_api/albedo_openai_transport.erl b/src/albedo/openai_api/albedo_openai_transport.erl index 4b6d77d4d..cd2dbe206 100644 --- a/src/albedo/openai_api/albedo_openai_transport.erl +++ b/src/albedo/openai_api/albedo_openai_transport.erl @@ -9,8 +9,8 @@ %% messages carry the socket in their second element, and a gleam_erlang %% selector selects by the first element and arity only. %% - piece/1, which tells one term of untyped iodata apart with guards: -%% a binary, a byte, list structure, or a stored-image or attestation -%% placeholder. request_body.gleam walks the body and applies the rules. +%% a binary, a byte, list structure, or a deferred or digest part. +%% request_body.gleam walks the body and applies the rules. -export([await/3, piece/1]). @@ -36,15 +36,16 @@ tags(tls) -> {ssl, ssl_passive, ssl_closed, ssl_error}. %% One piece of an iodata body as request_body.Piece: {bytes, Term, Size} %% for a binary or a byte, {cons, Head, Tail} and empty for the (possibly -%% improper) list structure, and the stored-image and attestation -%% placeholders, which request_body.gleam places in its plan. +%% improper) list structure, and {part_piece, Part} for a deferred or digest +%% part, request_body.Part's own tuples, which request_body.gleam places in +%% its plan. piece(Piece) when is_binary(Piece) -> {bytes, Piece, byte_size(Piece)}; piece(Byte) when is_integer(Byte) -> {bytes, Byte, 1}; piece([Head | Tail]) -> {cons, Head, Tail}; piece([]) -> empty; -piece({albedo_image, Size, Read}) -> - {stored_image, Size, Read}; -piece({albedo_attest, Init, Update, Emit, Placeholder}) -> - {attest_marker, Init, Update, Emit, Placeholder}. +piece({albedo_http_deferred, _Size, _Read} = Part) -> + {part_piece, Part}; +piece({albedo_http_digest, _Init, _Update, _Emit, _Placeholder} = Part) -> + {part_piece, Part}. diff --git a/src/albedo/openai_api/attestation.gleam b/src/albedo/openai_api/attestation.gleam index 555623b0e..8f0654a7c 100644 --- a/src/albedo/openai_api/attestation.gleam +++ b/src/albedo/openai_api/attestation.gleam @@ -1,27 +1,13 @@ -//// The streaming attestation marker that `request_body` splices while it -//// writes a body. The transport feeds every byte of the body before -//// and after the marker, with the placeholder in the marker's place, through -//// `update`, then writes `emit`'s value where the placeholder stood. -//// -//// Invariants the transport checks or relies on: a body carries at most one -//// marker, no stored image follows it, and `emit` returns exactly as many -//// bytes as `placeholder`. +//// Raw JSON with a digest part spliced into it, for a provider whose request +//// carries a digest of its own body, such as Claude Code's billing block. +//// `request_body` owns the digest part's rules and computes it while the +//// transport writes the body. -import gleam/dynamic.{type Dynamic} +import albedo/openai_api/request_body import gleam/json.{type Json} -/// `{albedo_attest, Init, Update, Emit, Placeholder}` on the wire. -type Marker(state) { - AlbedoAttest( - init: fn() -> state, - update: fn(state, Dynamic) -> state, - emit: fn(state) -> BitArray, - placeholder: BitArray, - ) -} - -/// Raw JSON bytes `before`, the marker, then raw JSON bytes `after`. The -/// caller owns the JSON validity of the spliced text. +/// Raw JSON bytes `before`, the digest part, then raw JSON bytes `after`. +/// The caller owns the JSON validity of the spliced text. pub fn spliced( before before: String, init init: fn() -> state, @@ -30,18 +16,9 @@ pub fn spliced( placeholder placeholder: BitArray, after after: String, ) -> Json { - let marker = - AlbedoAttest( - init, - fn(state, data) { update(state, iolist_to_binary(data)) }, - emit, - placeholder, - ) - coerce([coerce(before), coerce(marker), coerce(after)]) + let digest = request_body.digest(init:, update:, emit:, placeholder:) + coerce([coerce(before), digest, coerce(after)]) } -@external(erlang, "erlang", "iolist_to_binary") -fn iolist_to_binary(data: Dynamic) -> BitArray - @external(erlang, "gleam_stdlib", "identity") fn coerce(value: a) -> b diff --git a/src/albedo/openai_api/request_body.gleam b/src/albedo/openai_api/request_body.gleam index 5014d5989..469a1edd4 100644 --- a/src/albedo/openai_api/request_body.gleam +++ b/src/albedo/openai_api/request_body.gleam @@ -1,59 +1,166 @@ -//// A request body as the streaming transport writes it. A body is encoded -//// JSON iodata that may hold stored-image placeholders, read only while the -//// body is written so at most one image payload is held at a time, and one -//// streaming attestation marker, whose digest covers every byte around it. +//// A request body as the streaming transport writes it: iodata, as a +//// `StringTree`, that may carry parts besides bytes. //// -//// `albedo_openai_transport.erl` tells each untyped iodata term apart. This -//// module walks the body into a typed plan and owns what a plan means: its -//// placeholder rules, its length on the wire, whether it may be compressed, -//// how it is written, and the bytes it stands for. +//// - A deferred part has a known size and is read only while the body is +//// written, so a body of many large parts holds one payload at a time. +//// - A digest part stands for bytes computed over the whole body. Its +//// placeholder takes its place while the digest reads the body, and its +//// digest's bytes replace the placeholder on the wire. +//// +//// `deferred` and `digest` return a part as a `StringTree` to place in the +//// body at any depth, inside encoded JSON for instance. `zstd` and `gzip` +//// wrap a whole body for compression. The rules are this module's: a body +//// carries at most one digest part, no deferred part follows it, and the +//// digest's bytes are exactly as long as its placeholder. A body that holds +//// a deferred part is never compressed, since compressing it would hold +//// every payload in memory at once. //// -//// Invariants: nothing placeholder-bearing may follow the attestation -//// marker, and its `emit` returns exactly as many bytes as its placeholder. +//// `albedo_openai_transport.erl` tells each untyped iodata term apart; this +//// module walks the body into a typed plan and owns what a plan means: its +//// length on the wire, how it is written, and the bytes it stands for. -import albedo/openai_api/connect.{type Transport} -import albedo/openai_api/socket.{type Socket} import albedo_protect +import gleam/bit_array import gleam/dynamic.{type Dynamic} import gleam/erlang/atom import gleam/list -import gleam/string +import gleam/option.{type Option, None, Some} import gleam/string_tree.{type StringTree} +/// A part as it sits in a body's iodata. The constructors compile to the +/// tagged tuples `albedo_openai_transport:piece/1` recognises. +type Part { + AlbedoHttpDeferred(size: Int, read: fn() -> Result(BitArray, Nil)) + AlbedoHttpDigest( + init: fn() -> Dynamic, + update: fn(Dynamic, BitArray) -> Dynamic, + emit: fn(Dynamic) -> BitArray, + placeholder: BitArray, + ) +} + +/// `{albedo_http_compress, Encoding, Body}`, a body sent compressed. +type Compressed { + AlbedoHttpCompress(encoding: Encoding, body: StringTree) +} + +type Encoding { + Zstd + Gzip +} + +/// A part of `size` bytes that `read` returns while the body is written. A +/// read that fails or returns another size fails the request. +pub fn deferred(size: Int, read: fn() -> Result(BitArray, Nil)) -> StringTree { + coerce(AlbedoHttpDeferred(size, read)) +} + +/// A digest part. `init`, `update` and `emit` compute the digest of the whole +/// body, fed in order with `placeholder` where the part stands; `emit`'s +/// bytes then go on the wire in its place and must be exactly as long. +pub fn digest( + init init: fn() -> state, + update update: fn(state, BitArray) -> state, + emit emit: fn(state) -> BitArray, + placeholder placeholder: BitArray, +) -> StringTree { + coerce(AlbedoHttpDigest( + init: coerce(init), + update: coerce(update), + emit: coerce(emit), + placeholder:, + )) +} + +/// `body` sent zstd-compressed under `content-encoding: zstd`, for a server +/// known to accept that. A body with a deferred part is sent as it is. +pub fn zstd(body: StringTree) -> StringTree { + coerce(AlbedoHttpCompress(Zstd, body)) +} + +/// `body` sent gzip-compressed under `content-encoding: gzip`, as `zstd`. +pub fn gzip(body: StringTree) -> StringTree { + coerce(AlbedoHttpCompress(Gzip, body)) +} + +/// Why a body cannot be sent. +pub type Invalid { + /// The body is not iodata of bytes and parts. + Malformed + /// A second digest part. + SecondDigest + /// A deferred part after the digest part. + DeferredAfterDigest + /// A deferred part's read failed or returned another size. + UnreadablePart + /// The digest's bytes are not as long as its placeholder. + DigestLength +} + +/// The words for `invalid`. +pub fn describe(invalid: Invalid) -> String { + case invalid { + Malformed -> "a request body is not iodata" + SecondDigest -> "a request body may carry at most one digest part" + DeferredAfterDigest -> "a deferred body part cannot follow a digest part" + UnreadablePart -> "a deferred body part is missing or damaged" + DigestLength -> "a body digest is not as long as its placeholder" + } +} + +/// The body to send and its content encoding: a body `zstd` or `gzip` +/// wrapped compressed once, so a resend sends the same bytes. A body with a +/// deferred part, or one that cannot be materialized, goes out as it is, and +/// sending it reports any error. +pub fn encode(body: StringTree) -> #(Option(String), StringTree) { + let value: Dynamic = coerce(body) + case + is_tuple(value) + && tuple_size(value) == 3 + && element(1, value) == atom.to_dynamic(atom.create("albedo_http_compress")) + { + False -> #(None, body) + True -> { + let AlbedoHttpCompress(encoding, inner) = coerce(value) + let plain = case compressible(inner) { + True -> materialize(inner) + False -> Error(Malformed) + } + case plain, encoding { + Ok(plain), Zstd -> #( + Some("zstd"), + coerce(iolist_to_binary(zstd_compress(plain))), + ) + Ok(plain), Gzip -> #(Some("gzip"), coerce(gzip_compress(plain))) + Error(_), _ -> #(None, inner) + } + } + } +} + /// What the walk found in a body. type Plan { - /// No placeholders: the body is written as it is. + /// No parts: the body is written as it is. Plain - /// Data runs and placeholders in order, the body's length on the wire, and - /// its marker. - Segmented(segments: List(Segment), length: Int, marker: Marker) + /// Data runs and parts in order, the body's length on the wire, and its + /// digest, if any. + Segmented(segments: List(Segment), length: Int, digest: Option(Part)) } type Segment { /// In-memory iodata. Data(bytes: Dynamic) - /// A stored image of `size` bytes, read when it is written. - Image(size: Int, read: fn() -> Result(String, Nil)) - /// Where the attestation's digits go, `placeholder`'s size. - Attest(emit: fn(Dynamic) -> BitArray, placeholder: BitArray) -} - -type Marker { - NoMarker - Images - Attestation( - init: fn() -> Dynamic, - update: fn(Dynamic, Dynamic) -> Dynamic, - emit: fn(Dynamic) -> BitArray, - placeholder: BitArray, - ) + /// A deferred part, read when it is written. + Deferred(size: Int, read: fn() -> Result(BitArray, Nil)) + /// Where the digest's bytes go, `placeholder`'s size. + Digest(emit: fn(Dynamic) -> BitArray, placeholder: BitArray) } -/// The attestation digest's state while a body is written: not attested, -/// fed every byte so far, or emitted. +/// The digest's state while a body is written: no digest, fed every byte so +/// far, or emitted. type Hasher { Unhashed - Hashing(update: fn(Dynamic, Dynamic) -> Dynamic, state: Dynamic) + Hashing(update: fn(Dynamic, BitArray) -> Dynamic, state: Dynamic) Done } @@ -65,32 +172,31 @@ pub opaque type Prepared { /// Why a body could not be written. pub type WriteFailure { - /// The socket refused bytes. + /// `send` refused bytes, for this reason. SendError(reason: Dynamic) - /// A stored image could not be read. - BodyFailed(why: String) + /// The body broke a rule while it was written. + WriteInvalid(Invalid) } -/// The body's length on the wire and the form `write` sends, or why the body -/// breaks a placeholder rule. -pub fn prepare(body: StringTree) -> Result(#(Int, Prepared), String) { +/// The body's length on the wire and the form `write` sends, or the rule it +/// breaks. +pub fn prepare(body: StringTree) -> Result(#(Int, Prepared), Invalid) { case segments(body) { Ok(Plain) -> Ok(#(iolist_size(body), PlainBody(body))) - Ok(Segmented(segments, length, marker)) -> - Ok(#(length, SegmentedBody(segments, hasher(marker)))) - Error(why) -> Error(why) + Ok(Segmented(segments, length, digest)) -> + Ok(#(length, SegmentedBody(segments, hasher(digest)))) + Error(invalid) -> Error(invalid) } } -/// Whether a body may be compressed: it holds no stored image and is valid. -/// Compressing a stored image would hold every image in memory at once. -pub fn compressible(body: StringTree) -> Bool { +/// Whether a body may be compressed: it is valid and holds no deferred part. +fn compressible(body: StringTree) -> Bool { case segments(body) { Ok(Plain) -> True Ok(Segmented(segments, ..)) -> !list.any(segments, fn(segment) { case segment { - Image(..) -> True + Deferred(..) -> True _ -> False } }) @@ -98,15 +204,14 @@ pub fn compressible(body: StringTree) -> Bool { } } -/// Writes the body. Each send returns once the socket has taken its -/// segment, so at most one image payload is held at a time. +/// Writes the body through `send`. Each send returns once the socket has +/// taken its segment, so at most one deferred payload is held at a time. pub fn write( - transport: Transport, - connected: Socket, body: Prepared, + send: fn(StringTree) -> Result(Nil, Dynamic), ) -> Result(Nil, WriteFailure) { let send = fn(data: Dynamic) { - case socket.send(transport, connected, coerce(data)) { + case send(coerce(data)) { Ok(Nil) -> Ok(Nil) Error(reason) -> Error(SendError(reason)) } @@ -129,37 +234,41 @@ fn write_segments( Ok(Nil) -> write_segments(send, rest, feed(hasher, data)) Error(failure) -> Error(failure) } - [Image(size, read), ..rest] -> + [Deferred(size, read), ..rest] -> case read_payload(size, read) { - Error(why) -> Error(BodyFailed(why)) + Error(invalid) -> Error(WriteInvalid(invalid)) Ok(payload) -> case send(coerce(payload)) { Ok(Nil) -> write_segments(send, rest, feed(hasher, coerce(payload))) Error(failure) -> Error(failure) } } - [Attest(emit, placeholder), ..rest] -> - case send(coerce(marker_value(emit, placeholder, rest, hasher))) { - Ok(Nil) -> write_segments(send, rest, Done) - Error(failure) -> Error(failure) + [Digest(emit, placeholder), ..rest] -> + case digest_value(emit, placeholder, rest, hasher) { + Error(invalid) -> Error(WriteInvalid(invalid)) + Ok(value) -> + case send(coerce(value)) { + Ok(Nil) -> write_segments(send, rest, Done) + Error(failure) -> Error(failure) + } } } } -/// The exact bytes sent over the wire, with payloads read and the marker -/// spliced, or why they cannot be produced. -pub fn materialize(body: StringTree) -> Result(BitArray, String) { +/// The exact bytes sent on the wire, with deferred parts read and the digest +/// in place, or the rule the body breaks. +pub fn materialize(body: StringTree) -> Result(BitArray, Invalid) { let materialized = albedo_protect.rescue(fn() { case segments(body) { Ok(Plain) -> Ok(iolist_to_binary(coerce(body))) - Ok(Segmented(segments, _, marker)) -> fold(segments, hasher(marker), []) - Error(why) -> Error(why) + Ok(Segmented(segments, _, digest)) -> fold(segments, hasher(digest), []) + Error(invalid) -> Error(invalid) } }) case materialized { Ok(result) -> result - Error(_) -> Error("a body could not be materialized") + Error(_) -> Error(Malformed) } } @@ -167,25 +276,26 @@ fn fold( segments: List(Segment), hasher: Hasher, out: List(Dynamic), -) -> Result(BitArray, String) { +) -> Result(BitArray, Invalid) { case segments { [] -> Ok(iolist_to_binary(coerce(list.reverse(out)))) [Data(data), ..rest] -> fold(rest, feed(hasher, data), [data, ..out]) - [Image(size, read), ..rest] -> + [Deferred(size, read), ..rest] -> case read_payload(size, read) { Ok(payload) -> fold(rest, feed(hasher, coerce(payload)), [coerce(payload), ..out]) - Error(why) -> Error(why) + Error(invalid) -> Error(invalid) + } + [Digest(emit, placeholder), ..rest] -> + case digest_value(emit, placeholder, rest, hasher) { + Ok(value) -> fold(rest, Done, [coerce(value), ..out]) + Error(invalid) -> Error(invalid) } - [Attest(emit, placeholder), ..rest] -> { - let value = marker_value(emit, placeholder, rest, hasher) - fold(rest, Done, [coerce(value), ..out]) - } } } -/// A plain body as one binary: a retry keeps it off the heap, not as the -/// encoder's many small pieces. A segmented body stays as it is. +/// A plain body as one binary: a resend keeps it off the heap, not as the +/// encoder's many small pieces. A body with parts stays as it is. pub fn compact(body: StringTree) -> StringTree { case albedo_protect.rescue(fn() { iolist_to_binary(coerce(body)) }) { Ok(bytes) -> coerce(bytes) @@ -197,31 +307,30 @@ pub fn compact(body: StringTree) -> StringTree { } } -fn hasher(marker: Marker) -> Hasher { - case marker { - NoMarker | Images -> Unhashed - Attestation(init:, update:, ..) -> Hashing(update, init()) +fn hasher(digest: Option(Part)) -> Hasher { + case digest { + Some(AlbedoHttpDigest(init:, update:, ..)) -> Hashing(update, init()) + _ -> Unhashed } } fn feed(hasher: Hasher, data: Dynamic) -> Hasher { case hasher { - Hashing(update, state) -> Hashing(update, update(state, data)) + Hashing(update, state) -> + Hashing(update, update(state, iolist_to_binary(data))) _ -> hasher } } -/// The marker's digits. The walk guarantees that only in-memory data -/// segments follow the marker, so the digest covers them before they are -/// written. -fn marker_value( +/// The digest's bytes. The walk guarantees that only in-memory data segments +/// follow the digest part, so the digest covers them before they are written. +fn digest_value( emit: fn(Dynamic) -> BitArray, placeholder: BitArray, rest: List(Segment), hasher: Hasher, -) -> BitArray { - let assert Hashing(update, state) = hasher - as "an attestation marker without its digest" +) -> Result(BitArray, Invalid) { + let assert Hashing(update, state) = hasher as "a digest part without a digest" let tail = list.filter_map(rest, fn(segment) { case segment { @@ -229,25 +338,28 @@ fn marker_value( _ -> Error(Nil) } }) - emit(update(update(state, coerce(placeholder)), coerce(tail))) + let value = + emit(update(update(state, placeholder), iolist_to_binary(coerce(tail)))) + case bit_array.byte_size(value) == bit_array.byte_size(placeholder) { + True -> Ok(value) + False -> Error(DigestLength) + } } fn read_payload( size: Int, - read: fn() -> Result(String, Nil), -) -> Result(String, String) { + read: fn() -> Result(BitArray, Nil), +) -> Result(BitArray, Invalid) { case read() { Ok(payload) -> - case string.byte_size(payload) == size { + case bit_array.byte_size(payload) == size { True -> Ok(payload) - False -> Error(damaged) + False -> Error(UnreadablePart) } - Error(Nil) -> Error(damaged) + Error(Nil) -> Error(UnreadablePart) } } -const damaged = "a stored image payload is missing or damaged" - /// One term of a body's iodata, as `albedo_openai_transport:piece/1` tells /// it apart. type Piece { @@ -256,31 +368,32 @@ type Piece { /// A list cell; its tail may be a binary, as iodata allows. Cons(head: Dynamic, tail: Dynamic) Empty - StoredImage(size: Int, read: fn() -> Result(String, Nil)) - AttestMarker( - init: fn() -> Dynamic, - update: fn(Dynamic, Dynamic) -> Dynamic, - emit: fn(Dynamic) -> BitArray, - placeholder: BitArray, - ) + PartPiece(part: Part) } /// The walk so far: the current data run (reversed), the finished segments -/// (reversed), the length on the wire, and the marker. +/// (reversed), the length on the wire, whether a deferred part was seen, +/// and the digest part. type Walk { - Walk(current: List(Dynamic), done: List(Segment), length: Int, marker: Marker) + Walk( + current: List(Dynamic), + done: List(Segment), + length: Int, + deferred: Bool, + digest: Option(Part), + ) } -fn segments(body: StringTree) -> Result(Plan, String) { - case walk(coerce(body), Walk([], [], 0, NoMarker)) { - Error(why) -> Error(why) - Ok(Walk(marker: NoMarker, ..)) -> Ok(Plain) - Ok(Walk(current, done, length, marker)) -> - Ok(Segmented(list.reverse(flush(current, done)), length, marker)) +fn segments(body: StringTree) -> Result(Plan, Invalid) { + case walk(coerce(body), Walk([], [], 0, False, None)) { + Error(invalid) -> Error(invalid) + Ok(Walk(deferred: False, digest: None, ..)) -> Ok(Plain) + Ok(Walk(current:, done:, length:, digest:, ..)) -> + Ok(Segmented(list.reverse(flush(current, done)), length, digest)) } } -fn walk(term: Dynamic, state: Walk) -> Result(Walk, String) { +fn walk(term: Dynamic, state: Walk) -> Result(Walk, Invalid) { case piece(term) { Bytes(term, size) -> Ok( @@ -294,34 +407,38 @@ fn walk(term: Dynamic, state: Walk) -> Result(Walk, String) { Cons(head, tail) -> case walk(head, state) { Ok(state) -> walk(tail, state) - Error(why) -> Error(why) + Error(invalid) -> Error(invalid) } - StoredImage(size, read) -> - case state.marker { - Attestation(..) -> - Error("a stored image cannot follow an attestation marker") - NoMarker | Images -> - Ok(Walk( - current: [], - done: [Image(size, read), ..flush(state.current, state.done)], - length: state.length + size, - marker: Images, - )) + PartPiece(AlbedoHttpDeferred(size, read)) -> + case state.digest { + Some(_) -> Error(DeferredAfterDigest) + None -> + Ok( + Walk( + ..state, + current: [], + done: [Deferred(size, read), ..flush(state.current, state.done)], + length: state.length + size, + deferred: True, + ), + ) } - AttestMarker(init, update, emit, placeholder) -> - case state.marker { - Attestation(..) -> - Error("a body may carry at most one attestation marker") - NoMarker | Images -> - Ok(Walk( - current: [], - done: [ - Attest(emit, placeholder), - ..flush(state.current, state.done) - ], - length: state.length + bit_array_size(placeholder), - marker: Attestation(init, update, emit, placeholder), - )) + PartPiece(AlbedoHttpDigest(emit:, placeholder:, ..) as digest) -> + case state.digest { + Some(_) -> Error(SecondDigest) + None -> + Ok( + Walk( + ..state, + current: [], + done: [ + Digest(emit, placeholder), + ..flush(state.current, state.done) + ], + length: state.length + bit_array.byte_size(placeholder), + digest: Some(digest), + ), + ) } } } @@ -336,14 +453,26 @@ fn flush(current: List(Dynamic), done: List(Segment)) -> List(Segment) { @external(erlang, "albedo_openai_transport", "piece") fn piece(term: Dynamic) -> Piece -@external(erlang, "erlang", "byte_size") -fn bit_array_size(bytes: BitArray) -> Int - @external(erlang, "erlang", "iolist_size") fn iolist_size(body: StringTree) -> Int @external(erlang, "erlang", "iolist_to_binary") fn iolist_to_binary(data: Dynamic) -> BitArray +@external(erlang, "zstd", "compress") +fn zstd_compress(plain: BitArray) -> Dynamic + +@external(erlang, "zlib", "gzip") +fn gzip_compress(plain: BitArray) -> BitArray + +@external(erlang, "erlang", "is_tuple") +fn is_tuple(value: Dynamic) -> Bool + +@external(erlang, "erlang", "tuple_size") +fn tuple_size(value: Dynamic) -> Int + +@external(erlang, "erlang", "element") +fn element(index: Int, tuple: Dynamic) -> Dynamic + @external(erlang, "gleam_stdlib", "identity") fn coerce(value: a) -> b diff --git a/src/albedo/openai_api/transport.gleam b/src/albedo/openai_api/transport.gleam index dee0c65dd..2cf397bbc 100644 --- a/src/albedo/openai_api/transport.gleam +++ b/src/albedo/openai_api/transport.gleam @@ -156,16 +156,6 @@ type StateKey { AlbedoOpenaiTransport(ref: Reference) } -type Encoding { - Zstd - Gzip -} - -// `{albedo_compress, Encoding, Body}`, a body the transport compresses. -type Compressed { - AlbedoCompress(encoding: Encoding, body: StringTree) -} - type SslNotStarted { SslNotStarted(reason: Dynamic) } @@ -326,51 +316,18 @@ fn token(name: BitArray) -> Bool { } } -/// `body` sent zstd-compressed under `content-encoding: zstd`, for a server -/// known to accept that. A body carrying stored images is sent uncompressed. -pub fn zstd(body: StringTree) -> StringTree { - coerce(AlbedoCompress(Zstd, body)) -} - -/// `body` sent gzip-compressed under `content-encoding: gzip`, as `zstd`. -pub fn gzip(body: StringTree) -> StringTree { - coerce(AlbedoCompress(Gzip, body)) -} - -// Compresses a body wrapped by `zstd` or `gzip` once, before any connection -// is taken, so a pooled retry resends the same bytes. A body with stored -// images goes out uncompressed: compressing it would hold every image in -// memory at once, and base64 images barely shrink. A body that cannot be -// materialized also goes out as it is, so sending reports its error. +// A body `request_body.zstd` or `gzip` wrapped goes out compressed, under +// its content encoding. fn encode_body( headers: List(#(String, String)), body: StringTree, ) -> #(List(#(String, String)), StringTree) { - let value: Dynamic = coerce(body) - case - is_tuple(value) - && tuple_size(value) == 3 - && element(1, value) == atom.to_dynamic(atom.create("albedo_compress")) - { - False -> #(headers, body) - True -> { - let AlbedoCompress(encoding, inner) = coerce(value) - let plain = case request_body.compressible(inner) { - True -> request_body.materialize(inner) - False -> Error("") - } - case plain, encoding { - Ok(plain), Zstd -> #( - [#("content-encoding", "zstd"), ..headers], - coerce(iolist_to_binary(zstd_compress(plain))), - ) - Ok(plain), Gzip -> #( - [#("content-encoding", "gzip"), ..headers], - coerce(gzip_compress(plain)), - ) - Error(_), _ -> #(headers, inner) - } - } + case request_body.encode(body) { + #(Some(encoding), body) -> #( + [#("content-encoding", encoding), ..headers], + body, + ) + #(None, body) -> #(headers, body) } } @@ -593,7 +550,7 @@ fn send_request( body: StringTree, ) -> Result(Nil, SendFailure) { case request_body.prepare(body) { - Error(why) -> Error(SendFailed(why)) + Error(invalid) -> Error(SendFailed(request_body.describe(invalid))) Ok(#(length, prepared)) -> send_prepared(request, connected, headers, length, prepared) } @@ -650,11 +607,18 @@ fn send_prepared( case socket.send(request.transport, connected, head) { Error(reason) -> Error(SendFailed(failure("request failed", reason))) Ok(Nil) -> - case request_body.write(request.transport, connected, prepared) { + case + request_body.write(prepared, socket.send( + request.transport, + connected, + _, + )) + { Ok(Nil) -> Ok(Nil) Error(request_body.SendError(reason)) -> Error(SendFailed(failure("request failed", reason))) - Error(request_body.BodyFailed(why)) -> Error(SendFailed(why)) + Error(request_body.WriteInvalid(invalid)) -> + Error(SendFailed(request_body.describe(invalid))) } } } @@ -1315,15 +1279,6 @@ fn decode_packet( options: List(Nil), ) -> Dynamic -@external(erlang, "zstd", "compress") -fn zstd_compress(plain: BitArray) -> Dynamic - -@external(erlang, "zlib", "gzip") -fn gzip_compress(plain: BitArray) -> BitArray - -@external(erlang, "erlang", "iolist_to_binary") -fn iolist_to_binary(data: Dynamic) -> BitArray - @external(erlang, "erlang", "garbage_collect") fn garbage_collect() -> Bool diff --git a/src/albedo/openai_api/types.gleam b/src/albedo/openai_api/types.gleam index 07145a32e..681ddc90d 100644 --- a/src/albedo/openai_api/types.gleam +++ b/src/albedo/openai_api/types.gleam @@ -1,3 +1,4 @@ +import albedo/openai_api/request_body import gleam/bit_array import gleam/bool import gleam/crypto @@ -592,17 +593,15 @@ fn base64_clean(data: BitArray) -> Bool { } } -/// A body placeholder the streaming transport replaces with the payload -/// `read` returns while it writes the request, so at most one image payload -/// is held at a time. It compiles to `{albedo_image, Size, Read}`, the shape -/// `albedo_openai_transport.erl` walks. Nothing else may serialize a body -/// that holds one. -type BodyPart { - AlbedoImage(size: Int, read: fn() -> Result(String, Nil)) -} - +/// A stored payload as a deferred body part, which the streaming transport +/// reads only while it writes the request, so at most one image payload is +/// held at a time. Nothing else may serialize a body that holds one. fn stored_payload(size: Int, read: fn() -> Result(String, Nil)) -> Json { - coerce(AlbedoImage(size, read)) + coerce( + request_body.deferred(size, fn() { + result.map(read(), bit_array.from_string) + }), + ) } // Encoded JSON is iodata on Erlang, so text and JSON pieces join as a list. diff --git a/test/harness/claude_test.gleam b/test/harness/claude_test.gleam index 04ef19750..94672c646 100644 --- a/test/harness/claude_test.gleam +++ b/test/harness/claude_test.gleam @@ -12,6 +12,7 @@ import albedo/harness/sdk/transcript import albedo/openai_api import albedo/openai_api/cost import albedo/openai_api/request +import albedo/openai_api/request_body import albedo/openai_api/stream as reducer import albedo/openai_api/transport import albedo/openai_api/types @@ -1075,8 +1076,13 @@ fn billing_hash_streamed(chunks: List(String)) -> String { billing.hash_streamed(list.map(chunks, fn(chunk) { <> })) } -@external(erlang, "albedo@openai_api@request_body", "materialize") -fn materialize(body: StringTree) -> Result(String, String) +/// The body's bytes on the wire, as text. +fn materialize(body: StringTree) -> Result(String, Nil) { + case request_body.materialize(body) { + Ok(bytes) -> bit_array.to_string(bytes) + Error(_) -> Error(Nil) + } +} fn sent(body: StringTree) -> String { let assert Ok(text) = materialize(body) diff --git a/test/harness/messages_cache_test.gleam b/test/harness/messages_cache_test.gleam index f7aadf124..a9dee29d4 100644 --- a/test/harness/messages_cache_test.gleam +++ b/test/harness/messages_cache_test.gleam @@ -5,7 +5,9 @@ import albedo/harness/extensions/github_copilot/wire as copilot import albedo/harness/extensions/opencode_go/wire as opencode import albedo/openai_api +import albedo/openai_api/request_body import albedo/openai_api/types +import gleam/bit_array import gleam/dict import gleam/dynamic/decode import gleam/json @@ -14,8 +16,13 @@ import gleam/option.{type Option, None, Some} import gleam/result import gleam/string_tree.{type StringTree} -@external(erlang, "albedo@openai_api@request_body", "materialize") -fn materialize(body: StringTree) -> Result(String, String) +/// The body's bytes on the wire, as text. +fn materialize(body: StringTree) -> Result(String, Nil) { + case request_body.materialize(body) { + Ok(bytes) -> bit_array.to_string(bytes) + Error(_) -> Error(Nil) + } +} fn copilot_client() -> copilot.Client { copilot.client( diff --git a/test/openai_api/albedo_openai_transport_test_server.erl b/test/openai_api/albedo_openai_transport_test_server.erl index 5f349d89c..f4cc07ee4 100644 --- a/test/openai_api/albedo_openai_transport_test_server.erl +++ b/test/openai_api/albedo_openai_transport_test_server.erl @@ -16,17 +16,13 @@ unopened/1, await_headers/1, unzstd/1, - gunzip/1, - image_body/0 + gunzip/1 ]). unzstd(Bytes) -> iolist_to_binary(zstd:decompress(Bytes)). gunzip(Bytes) -> zlib:gunzip(Bytes). -%% A body with a stored image the transport reads only while sending. -image_body() -> [<<"{\"image\":\"">>, {albedo_image, 3, fun() -> {ok, <<"abc">>} end}, <<"\"}">>]. - start(Mode) -> {ok, Listen} = gen_tcp:listen(0, [ binary, diff --git a/test/openai_api/transport_test.gleam b/test/openai_api/transport_test.gleam index 0fde64e85..68720c4fe 100644 --- a/test/openai_api/transport_test.gleam +++ b/test/openai_api/transport_test.gleam @@ -7,6 +7,7 @@ import albedo/harness/extensions/mcp/http as mcp_http import albedo/openai_api import albedo/openai_api/refusal +import albedo/openai_api/request_body import albedo/openai_api/route import albedo/openai_api/stream as reducer import albedo/openai_api/stream_http @@ -83,18 +84,15 @@ fn unzstd(bytes: BitArray) -> BitArray @external(erlang, "albedo_openai_transport_test_server", "gunzip") fn gunzip(bytes: BitArray) -> BitArray -@external(erlang, "albedo_openai_transport_test_server", "image_body") -fn image_body() -> string_tree.StringTree - -// A stored image placeholder, `{albedo_image, Size, Read}`, which the -// transport reads only while sending. -type BodyPart { - AlbedoImage(size: Int, read: fn() -> Result(BitArray, Nil)) +/// A body with a deferred part the transport reads only while sending. +fn deferred_body() -> string_tree.StringTree { + string_tree.concat([ + string_tree.from_string("{\"image\":\""), + request_body.deferred(3, fn() { Ok(<<"abc">>) }), + string_tree.from_string("\"}"), + ]) } -@external(erlang, "gleam_stdlib", "identity") -fn coerce(value: a) -> b - pub fn invalid_headers_are_refused_before_connecting_test() -> Nil { let invalid = [ #("x-probe", "secret\rvalue"), @@ -176,8 +174,8 @@ pub fn valid_signed_headers_keep_their_bytes_test() -> Nil { pub fn a_body_asked_for_compression_is_compressed_unless_it_carries_images_test() -> Nil { use #(compressed, encoding, decompress) <- list.each([ - #(transport.zstd, "zstd", unzstd), - #(transport.gzip, "gzip", gunzip), + #(request_body.zstd, "zstd", unzstd), + #(request_body.gzip, "gzip", gunzip), ]) let text = string.repeat("{\"role\":\"user\",\"content\":\"hello\"},", 200) let body = compressed(string_tree.from_string(text)) @@ -205,7 +203,7 @@ pub fn a_body_asked_for_compression_is_compressed_unless_it_carries_images_test( transport.options(), url(fixture), [], - compressed(image_body()), + compressed(deferred_body()), 1000, ) string.contains(await_headers(fixture), "content-encoding") @@ -359,11 +357,14 @@ pub fn a_failed_exchange_closes_its_connection_test() -> Nil { /// with its socket reason, which names the network fault for the caller. pub fn a_failed_body_send_reports_the_socket_reason_test() -> Nil { let fixture = start(CloseAfterHeaders) - // Each stored image is its own send, and together they far exceed what + // Each deferred part is its own send, and together they far exceed what // loopback buffers hold, so a send after the hang-up fails. let payload = bit_array.from_string(string.repeat("x", 1_048_576)) let body = - coerce(list.repeat(AlbedoImage(1_048_576, fn() { Ok(payload) }), 64)) + string_tree.concat(list.repeat( + request_body.deferred(1_048_576, fn() { Ok(payload) }), + 64, + )) let assert Error(transport.TransportError(reason)) = transport.open(transport.options(), url(fixture), [], body, 10_000) stop(fixture) -- knotmirror 0.0.1