Resources / Blog

Helix: Coordinating agent swarms for Ada to C porting

This translation was carried out by Helix, H2LooP's code modernization platform. Helix ported an 8-package CCSDS protocol library from Ada to C in a single automated run, correcting its own output as it went - then verified the result three ways: a behavioural suite carried across from the source, an integration gate per dependency wave, and exhaustive formal proof over every public entry point.

The subject

An 8-package protocol library where a byte-order error is a mission anomaly

ccsds_ada implements the CCSDS space data-link protocols - Space Packets, AOS transfer frames, CFDP file delivery, CUC and CDS time codes, encapsulation, and SLE service taxonomy. The source language was chosen for its compile-time guarantees, and those guarantees are what a translation to C stands to lose.

MetricValue
Lines of Ada2,408
Packages8
Preconditions35
Postconditions17
Range types20

Why this language pairing is hard

Ada carries specification that C has no way to hold. A declaration like type APID_Type is range 0 .. 16#7FF# is enforced by the compiler at every assignment; the natural C translation is uint16_t, which accepts anything. A Pre => clause is a checked contract; in C it becomes, at best, an assert somebody remembered to write.

Seventy-two contracts and constrained types in this library have no representation in the target language. A translation can be syntactically flawless and silently discard every one. The gap is therefore in the contracts, not the syntax.

The source library

Eight Ada specification packages, each a distinct area of the CCSDS standard. Helix reads the repository as it is - its own project file, its own build, its own test programs - rather than requiring it be restructured first.

PackageCoversSpec lines
ccsds.adsRoot types: APID, sequence count, packet version, data length158
ccsds-cfdp.adsFile Delivery Protocol: PDU headers, directive and condition codes245
ccsds-time_codes.adsCUC and CDS time code formats219
ccsds-aos_frames.adsAOS transfer frames, virtual channels, frame error control155
ccsds-sle.adsSpace Link Extension service taxonomy136
ccsds-space_packets.adsSpace Packet primary header and payload130
ccsds-encap_packets.adsEncapsulation packets and length-of-length encoding111
ccsds-crc16.adsCRC-16-CCITT-FALSE, single-shot and streaming82

The repository also ships four hand-written test programs - no framework, just Check_X ("name", …) calls - which Helix builds and runs against the original Ada before trusting anything downstream. A suite that cannot be made to pass on the source is not a usable oracle for the target.

The dependency graph Helix constructed

12 capability requirements · 3 levels · derived, not declared

Decomposition is not package-by-package. It decomposes the library into capabilities - what the code does, not where it lives - and derives dependency edges between them. Each requirement's level is its longest path through that graph, which is what makes independent work provably independent.

Dependency graph: one frozen API requirement in wave 0. Six wave 1 capabilities declare a dependency on it and four more have that edge inferred by Helix. Wave 2's FECF requirement declares dependencies on both the CRC capability and the API layer. The graph Helix derived. One structural requirement forms the frozen API layer. Eight edges into it were declared by the analyzer; four were inferred by Helix, which is what puts every capability behind the shared type surface rather than beside it. The ten wave 1 capabilities depend on nothing else, so all ten translate at once; only FECF has a second dependency, so it waits.

The inferred edge

Analysis produces the edges a reader would recognise - AOS frame checking needs CRC. Helix adds one kind of its own: every requirement outside the frozen API layer depends on all of it. On this library that inferred four extra edges.

Without it, the shared type surface would be translated concurrently with the code that compiles against it, and each translator would invent its own version of the same integer aliases and structures. The edges are cycle-free by construction - they run only outward from the API layer, and an API member declares no dependencies - so the schedule can never deadlock as a result.

The consequence is intended and worth stating plainly. Nothing is independent of the API layer, so if wave 0 fails, everything fails. That is honest: nothing compiles without the shared types. A schedule that pretended otherwise would report ten green units built against a surface that never existed.

The workflow, stage by stage

Ten stages · every one an auditable queue entry

Translation is not file-to-file. It analyses the source into a requirement graph, derives a target structure from it, declares the shared API before writing any code, translates the test suite before the implementation, then admits one unit at a time.

  1. Explore

  2. Parse the source into a complete entity inventory - every subprogram, type and constant. This inventory is load-bearing: it becomes the mandatory checklist that later stages are measured against, so anything a parser misses is never asked about rather than flagged as missing.

  3. OUTPUT 8 units · 177 entity checklist items

  4. Requirements

  5. Turn the inventory into a graph of capabilities with dependency edges - not one requirement per file, but per behaviour the library provides. Helix adds one inferred edge kind of its own: everything outside the frozen API layer depends on all of it, so the shared type surface is settled before anything compiles against it.

  6. OUTPUT 12 requirements · 4 inferred edges · 3 dependency waves

  7. Structure

  8. Map every requirement to a file in an idiomatic target tree. Grouping is language-agnostic - it reads source stems, directories and requirement names - and each target language renders those placements into its own conventions. The result is src/aos/, src/cfdp/, src/time_codes/: organised by concept, not by slug.

  9. OUTPUT 24 files across 12 requirements

  10. Approve

  11. The pipeline's one human gate. The proposed structure and schedule are reviewed and approved before a single line is written; afterwards nothing may recompute a target path. An unattended run stops here and says so rather than proceeding on an unreviewed plan.

  12. OUTPUT structure frozen & committed

  13. Scaffold

  14. Commit a real, compiling skeleton to the target repository - build files, module declarations, one stub per requirement. Every unit therefore opens onto a crate that already builds, which is why the first compile inside a sandbox succeeds rather than failing on missing scaffolding.

  15. OUTPUT 30 files committed

  16. Declare the API

  17. One pass, with the whole requirement graph in view, authors the shared declaration surface: type aliases, structs, function signatures with unimplemented bodies. Without it, a dozen independent translators each invent their own version of the shared types and later waves compile against whichever landed first. Gated by a real build on the target platform, and retried against the compiler's own errors until it holds.

  18. OUTPUT 12 requirements declared · build gate passed

  19. Translate the test suite - before any code

  20. The source's own suite is carried across while the implementation is still stubs. A test written afterwards can be fitted to whatever the code happens to do; a test written before it cannot. Helix enforces the ordering structurally, and rejects any translated test that passes against unwritten code - a test that passes there is asserting nothing.

  21. OUTPUT 4 suites · 253 assertion sites · stowed until code exists

  22. Implement, wave by wave

  23. Each requirement is translated in its own isolated sandbox: translate, build, test - three phases the sandbox reports separately, so a failure is attributed rather than inferred from an exit code. A unit is admitted only when its box built it and its tests passed, and retries refine the same workspace rather than starting over.

  24. OUTPUT 12/12 units translated · 171-235s each

  25. Merge and gate

  26. Each unit merges the moment it lands rather than waiting for its wave, so conflict resolution overlaps with translations still running. Exactly one merge consumer exists, because two concurrent merges cannot share a repository. Each completed wave is then built and tested as a whole, on the target platform.

  27. OUTPUT 12 merges · 0 conflicts · 3/3 gates passed

  28. Prove, then report

  29. With the library assembled, formal verification runs over every public entry point, followed by the run's final rollup. Proof runs after the last merge because merges can change code that already passed its own gate - verifying earlier would verify something that no longer exists.

  30. OUTPUT 1,026 properties checked across the merged library

Waves, and why concurrency is safe

A wave is a level in the dependency graph, not a batch size

Helix computes each requirement's wave as its longest-path depth over the dependency edges, so siblings stay on the same level rather than being serialised behind one another. Wave width is therefore a property of the source library, not of the machine running it.

WaveRequirementsContainsConcurrency
01Frozen API layer - shared binary storage primitives1
110CRC, AOS, CFDP, time codes, encapsulation, SLE, space packets10
21AOS FECF computation, which depends on CRC1

Wave 1's ten requirements are independent by construction, so all ten translated at once. Pool size is derived from the widest wave capped by the capacity of the machine actually hosting the sandboxes - never more boxes than the graph can use, never more than the host can hold.

What makes it reproducible

Every member of a wave branches from the same pinned base, fixed when the wave opens. Without that, a unit finishing early would change the starting point of one finishing later, and the same inputs would produce different histories on different machines. The wave boundary is the one hard ordering rule: every merge of wave N completes before wave N+1 dispatches.

The isolation model

One container per unit · nothing reaches the host

Each unit is translated inside its own container on a dedicated build host. The agent doing the work has no path to the orchestrator, the source repository, or any credential beyond the single API key forwarded to it by name. It edits a synced working copy and reports what it changed; the orchestrator commits outside the box.

PropertyHow it is enforced
Units cannot interfereSeparate container and separate worktree per unit, even when sharing a host
Build output never shipsObject files, lockfiles and run state excluded from what a unit may commit
Gates run on the target platformNever on the operator's machine - char signedness alone differs between them
Failures are attributedTranslate, build and test each report separately with their own evidence
Infrastructure faults are not code faultsA degraded machine is replaced, not counted against the unit's retry budget

Provisioning is amortised across the run: containers are warmed once and reused, so the build cache stays warm and setup cost drops from tens of seconds on the first unit to under a second on the rest.

Run results

Single automated pass · 10 parallel sandboxes · launched from the console

MetricResult
Units translated12/12 — Every requirement implemented and committed
Merges clean12/12 — Zero conflicts across three waves
Integration gates3/3 — Built and tested on the target platform
Recorded operations80 — Every step auditable after the fact

Individual units completed in 171 to 235 seconds. The whole run was launched and observed from the Helix console with no terminal in the path - the same interface a customer's engineer would use.

The translation itself

Read the C beside the Ada · every constrained type accounted for

Process evidence says a run completed. It does not say the C is any good. This section is the output read against its input: what happened to the types, what happened to the contracts, and whether the bits land where the standard says they land.

MetricResult
Range types preserved20/20 — Every Ada constrained scalar became a callable C predicate, bounds intact
Public functions61 — From 49 Ada subprograms, expanded where C needs an explicit constructor
Contracts as assertions38 — Ada Pre => clauses restated where the harness can resolve them
Files, concept-grouped24 — src/aos/, src/cfdp/, src/time_codes/ - not file-for-file

What happened to the constrained types

This is the hardest thing to carry across, and the easiest to lose silently. Ada declares twenty constrained scalar types; C has no equivalent construct. A literal translation maps each to the nearest integer width and the constraint disappears with no diagnostic.

Every one of the twenty came across as a named type plus a callable validity predicate, with the bounds preserved exactly - including the lower bounds, which are the ones a careless port drops:

Ada declarationC typeC predicate
type APID_Type is range 0 .. 16#7FF#apid_type_tx <= 0x7ffu
type Sequence_Count_Type is range 0 .. 16#3FFF#sequence_count_type_tx <= 0x3fffu
type Virtual_Channel_ID is range 0 .. 63aos_virtual_channel_id_tx <= 63
type Frame_Count_Type is range 0 .. 16#FFFFFF#aos_frame_count_type_tx <= 0xFFFFFF
type Entity_ID_Length is range 1 .. 8cfdp_entity_id_length_tx >= 1u && x <= 8u
type CUC_Coarse_Octets is range 1 .. 4cuc_coarse_octets_tx >= 1u && x <= 4u
type Reporting_Cycle is range 0 .. 600sle_reporting_cycle_tx <= SLE_REPORTING_CYCLE_MAX

One case is worth reading closely. Data_Length_Type is range 0 .. 16#FFFF# became uint16_t with the predicate (void)x; return true;. That is not a stub - the C type's own range is exactly the Ada range, so the check is genuinely vacuous and the translation says so rather than emitting a comparison that can never fail. The predicate still exists, so call sites read identically to every other domain and a later widening of the type has one place to change.

What happened to the unconstrained arrays

Ada's Byte_Array carries its own bounds; the reflexive C translation is a bare uint8_t *, which loses them. The port instead defines a view type passed by value, so length travels with the pointer and every callee has the bound the Ada guaranteed:

/* Storage_Array is represented as a view: the pointer denotes the first
   element and length is the number of elements. Passing the view by value
   preserves Ada's unconstrained-array bounds without exposing a bare pointer. */
typedef struct {
    const ccsds_byte_t *data;
    size_t              length;
} ccsds_byte_array_t;

Side by side: CRC-16, contract and all

The source states a precondition; the translation states it too, and says where it came from. Note also what the translation chose not to copy - the Ada special-cases a two-byte buffer, the C does not need to, because a CRC over a zero-length payload already returns the initial register value:

**Ada - ****ccsds-crc16.ads/.adb**

function Verify_Trailer (Full : Byte_Array)
  return Boolean
  with Pre => Full'Length >= 2;
if Full'Length = 2 then
  Actual := Initial_Value;
else
  Actual := Compute (Full (Full'First .. Payload_Last));
end if;

**C - ****src/crc16.c**

bool crc16_verify_trailer(ccsds_byte_array_t full)
{
  /* This is the Ada Pre condition: Full'Length >= 2. */
  assert(full.length >= 2u);
const ccsds_byte_array_t payload =
  { full.data, payload_length };
return crc16_compute(payload) == expected;

The comment carries the provenance: a reviewer reading the C alone can see that the assertion is a transcribed source contract rather than a defensive guess. The CRC parameters survive verbatim - polynomial 0x1021, seed 0xFFFF, check value 0x29B1 over "123456789" - and the fold is written with an explicit cast on every shift, which is the integer-promotion trap that silently breaks hand-written CRC code in C.

Side by side: the Space Packet primary header

Six bytes with fields at bit boundaries - the place a translation is most likely to be subtly, undetectably wrong. The standard's layout, the Ada, and the C agree field by field:

Byte 0:  [VVV T S AAA]     CCSDS 133.0-B-1
-- Ada
Result (0) := Byte (Shift_Left (V, 5) or Shift_Left (T, 4)
                    or Shift_Left (S, 3) or A_H);
Result (2) := Byte (Shift_Left (SF, 6) or SC_H);
/* C */
r.data[0] = (uint8_t)((h.version << 5) | (packet_type_to_bit(h.packet_type) << 4) |
                      (sec_header_to_bit(h.sec_header) << 3) | ((h.app_id >> 8) & 7));
r.data[2] = (uint8_t)((seq_flag_to_bits(h.seq_flags) << 6) | ((h.seq_count >> 8) & 0x3f));

Same shifts, same masks, same byte order. The CCSDS off-by-one on the length field - the wire value is the payload length minus one - is preserved in both the encoder and the decoder, which is exactly the kind of domain detail that a syntax-directed translation gets wrong in one direction and not the other.

The encoder also asserts the domain of every field before packing it, which is the range types doing their work at the boundary where C would otherwise accept anything:

assert(apid_type_is_valid(h.app_id) && sequence_count_type_is_valid(h.seq_count));
assert(h.seq_flags <= STANDALONE);

Idiom, not transliteration

A syntax-directed port produces C that reads as Ada in disguise. Several choices here are made against the source's structure because the target language wants something different:

Ada constructRendered asWhy
Hierarchical packages CCSDS.AOS_Framessrc/aos/primary_header_codec.cDirectory structure by concept; the header is the package spec
Enumeration typestypedef enum { CONTINUATION = 0, … }Representation values pinned, because they are wire values
Functions returning a discriminated resultStatus-plus-payload struct returned by valueNo out-parameters, no sentinel returns, no allocation for the common path
pragma Inlinestatic inline in the headerPredicates and accessors stay zero-cost at call sites
Package-private Fold_Bytestatic function in the .cInternal linkage is C's equivalent of body-only visibility

The result compiles clean, exposes 61 functions across 12 headers, and is organised the way a C engineer who had never seen the Ada would expect to find it.

What formal verification found

Exhaustive, not sampled

After the final merge, Helix proves properties over the assembled library: array bounds, pointer validity, pointer-arithmetic and integer overflow, division by zero, and loop termination - for every input the source contract admits, rather than the inputs a test happened to try.

MetricResult
Entry points proved27 — Exhaustively, for all admitted inputs
Properties checked1,026 — Across the merged library
Property classes7 — Bounds, pointer validity, overflow, division, termination
Defects located56 — With file, line and the failing condition

The prover located pointer-arithmetic defects that 253 behavioural assertions did not reach.

A behavioural suite exercises the inputs its author thought of; the prover exercises all of them. Where the Ada guaranteed an index was in range by construction, the translated C had no such guarantee - and each instance was located precisely:

src/crc16.c:32 in crc16_compute
  pointer arithmetic: pointer NULL in data.data + (signed long int)i
  must hold: !(__CPROVER_POINTER_OBJECT(NULL) == …)

A file, a line, the defect, and the condition that must hold. Each finding is actionable on its own without re-deriving anything the checker already computed.

Reading the source contract back

Where the Ada stated a precondition, the C states it too - and Helix assumes it when proving, because "is this safe for callers that honour the contract" is the question the Pre => clause always asked. Where a function states no precondition, nothing is assumed and the proof is unconditional. A function with no stated precondition is therefore proved unconditionally or not at all.

How results are reported

Proved means exhaustively verified: no input satisfying the source contract can violate the checked properties. Helix records the verdict per entry point together with the checks it was asked to discharge and the caller obligations it assumed, so each result can be read with its premises rather than on its own.

The formal stage records which entry points are proved, against which checks, and under which caller assumptions. It is diagnostic: it cannot gate the run, and the rollup does not read it.

The console

A run is launched, watched, paused and inspected from one console. Each surface answers a different question, and every number shown traces to a file on disk.

Thirteen surfaces · one run · start to evidence

Run control

A run takes hours, and can be interrupted. Pause is honoured between steps and at wave boundaries - never mid-unit, because a sandbox already translating has been paid for. Resume picks up from the last recorded verdict rather than the top: a unit whose box already answered is not re-run, and its output is reused.

A hard kill leaves entries that claim to be running when nothing is. Helix detects that by process identity rather than a timer - a translation can legitimately go forty minutes without touching the queue - reclaims those entries, and says it did so rather than quietly repairing them. A new attempt mints a fresh queue and marks the old one superseded rather than overwriting it, because a queue is the record of what a run did.

Diagnosis and repair

When a translated test disagrees with the implementation, the question is which one is wrong. A recorded answer key acts as referee where one exists. Proposed fixes are held to a rule that makes them safe to accept:

  • the passing set is captured before any edit, because afterwards "already broken" and "this patch broke it" are indistinguishable;

  • a fix that repairs its target and breaks anything else is reverted, whatever it fixed;

  • a fix that helps but falls short of its own prediction is held for a decision rather than applied silently;

  • a repair may never edit the tests it is judged by.

Scope of the proofs

For a proved entry point, the claim is mathematical: no input satisfying the source contract can violate the checked properties. Not sampled, not fuzzed - every reachable state within the analysis bound is examined. This is a different kind of statement from a test result, which reports only the inputs that were tried.

Helix is equally precise about the boundary. Proofs are bounded, so an entry point that did not conclude is reported as such, never as passing. Where the caller's obligations were assumed, they are listed alongside the result, so a proof is always read together with its premises. Constructs that would make a verdict unsound are refused rather than answered.

Assumptions are listed next to each result, so a reviewer can examine the premises rather than only the conclusion.

Auditability

The record is the artefact

Everything is checked into the target repository alongside the code it describes: the requirement graph, the approved structure, per-unit state, and per-attempt evidence including the exact prompt, the sandbox output, and the model usage. The run queue itself is versioned in its own history, so a hand edit is detectable rather than invisible.

QuestionWhere it is recorded
Why is this function in this file?The approved structure, gated before any code was written
What was this unit asked to do?Per-attempt prompt, stored beside its output
Did a human approve the plan?An explicit queue entry with a timestamp
What did this step cost?Provider-reported usage on the entry, plus a per-call table
What is proved, and under what assumptions?Per entry point, with the assumed preconditions listed
What changed after a merge conflict?The resolution diff, stored per unit per wave

Results summary

CapabilityMeasured
Automated port of safety-critical Ada12/12 units · 2,408 lines · single pass
Idiomatic target structure, not file-for-file24 files, concept-grouped
Constrained types preserved, not erased20/20 range types, bounds intact
Dependency-aware parallel execution3 waves · 10 concurrent sandboxes
Clean integration12 merges · 0 conflicts · 3/3 gates
Behavioural equivalence testing4 suites · 253 assertion sites
Exhaustive formal verification27 entry points proved · 1,026 properties
Defects found beyond test coverage56 counterexamples, file and line
Full cost attribution226 calls, per step and attempt
End-to-end auditability80 recorded operations

Every step, sandbox, model call and property - proved or left open - is recorded in the target repository alongside the code, so the run can be reviewed against its own evidence.