Node.js / Intermediate: application boundaries / Lesson 14
Compose stream pipelines with owned errors
Connect readable, transform, and writable streams while observing completion, backpressure, and failure.
On this page
Lesson goals
- Describe source, transform, and sink responsibilities.
- Await a pipeline and handle its rejection.
- Verify failure and cleanup under a controlled stream.
- Own pipeline completion and failures from source, transform, and destination.
- Handle backpressure, byte decoding, and retained state deliberately.
Define the data flow
A stream pipeline moves chunks from a source through optional transforms to a destination. It is useful when an entire input need not be buffered in memory, but each stage must still have a clear data and error contract. Decide who owns each stream and when the overall operation is complete. The examples use small synthetic text chunks so the control flow can be inspected without accessing a real file or network.
Connect the stages
The first example uses Readable.from as a source, a Transform to uppercase each chunk, and a Writable sink. pipeline coordinates stream flow and returns a promise that settles when the operation finishes or fails. The catch observes rejection and sets a failure exit status. The transform is intentionally simple: real text processing must account for character boundaries across byte chunks rather than assuming every chunk contains complete characters or records.
const { Readable, Transform, Writable } = require("node:stream");
const { pipeline } = require("node:stream/promises");
const upper = new Transform({
transform(chunk, encoding, callback) { callback(null, chunk.toString().toUpperCase()); }
});
const sink = new Writable({
write(chunk, encoding, callback) { process.stdout.write(chunk); callback(); }
});
pipeline(Readable.from(["one\n", "two\n"]), upper, sink)
.catch(error => { console.error(error.message); process.exitCode = 1; });
The promise represents the whole connected pipeline; the catch owns failure.
Observe a destination failure
The second example injects a failure in the writable callback. pipeline rejects and the catch observes the error message. In an application, propagate the error to the owning request or job instead of reporting success. A callback must be called once for each write; leaving it pending stalls completion. Treat each displayed block as an independent program because both declare the same local names.
const { Readable, Writable } = require("node:stream");
const { pipeline } = require("node:stream/promises");
const sink = new Writable({
write(chunk, encoding, callback) { callback(new Error("sink failed")); }
});
pipeline(Readable.from(["sample"]), sink)
.catch(error => console.log(error.message));
The write callback reports an error, which rejects pipeline and reaches the catch.
Respect flow control and cleanup
A slow destination can apply backpressure so upstream stages do not need to produce unbounded buffered data. pipeline helps coordinate the connected streams and errors, but it cannot undo a partially written external file or a remote side effect. Define whether a failed output is discarded, written to a temporary location, or otherwise recovered. Close resources you own and report partial results truthfully according to the destination’s contract.
Verify the complete operation
Run the successful example and confirm both lines reach the sink before completion. Run the failing example and confirm the rejection is observed. In a test, add a deliberately slow writable, count completed chunks, and inject failures in both source and destination; assert that the pipeline settles and owned resources are closed. For real files use isolated temporary fixtures and verify the final artifact, including the behavior after partial failure.
Define the pipeline and ownership
A Node stream pipeline connects a readable source, zero or more transforms, and a writable destination. The promise-based pipeline from node:stream/promises settles when the connected operation completes or fails. Await or return that promise to an owner that can handle the result. A successful transformation of a chunk is not by itself proof that the destination finished or that an external effect is durable.
Define the units and contract at each stage: bytes, decoded text, records, and output representation. Decide who owns source and destination resources, how errors are reported, and whether partial output needs cleanup or a separate commit step. The examples use finite in-memory synthetic streams under Node 22.23.3; they do not connect to a live service or prove production throughput.
Own errors from every stage
A source, transform, or destination can fail. When a writable callback receives an error, the promise-based pipeline rejects and the caller catch can observe it. Treat the operation as failed and apply the documented cleanup policy. Pipeline coordinates stream failure and teardown according to its API, but the owner remains responsible for the returned promise and resources outside the chain.
An error after some output was accepted does not automatically roll that output back. For a file or remote sink, decide whether to write to a temporary destination and publish only after success, use a transactional sink, or provide compensation. Do not treat a caught error as success merely to keep a script running. Test a controlled source error, transform error, and sink error separately, including the exact user-visible outcome.
Respect backpressure and cancellation
A writable can signal backpressure by returning false from write. The chunk passed to that call was accepted for processing or buffering; stop producing additional chunks until drain, and do not resend the same chunk. For a pipeline, Node stream machinery coordinates flow between compatible stages. A manual producer must also observe error and cancellation while waiting, because an operation that fails or is destroyed may not produce the expected drain.
An AbortSignal can cancel pipeline when supported by the API and environment, but cancellation is cooperative and does not undo already completed external effects. Own the controller, handle the pipeline rejection, and release resources not owned by pipeline. Test an already-aborted signal and a controlled failure. Avoid using fixed sleeps to infer completion; await the actual promise or finish event.
Respect bytes and record boundaries
A byte chunk is a transport unit, not necessarily a complete character or record. An uppercase transform that independently calls chunk.toString() is a useful ASCII demonstration but is not a general Unicode text processor: a UTF-8 character can be split across chunks, and a text operation may depend on context across boundaries. Use an appropriate streaming decoder and define record framing and final-fragment policy before transforming text.
Test a multibyte character split across byte chunks, a line split across chunks, multiple records in one chunk, and a final unterminated fragment. Set limits on a retained partial record. The transformation must also decide how invalid encoding is handled. These tests should verify exact output and not assume that each chunk corresponds to one logical item.
Verify completion and retained state
Build a small matrix for successful pipeline completion, source failure, transform failure, sink failure, cancellation, backpressure, and cleanup. Assert the output or error category, number and order of accepted chunks, and any external effects. A pipeline can reduce buffering between stages while application code still retains every processed row in an array. Measure memory with increasing input sizes and bound retained state if the contract requires it.
Use complete isolated .mjs fixtures, synthetic chunks, and the stated Node version. Await pipeline or the relevant completion event and ensure owned resources settle even on failure. The public renderer displays these examples without executing them. A passing local in-memory fixture does not prove production Unicode correctness, durability, resource limits, or remote-service behavior.
20 worked examples
1. Basic pipeline
Problem: Pipe two synthetic chunks to a writable and await completion.
- The readable supplies two finite chunks to the writable.
- Awaiting pipeline observes completion before printing the combined output.
import { Readable, Writable } from "node:stream"; import { pipeline } from "node:stream/promises"; let out = ""; const sink = new Writable({ write(c, e, cb) { out += c; cb(); } }); await pipeline(Readable.from(["a", "b"]), sink); console.log(out);
ab
Why this result follows: Awaiting pipeline observes completion before printing the combined output.
2. Uppercase ASCII
Problem: Transform two ASCII chunks through an uppercase pipeline.
- Each controlled input chunk contains ASCII text.
- The transform forwards uppercase chunks, yielding ABCD in this limited fixture.
import { Readable, Transform, Writable } from "node:stream"; import { pipeline } from "node:stream/promises"; let out = ""; const upper = new Transform({ transform(c, e, cb) { cb(null, c.toString().toUpperCase()); } }); const sink = new Writable({ write(c, e, cb) { out += c; cb(); } }); await pipeline(Readable.from(["ab", "cd"]), upper, sink); console.log(out);
ABCD
Why this result follows: The transform forwards uppercase chunks, yielding ABCD in this limited fixture.
3. Source failure
Problem: Observe a controlled readable error through pipeline rejection.
- The source destroys itself with a synthetic Error.
- The awaited pipeline rejects and its owner observes the source message.
import { Readable, Writable } from "node:stream"; import { pipeline } from "node:stream/promises"; const source = new Readable({ read() { this.destroy(new Error("source")); } }); const sink = new Writable({ write(c, e, cb) { cb(); } }); try { await pipeline(source, sink); } catch (e) { console.log(e.message); }
source
Why this result follows: The awaited pipeline rejects and its owner observes the source message.
4. Transform failure
Problem: Observe a transform callback error through the pipeline promise.
- The transform reports a controlled error for its chunk.
- The pipeline promise rejects and delivers that error to the owner.
import { Readable, Transform, Writable } from "node:stream"; import { pipeline } from "node:stream/promises"; const transform = new Transform({ transform(c, e, cb) { cb(new Error("transform")); } }); const sink = new Writable({ write(c, e, cb) { cb(); } }); try { await pipeline(Readable.from(["x"]), transform, sink); } catch (e) { console.log(e.message); }
transform
Why this result follows: The pipeline promise rejects and delivers that error to the owner.
5. Sink failure
Problem: Observe a destination callback error through pipeline rejection.
- The writable callback reports a controlled destination error.
- The pipeline rejects and the catch observes the sink failure.
import { Readable, Writable } from "node:stream"; import { pipeline } from "node:stream/promises"; const sink = new Writable({ write(c, e, cb) { cb(new Error("sink")); } }); try { await pipeline(Readable.from(["x"]), sink); } catch (e) { console.log(e.message); }
sink
Why this result follows: The pipeline rejects and the catch observes the sink failure.
6. No success after failure
Problem: Ensure a failed pipeline does not record a success marker.
- The sink rejects the pipeline before the success statement.
- The owner records only the error path for this controlled failure.
import { Readable, Writable } from "node:stream"; import { pipeline } from "node:stream/promises"; const events = []; const sink = new Writable({ write(c, e, cb) { cb(new Error("bad")); } }); try { await pipeline(Readable.from(["x"]), sink); events.push("success"); } catch { events.push("error"); } console.log(events.join(","));
error
Why this result follows: The owner records only the error path for this controlled failure.
7. Partial output retained
Problem: Observe an earlier synthetic output after a later stage fails.
- The first effect is recorded before the controlled error.
- Catching the failure does not roll back an already completed effect.
const written = []; try { written.push("a"); throw new Error("bad"); } catch { console.log(written.join("")); }
a
Why this result follows: Catching the failure does not roll back an already completed effect.
8. Write false accepts chunk
Problem: Observe a writable accepting a chunk while signalling backpressure.
- The small buffer threshold causes write to return false.
- The chunk x was still accepted, so it must not be resent.
import { Writable } from "node:stream"; import { once } from "node:events"; const seen = []; const sink = new Writable({ highWaterMark: 1, write(c, e, cb) { seen.push(c.toString()); setImmediate(cb); } }); const ready = sink.write("x"); console.log(ready, seen.join("")); if (!ready) await once(sink, "drain"); sink.end(); await once(sink, "finish");
false x
Why this result follows: The chunk x was still accepted, so it must not be resent.
9. Drain before next chunk
Problem: Pause after backpressure, then send the next distinct chunk.
- The producer waits for drain after the accepted first chunk.
- The next chunk y is sent once, producing xy rather than xxy.
import { Writable } from "node:stream"; import { once } from "node:events"; let out = ""; const sink = new Writable({ highWaterMark: 1, write(c, e, cb) { out += c; setImmediate(cb); } }); if (!sink.write("x")) await once(sink, "drain"); sink.end("y"); await once(sink, "finish"); console.log(out);
xy
Why this result follows: The next chunk y is sent once, producing xy rather than xxy.
10. Already-aborted pipeline
Problem: Observe rejection when pipeline receives an already-aborted signal.
- The controller is aborted before pipeline is invoked.
- The Node fixture rejects with AbortError and the owner catches it.
import { Readable, Writable } from "node:stream"; import { pipeline } from "node:stream/promises"; const c = new AbortController(); c.abort(); const sink = new Writable({ write(x, e, cb) { cb(); } }); try { await pipeline(Readable.from(["x"]), sink, { signal: c.signal }); } catch (e) { console.log(e.name); }
AbortError
Why this result follows: The Node fixture rejects with AbortError and the owner catches it.
11. Split UTF-8 bytes
Problem: Decode a character whose bytes arrive in separate chunks.
- The first byte is an incomplete UTF-8 sequence.
- StringDecoder retains the byte until the second completes é.
import { StringDecoder } from "node:string_decoder"; const d = new StringDecoder("utf8"); const first = d.write(Buffer.from([0xc3])); const second = d.write(Buffer.from([0xa9])); console.log(JSON.stringify(first), second);
"" é
Why this result follows: StringDecoder retains the byte until the second completes é.
12. Split line fragments
Problem: Reconstruct a newline-delimited record split across chunks.
- The first fragment is incomplete until the second supplies newline.
- The framing loop emits hello once after the delimiter arrives.
let pending = ""; const lines = []; for (const chunk of ["hel", "lo\n"]) { pending += chunk; let i; while ((i = pending.indexOf("\n")) !== -1) { lines.push(pending.slice(0, i)); pending = pending.slice(i + 1); } } console.log(JSON.stringify(lines));
["hello"]
Why this result follows: The framing loop emits hello once after the delimiter arrives.
13. Multiple records
Problem: Extract two records from a single synthetic text chunk.
- One chunk contains two newline delimiters.
- The loop emits both records rather than assuming one per chunk.
let pending = "a\nb\n"; const lines = []; let i; while ((i = pending.indexOf("\n")) !== -1) { lines.push(pending.slice(0, i)); pending = pending.slice(i + 1); } console.log(JSON.stringify(lines));
["a","b"]
Why this result follows: The loop emits both records rather than assuming one per chunk.
14. Final fragment
Problem: Apply a stated policy to a final unterminated fragment.
- The input ends with text but no newline.
- This fixture deliberately accepts the remaining fragment as one final record.
const pending = "last"; const records = []; if (pending) records.push(pending); console.log(JSON.stringify(records));
["last"]
Why this result follows: This fixture deliberately accepts the remaining fragment as one final record.
15. Bound pending bytes
Problem: Reject an incomplete record larger than its synthetic byte limit.
- The ASCII fragment occupies four bytes, exceeding the limit three.
- The explicit bound prevents accepting this oversized pending record.
const pending = "abcd", max = 3; console.log(Buffer.byteLength(pending, "utf8") > max ? "too-large" : "ok");
too-large
Why this result follows: The explicit bound prevents accepting this oversized pending record.
16. Object-mode sum
Problem: Aggregate synthetic records through an object-mode writable.
- The sink receives two record objects with values two and three.
- The incremental accumulator reaches five without storing a result list.
import { Readable, Writable } from "node:stream"; import { pipeline } from "node:stream/promises"; let total = 0; const sink = new Writable({ objectMode: true, write(row, e, cb) { total += row.n; cb(); } }); await pipeline(Readable.from([{ n: 2 }, { n: 3 }]), sink); console.log(total);
5
Why this result follows: The incremental accumulator reaches five without storing a result list.
17. Retained array grows
Problem: Show application retention despite incremental processing.
- The application appends every processed record to an array.
- The retained result count grows with rows regardless of stream flow control.
const retained = []; for (const row of [{n:1}, {n:2}, {n:3}]) retained.push(row); console.log(retained.length);
3
Why this result follows: The retained result count grows with rows regardless of stream flow control.
18. Bounded retained window
Problem: Keep the latest two values while processing a longer sequence.
- The oldest value is removed after the window exceeds two.
- The final retained window contains only three and four.
const window = []; for (const n of [1, 2, 3, 4]) { window.push(n); if (window.length > 2) window.shift(); } console.log(JSON.stringify(window));
[3,4]
Why this result follows: The final retained window contains only three and four.
19. Await finish
Problem: Wait for a writable to finish after its last synthetic chunk.
- The end call sends the final data and requests completion.
- The owner waits for finish before reporting the collected output.
import { Writable } from "node:stream"; import { once } from "node:events"; let out = ""; const sink = new Writable({ write(c, e, cb) { out += c; cb(); } }); sink.end("done"); await once(sink, "finish"); console.log(out);
done
Why this result follows: The owner waits for finish before reporting the collected output.
20. Empty pipeline
Problem: Complete a pipeline with no source chunks.
- The readable contains no chunks to deliver.
- The pipeline completes and the writable callback count remains zero.
import { Readable, Writable } from "node:stream"; import { pipeline } from "node:stream/promises"; let count = 0; const sink = new Writable({ write(c, e, cb) { count++; cb(); } }); await pipeline(Readable.from([]), sink); console.log(count);
0
Why this result follows: The pipeline completes and the writable callback count remains zero.
Common errors and fixes
The process reports success before writing finishes
- Why it happens
- The pipeline promise was started but not observed.
- How to fix it
- Await the promise or attach a rejection handler at the owning boundary.
- Prevent it next time
- Test delayed completion and injected failure.
Memory grows with a slow consumer
- Why it happens
- Chunks are accumulated without respecting the destination’s capacity.
- How to fix it
- Use stream flow control and pipeline rather than an unbounded buffer.
- Prevent it next time
- Test with a slow writable and representative input sizes.
A partial file is mistaken for a complete result
- Why it happens
- A failed pipeline cannot roll back external effects automatically.
- How to fix it
- Use a documented temporary-output and publication strategy.
- Prevent it next time
- Test failure after some bytes have been written.
20 practice exercises
1. What happens when the sink callback receives an error?
Show hint
A destination callback error rejects the owned pipeline promise.
Show worked solution
The pipeline promise rejects and the catch receives the error. The owner must treat the operation as failed and apply its cleanup policy; partial external effects may still need attention.
The pipeline promise rejects and the catch receives the sink error. Treat the operation as failed and apply the cleanup policy; partial external effects may already exist and need separate handling. Test that no normal success is reported.
Check your solution
- The owner observes the sink error.
- Cleanup and partial-effect policy are applied.
2. Why is an uppercase transform not a general Unicode text processor?
Show hint
Byte chunks do not guarantee complete Unicode characters or records.
Show worked solution
Byte chunks can split a multibyte character and text processing may require boundaries across chunks. Use an appropriate streaming decoder and define record handling, then test characters split across chunk boundaries.
A multibyte character can be split across byte chunks, and text transformations may require context across chunks. Use an appropriate streaming decoder and explicit record handling, then test a character split at the byte boundary and a final fragment.
Check your solution
- A split multibyte character is decoded correctly.
- Record and final-fragment policies are tested.
3. A pipeline source emits Error("source") before any chunk reaches the sink. State the expected owner outcome.
Show hint
Await the pipeline promise and distinguish source failure from a sink callback error.
Show worked solution
The pipeline rejects with the controlled source error, and the owner must observe it instead of reporting success. Verify that the sink received zero chunks and that owned resources are cleaned up. This tests a source-stage failure independently from the original sink-failure exercise.
Check your solution
- The owner observes the source error.
- The sink records zero chunks and no success marker.
4. Two chunks contain ASCII text "ab" and "cd". State the limited uppercase pipeline result and one untested boundary.
Show hint
Trace both chunks, then consider a split multibyte character separately.
Show worked solution
The controlled ASCII transform produces "ABCD" after both chunks complete. That result alone does not establish correct handling of a UTF-8 character split across byte chunks; add a streaming-decoder test for that boundary and await pipeline completion.
Check your solution
- The ASCII output is exactly ABCD.
- A split UTF-8 character has a separate decoder test.
5. Trace a readable, uppercase transform, and writable for ASCII chunks "ab" and "cd".
Show hint
Await the pipeline before asserting the combined output.
Show worked solution
The controlled ASCII pipeline produces "ABCD". Await pipeline so the assertion happens after the writable completes, and handle rejection at an owner. This fixture does not establish correctness for arbitrary Unicode or record-sensitive transformations.
Check your solution
- The completed output is ABCD
- The pipeline promise is awaited
6. Inject separate source, transform, and sink failures into a pipeline test suite.
Show hint
Each stage can fail and needs an observed outcome.
Show worked solution
Use separate synthetic fixtures that fail at each stage, await each pipeline rejection, and assert the expected category or message. Verify resource cleanup and no success report. Include a successful finite pipeline as a control; do not assume partial output is rolled back.
Check your solution
- All three stage failures reach an owner
- A successful control completes and cleanup is verified
7. A writable accepts "x" but returns false. Specify when to send "y".
Show hint
Do not resend the accepted chunk; wait for drain.
Show worked solution
Treat x as accepted, pause additional writes, and wait for drain while observing errors and cancellation. Then send y once. A recording sink should produce "xy", not "xxy". Pipeline can normally coordinate this flow when its abstraction fits.
Check your solution
- x is not resent
- y is sent once after drain
8. Explain why a manual wait for drain also needs error and cancellation handling.
Show hint
A failed or destroyed stream may not produce the expected drain.
Show worked solution
While production is paused, observe terminal errors and cancellation so the owning workflow settles rather than waiting forever. Prefer pipeline where appropriate. Test a controlled failure during the wait and assert cleanup and rejection reach the owner.
Check your solution
- Additional writes remain paused
- Failure or cancellation settles the workflow
9. Decode UTF-8 bytes c3 and a9 arriving as two chunks.
Show hint
Use a streaming decoder that retains an incomplete character.
Show worked solution
Feed both buffers to StringDecoder in order and flush it at the end. The first byte alone produces no complete character; the second completes "é". Assert exact output and define how invalid or incomplete final bytes are handled.
Check your solution
- The combined output is é
- The final decoder behavior is tested
10. Frame "hello\n" when the bytes arrive as "hel" and "lo\n".
Show hint
Retain the incomplete suffix until a delimiter arrives.
Show worked solution
Keep "hel" after the first chunk, append the second, and emit "hello" at the newline. Test two records in one chunk and an unterminated final fragment separately. Bound retained bytes so a missing delimiter cannot grow memory without limit.
Check your solution
- One hello record is emitted
- The pending suffix is empty
11. Explain why pipeline rejection does not automatically roll back a destination write.
Show hint
Some output may have been accepted before the error.
Show worked solution
A later failure does not erase bytes or external effects already written. If atomic publication is required, design a temporary or transactional destination and commit policy appropriate to the actual storage. Test a controlled failure after partial progress.
Check your solution
- Partial output is not assumed undone
- Recovery or publication policy is explicit
12. Cancel a supported pipeline with an already-aborted signal and inspect the outcome.
Show hint
Await the pipeline rejection and classify abort separately.
Show worked solution
Pass an already-aborted signal to the supported pipeline, await rejection, and assert the documented AbortError outcome for the target Node version. Verify owned resources outside the pipeline are cleaned up. Do not assume cancellation reverses completed external effects.
Check your solution
- The pipeline rejects as aborted
- External owned resources are cleaned separately
13. Explain why storing every processed row defeats a total-memory bound from backpressure.
Show hint
Application-retained results are separate from stream buffers.
Show worked solution
Backpressure can limit flow between stages while the application array grows with each row. Persist or aggregate incrementally, or retain a documented bounded window. Measure memory with increasing representative inputs and inspect every retained stage state.
Check your solution
- Retained rows are counted separately
- A bounded strategy is measured
14. Use a two-item window while processing [1, 2, 3, 4].
Show hint
Drop the oldest item after the window exceeds two.
Show worked solution
Append each value and remove the oldest when length exceeds two. The final window is [3, 4], and the post-update length never exceeds two. This bounds that application collection but does not prove every stream buffer or record has a production limit.
Check your solution
- The final window is [3, 4]
- The post-update window length is at most two
15. Test that a failed sink produces no success marker and that its error is observed.
Show hint
Await the pipeline and record success and failure events.
Show worked solution
Use a writable whose callback reports Error("sink"), await pipeline, and assert the owner records the sink error rather than success. Verify cleanup and any partial-effect policy separately. A test that only starts pipeline can finish before rejection is observed.
Check your solution
- The sink error reaches the owner
- No success marker is recorded
16. Explain why a local ASCII pipeline success is not proof of general text correctness.
Show hint
Encoding and record boundaries require additional cases.
Show worked solution
The fixture supports its ASCII output under the stated Node version, but it does not cover multibyte splits, context-sensitive operations, invalid encodings, or final fragments. Use a streaming decoder and test representative boundary cases in the target environment.
Check your solution
- The ASCII fixture scope is stated
- Unicode and framing boundaries are tested separately
17. Design a complete pipeline test matrix with success, three failure stages, and cancellation.
Show hint
Use controlled finite sources and owned destinations.
Show worked solution
Assert exact successful output, then inject source, transform, and sink errors separately and await each rejection. Add an aborted-signal case, verify resource cleanup and partial-effect policy, and test backpressure without resending accepted chunks. Keep all fixtures synthetic and isolated.
Check your solution
- Every stage failure is observed
- Cancellation and cleanup are tested
18. Explain why a local in-memory pipeline test does not establish production durability.
Show hint
The fixture has no real durable destination or crash recovery.
Show worked solution
A passing in-memory pipeline supports its synthetic flow and error behavior only. It does not prove a file or remote sink is durable, atomic, or safe across process failure. Define those guarantees and test the actual destination in an authorized environment.
Check your solution
- The in-memory scope is recorded
- Durability is verified separately
19. Process object records {n: 2} and {n: 3} through an object-mode sink and verify their running total.
Show hint
Accumulate each record value and await pipeline completion.
Show worked solution
Use an object-mode writable that adds each validated n to an accumulator, await pipeline, and assert the total is 5. Also assert that a controlled sink error rejects instead of reporting success. The local fixture does not prove a production memory bound.
Check your solution
- The completed total is 5.
- A controlled sink error is observed separately.
20. Bound an unterminated pending record "abcd" to a maximum of three UTF-8 bytes.
Show hint
Count encoded bytes before retaining more input.
Show worked solution
The ASCII fragment occupies four UTF-8 bytes, so it exceeds the synthetic maximum of three and must follow the documented too-large path. Test a three-byte boundary and a multibyte character separately; the limit belongs to the actual service contract.
Check your solution
- The fragment counts as 4 bytes.
- The three-byte policy rejects it before further buffering.
Key takeaways
- Observe completion and errors for the whole pipeline.
- Flow control does not automatically roll back partial external effects.
- A sink callback error rejects the pipeline promise.
- A false write return accepts the current chunk but pauses additional production.
- An ASCII chunk transform is not a general Unicode processor.