A synthetic C++20/.NET 8 reliability lab comparing naive and safer designs for identity, IPC, recording failures, and process isolation.

In 2019, I worked on a Windows multimedia system that coordinated multiple camera sources. This was not a toy camera wrapper. The system combined native capture code, C++/CLI integration, a C# API, and a WPF client. Each camera ran in its own worker process. Commands traveled through Windows named pipes, while frame data was shared through memory-mapped memory. At a high level, the architecture already looked like this:

C# application
    │
    ├── control ──→ Named Pipe ──→ Camera Worker Process
    │
    └── frames  ←── Memory-Mapped Memory ←──┘

Each camera had its own process. Control traffic and frame traffic were separated. There was a source/filter/sink processing pipeline and an explicit recording-state model. For the constraints of the time, those were reasonable architectural decisions. The difficult part was not getting one camera frame onto the screen. The difficult part was making several technologies and several concurrent streams work together at all. And they did. But years later, looking at that design with a stronger reliability mindset, I noticed something more interesting. The broad architecture was not the main problem. The weak points were at the boundaries.

The Architecture Was Reasonable. Some Assumptions Were Not.

Consider device identity. The system obtained a persistent device identifier internally, but exposed and reopened devices using their enumeration index. That works as long as enumeration order stays stable. But an index is a position, not necessarily an identity. Now consider the command channel. The worker used a named pipe, but the protocol assumed that one ReadFile call contained exactly one complete command. That is a convenient assumption. It is not a reliable framing contract. The processing pipeline had another issue. It used queues between stages, but those queues were effectively unbounded and some state was shared across threads without sufficient synchronization. The architecture had a pipeline. What it did not have was a clearly defined overload contract. Shared memory had a similar problem. Moving frames through MMF was a sensible choice for local high-volume transport, but the shared frame layout lacked explicit versioning, torn-write detection, sequence markers, payload validation, and CRC protection. Recording had state, but successful initialization was easier to observe than a failure occurring later during write, flush, or finalization. None of these observations means the original architecture was foolish. Quite the opposite. It means a system can have the right architectural idea while still having weak contracts at the points where components meet. That became the subject of this project.

I Could Not Publish the Original Code

The original implementation is proprietary. Publishing it, anonymizing its class names, or lightly rewriting the code would not have been appropriate. So I took a different approach. I extracted several general engineering problems from the system and rebuilt them independently. No original customer code was copied. No original protocol, data structure, naming scheme, constants, media, or device integration was reused. The result is StreamBoundary Lab.

The public source is available in the StreamBoundary Lab repository. It is a synthetic Windows reliability laboratory built with C++20 and .NET 8. It is not a recreation of the original application. It recreates the problem classes.

Why There Is a “Naive” and a “Safe” Version

This is where the repository may look unusual at first. For each engineering problem, I intentionally implemented two approaches.

Naive

The reasonable shortcut. Not deliberately stupid code. Not “junior developer code.” It represents an assumption that can appear perfectly acceptable while the system is working normally.

Safe

A version where that hidden assumption has been turned into an explicit contract. The lab then creates a deterministic condition that breaks the naive assumption. The same condition is applied to the safe implementation. So each experiment follows this pattern:

reasonable assumption
        ↓
naive implementation
        ↓
controlled failure
        ↓
observable evidence

same problem
        ↓
explicit contract
        ↓
safe implementation
        ↓
same test condition
        ↓
expected invariant holds

This is why the repository contains code that is intentionally less safe. Without the naive version, the safer architecture would just look more complicated. With both versions, you can see exactly what problem the extra design is solving.

What I Chose to Revisit

I reduced the original system into four paired experiments, plus two additional reliability protections.

Four paired naive-vs-safe experiments

1. Identity

If two APIs enumerate the same sources, can I safely join them by index?

2. Transport

Should latency-sensitive commands share a path with large, continuous frame data?

3. Recording lifecycle

Does “the recorder opened” really mean “recording succeeded”?

4. Failure isolation

If one stream fails, how much of the application should stop? These four are the direct naive vs safe comparisons in the lab. Each deliberately reproduces a failure in the naive design and then checks the safer design under the same class of condition.

Two additional reliability protections

5. Backpressure

What happens when one stage of a processing pipeline cannot keep up? Here the focus is not a paired naive-vs-safe scenario. The lab demonstrates bounded queues, an explicit overflow policy, and observable drop counts so overload cannot hide as an ever-growing backlog.

6. Shared-memory integrity

How does a reader know it did not observe a frame while the writer was halfway through replacing it? Again, this is not a paired naive-vs-safe scenario. The lab demonstrates sequence markers, layout/version checks, payload validation, and CRC-based integrity checks for shared-memory frames. These are not camera-feature questions. They are reliability questions. And that distinction is the main reason I built StreamBoundary Lab.

The Point of the Lab

The portfolio version is not “better” because it has more features. It has far fewer. The original system dealt with real cameras, real multimedia APIs, multiple integration layers, recording, and actual application behavior. That was the harder product. StreamBoundary Lab deliberately removes most of that complexity. Its job is different. It takes reliability assumptions that were difficult to see inside a large real-world system and turns them into small experiments that can be reproduced, inspected, and tested. The original system demonstrates:

Can you make a difficult Windows multimedia integration work? The lab asks: Can you explain exactly where it can fail, reproduce that failure, and verify the architectural response? The rest of this article walks through those experiments and points directly to the files where the naive and safe designs differ.

If You Only Have a Few Minutes

You do not need to read the entire repository to understand the idea. Start here:

  1. Read the short background above so you know where the problem came from.
  2. Open managed/StreamBoundary.Lab/IdentityScenario.cs to see the smallest naive-vs-safe comparison.
  3. Open managed/StreamBoundary.Lab/Scenarios.cs and find SinkFaultAsync to see how the lab turns a hidden recording failure into an observable state transition.
  4. Run the paired demo and inspect the generated JSON evidence. Everything after that is a deeper technical tour.

Look Here: The Naive and Safe Versions Are Side by Side

One reason I built this repository as a lab rather than as a feature demo is that I wanted the design differences to be easy to inspect. You do not need to understand the entire repository. For each problem, there is a specific place worth looking at.

1. Source Identity — Start Here

Open: managed/StreamBoundary.Lab/IdentityScenario.cs This is probably the easiest example in the repository. The lab creates two independently ordered lists representing two different views of the same synthetic sources.

Naive: assume the same position means the same source

Look for:

if (mode == "naive")
{
    mismatches = discovery.Zip(capabilities)
        .Count(pair => pair.First.StableKey != pair.Second.StableKey);
}

The naive version pairs:

discovery[0]     ↔ capabilities[0]
discovery[1]     ↔ capabilities[1]
discovery[2]     ↔ capabilities[2]

It assumes that position means identity. That works only while both APIs happen to enumerate sources in the same order. The demo deliberately shuffles the two catalogs independently. So this assumption breaks.

Safe: identify the source explicitly

Immediately below it, look at the safe path:

var byKey = capabilities.ToDictionary(
    source => source.StableKey,
    StringComparer.Ordinal);

mismatches = discovery.Count(
    source => byKey[source.StableKey].StableKey != source.StableKey);

Now the relationship is:

source-amber  ↔ source-amber
source-cobalt ↔ source-cobalt
source-jade   ↔ source-jade

The array position no longer matters.

What to notice

The code difference is tiny. The architectural difference is not. Naive:

position = identity

Safe:

stable key = identity

That is the first boundary contract demonstrated by this lab.

2. Transport — Look at the Scenario First

Open: managed/StreamBoundary.Lab/Scenarios.cs Find: TransportAsync This method makes the naive/safe comparison explicit.

Naive

The important test is:

status.CommandDeadlineMisses > 0

and the naive worker also exposes a frame-sized sample through the control path. The demonstration intentionally injects transfer delay. The expected result is:

bulk frame data
       ↓
control path becomes busy
       ↓
command deadline misses

A deadline miss is not treated as an accidental test failure. It is the expected evidence that the naive design is unsafe.

Safe

Now notice this line:

FrameReadResult? frame =
    options.Mode == "safe"
        ? FrameRingReader.ReadLatest(worker.MapName)
        : null;

Safe mode reads the frame from the memory-mapped area instead of carrying the frame payload through the control exchange. And its assertion becomes:

status.CommandDeadlineMisses == 0
&& frame?.Validation == "Ok"

So the comparison is:

NAIVE

Named Pipe
 ├── commands
 └── frame-sized payloads

          ↓

commands can miss deadlines

versus:

SAFE

Named Pipe
 └── commands

Memory-Mapped File
 └── frames

          ↓

different workloads,
different transport paths

What to look at next

After Scenarios.cs, open: native/src/lab_core.cpp Look for: WorkerPipeline::FrameSample() The distinction is intentionally obvious:

std::string WorkerPipeline::FrameSample() const {
    if (safe_mode_) {
        return {};
    }

    return std::string(65536, 'A');
}

In the synthetic naive path, a large frame-like payload exists in the control response. Safe mode does not put that payload there. That is the core idea of the transport experiment.

3. Backpressure — Look at the Pipeline

Open: native/src/lab_core.cpp Find these methods:

WorkerPipeline::Generate
WorkerPipeline::Transform
WorkerPipeline::Publish

This is the synthetic processing pipeline. Conceptually:

Generate
   ↓
bounded queue
   ↓
Transform
   ↓
bounded queue
   ↓
Publish

In Generate, notice:

if (generated_queue_.Push(std::move(frame))) {
    ++dropped_;
}

And in Transform:

if (transformed_queue_.Push(std::move(frame))) {
    ++dropped_;
}

The important part is not simply that queues exist. The important part is that overload becomes observable. The system does not quietly pretend that an ever-growing backlog is normal. Instead:

consumer cannot keep up
        ↓
queue reaches its limit
        ↓
defined overflow policy
        ↓
dropped counter increments

Metrics expose this through:

metrics.dropped = dropped_.load();
metrics.queue_peak =
    std::max(
        generated_queue_.PeakSize(),
        transformed_queue_.PeakSize());

What to notice

The safe principle here is:

A queue is not only storage. It is an overload policy. The interesting question is not: “Do we use a queue?” It is: “What happens when that queue is full?”


4. Recording Failure — This Is One of the Clearest Comparisons

First open: managed/StreamBoundary.Lab/Scenarios.cs Find: SinkFaultAsync The lab deliberately asks the worker to fail after several writes:

await worker.StartPipelineAsync(
    failAfter: 4,
    cancellationToken);

Then look at the expected outcomes.

Naive

status.SinkState == "Active"
&& status.DetectedFaults == 0

This is deliberately wrong behavior. The write has failed, but the application still thinks recording is active. That reproduces this class of bug:

Open succeeded
    ↓
"Recording is OK"
    ↓
later write fails
    ↓
failure not reflected
    ↓
still reports Active

Safe

Safe mode expects:

status.SinkState == "Faulted"
&& status.DetectedFaults >= 1

Now open: native/src/lab_core.cpp Find: RecordingSink::Write This is the important difference:

const bool injected_failure =
    fail_after_ > 0 && writes_ >= fail_after_;

if (injected_failure && checked_mode_) {
    state_ = SinkState::Faulted;
    ++detected_faults_;
    return false;
}

The key is checked_mode_. The synthetic failure occurs in both designs. Only the checked/safe design converts that failure into an explicit state transition.

Compare them visually

NAIVE

Open
 ↓
Active
 ↓
Write fails
 ↓
Active   ← wrong
SAFE

Open
 ↓
Active
 ↓
Write fails
 ↓
Faulted  ← visible

Also look at: RecordingSink::Stop() The safe implementation checks flush and close failures before entering Finalized. So the state machine is not:

Open = success

It is:

Idle
 ↓
Active
 ↓
Faulted OR Finalized

That is a much stronger lifecycle contract.

5. Process Isolation — The Difference Is Almost Visual in the Code

Open: managed/StreamBoundary.Lab/Scenarios.cs Find: IsolationAsync

Naive: one process represents all logical sources

The naive branch creates:

WorkerClient.StartAsync(
    workerPath,
    "combined-sources",
    options.Mode,
    ...)

Then it kills that process:

monolith.Kill();

The assertion says exactly what the experiment demonstrates:

Shared process termination stops every logical source

In simplified form:

Process
 ├── Stream A
 ├── Stream B
 └── Stream C

      X crash

A stops
B stops
C stops

Safe: one worker per source

Now look at the safe branch. It creates three separate workers:

for (var index = 0; index < 3; ++index)
{
    var worker = await WorkerClient.StartAsync(
        workerPath,
        $"source-{index + 1}",
        options.Mode,
        ...);

    workers.Add(worker);
}

Then only worker 2 is killed:

workers[1].Kill();

Before and after the crash, the code measures streams 1 and 3:

var before0 = await workers[0].StatusAsync(...);
var before2 = await workers[2].StatusAsync(...);

workers[1].Kill();

var after0 = await workers[0].StatusAsync(...);
var after2 = await workers[2].StatusAsync(...);

And verifies:

var unaffectedAdvanced =
    after0.Published > before0.Published
    && after2.Published > before2.Published;

Then only source 2 is restarted.

The difference

NAIVE

      One Process
   ┌───────────────┐
   │ A   B   C     │
   └───────────────┘
          X
          ↓
      all stop
SAFE

 Process A   Process B   Process C
    │           │           │
    A           B           C
                X
                ↓
            restart B

 A keeps going         C keeps going

This is not primarily a threading optimization. It is a decision about failure scope.

6. Shared Memory — Look at How a Reader Knows a Frame Is Valid

Open: native/src/lab_core.cpp Find: SharedRing::Publish During a write, the sequence marker is first marked unstable:

slot->sequence_begin = stable | 1U;
slot->sequence_end = 0;

Then the payload and metadata are written. Only after that does the writer publish stable markers:

slot->sequence_end = stable;
slot->sequence_begin = stable;

Now find: SharedRing::ReadFrame The reader refuses to trust the frame unless the sequence markers match. It can return:

TornFrame
OversizedPayload
UnsupportedVersion
CrcMismatch
SequenceUnavailable

The CRC is checked here:

if (Crc32(copy) != slot.crc32) {
    return FrameValidation::CrcMismatch;
}

Why this matters

Safe mode did not become safe merely because frames were moved to shared memory. Shared memory creates its own problem:

reader
   ↓
reads while writer is halfway through?

So another contract is needed:

A frame is valid only if its markers,
length, version, and CRC are valid.

That is what this code demonstrates.

If You Are Reviewing This Repository

You do not need to read every file. Use this path:

Five-minute review

README.md
   ↓
managed/StreamBoundary.Lab/IdentityScenario.cs
   ↓
managed/StreamBoundary.Lab/Scenarios.cs

That is enough to understand the naive-versus-safe idea.

Fifteen-minute technical review

Then continue to:

native/src/lab_core.cpp

Look specifically for:

SharedRing::Publish
SharedRing::ReadFrame
RecordingSink::Write
RecordingSink::Stop
WorkerPipeline::Generate
WorkerPipeline::Transform
WorkerPipeline::Publish
WorkerPipeline::FrameSample

These are the places where most of the reliability decisions become concrete.

If You Want Proof Rather Than Architecture

Run:

./scripts/build.ps1
./scripts/test.ps1 -SkipBuild
./scripts/run-portfolio-demo.ps1

Then inspect the generated JSON evidence. The fields worth looking at are:

identityMismatches
commandDeadlineMisses
framesDropped
sinkState
detectedFaults
restartCount
failureReproduced
assertions

The repository is designed so that the reader can move through:

code
 ↓
expected failure
 ↓
run demo
 ↓
actual evidence

instead of having to take the architectural claims on trust.

Next: Applying the Same Pipeline Ideas to Real-Time AI

StreamBoundary Lab deliberately uses synthetic frames so the reliability problems can be isolated and reproduced deterministically. The next step is to apply the same pipeline ideas to a real camera and an AI object-detection workload, where slow inference turns backpressure from a synthetic reliability concern into a practical real-time systems problem. The key question will be simple:

What happens when the camera produces frames faster than the AI model can process them? That follow-up will focus on bounded queues, freshness, dropped frames, and keeping capture responsive while inference runs at its own pace.