Captain / Documentation / Part 7. Embedding Captain

The pure profile

Contents ↓

The pure profile, captain.pure/1, runs one exported, effect-free entry point of one exact .capb artifact, inside your own process. A run can change nothing outside itself. The profile has no effect provider, no secret resolver, no shell, no file system, no network, no clock and no source of randomness, so there is nothing for a program to reach.

This is Captain with no effects, not a reduced dialect of it. A pure entry is checked by the same checker and compiled by the same compiler as any other Captain program. What the profile adds is a contract about the boundary: what may go in, what comes out, how the call is identified, and how a result can be proved later.

The program

The examples in this part embed a small order calculation. It takes a list of order lines, each a record with a quantity and a unit price, and returns the total as an exact decimal:

orders.capt
module Orders::Form.

export struct OrderLine { quantity: Decimal, unitPrice: Decimal }.

export orderTotal lines: List[OrderLine] -> Decimal [
  total := 0.00.
  lines forEach: [ :line | total := total + ((line quantity) * (line unitPrice)) ].
  ret total.
].

export lineTotal quantity: Decimal unitPrice: Decimal -> Decimal [
  ret quantity * unitPrice.
].

The same module, with a few more entries, is the fixture of the SDK's structured-value tests (structured_values.rs).

Build it as you would any program, and look at what the artifact offers:

Terminal
$ captain build orders.capt -o orders.capb
built orders.capb ([..])
$ captain inspect orders.capb
package  Orders::Form 0.0.0
sha256   [..]
compiler 0.1.0   vm 2   stripped

exports
  lineTotal quantity: Decimal unitPrice: Decimal -> Decimal  (pure)
  orderTotal lines: List[OrderLine] -> Decimal  (pure)

entry points
  lineTotal quantity:unitPrice:  quantity=<Decimal> unitPrice=<Decimal>

pools: [..]

Three things in that listing matter to an embedder:

  • Both exports are (pure). Their effect sets are empty, so the pure profile admits them. An export that can reach any effect is refused.
  • vm 2 is the oldest VM generation the artifact needs. The compiler records the newest feature the program uses, and the SDK refuses an artifact that needs a generation it does not run (chapter 3).
  • Only lineTotal is an entry point of the command line. A command line can pass quantity=3, but it has no way to write a list of records. The SDK can, so it reaches orderTotal from its export, reading its parameters from the checked signature.

The command line runs the scalar entry, which gives a value to compare with later:

Terminal
$ captain run orders.capb lineTotal quantity=3 unitPrice=19.99
run log: lineTotal.runlog
59.97

Loading an artifact

Everything starts from the artifact's bytes. VerifiedProgram::load decodes them, verifies the bytecode and its manifest, and checks the VM generation:

rust
use captain_sdk::{LoadLimits, VerifiedProgram};

let bytes = std::fs::read("orders.capb")?;
let program = VerifiedProgram::load(&bytes, LoadLimits::default())?;

The SDK's own example, examples/pure_consumer.rs, embeds its fixture with include_bytes! instead of reading a file. Either way the SDK sees only bytes: it never reads Captain source, and it never looks for a sibling checkout.

LoadLimits bounds the artifact's size: 16 MiB by default, never more than 64 MiB. A VerifiedProgram is cheap to clone and owns its data, so one loaded program can serve many calls.

program.manifest() describes what was loaded: the package and its version, the compiler version, the VM generation the artifact needs, and a ManifestId. program.artifact_id() is the artifact's identity.

Listing entry points

entry_points() lists every exported entry the artifact can be called at, pure or not, in the manifest's order. Each EntryPointInfo holds the entry's full name, its signature as the checker wrote it, its parameters with their types, whether the pure profile admits it, and typed identities for the entry and its signature:

rust
for entry in program.entry_points() {
    println!("{}  pure={}  {:?}", entry.signature, entry.pure, entry.parameters);
}

For orders.capb this prints:

lineTotal quantity: Decimal unitPrice: Decimal -> Decimal  pure=true  [("quantity", "Decimal"), ("unitPrice", "Decimal")]
orderTotal lines: List[OrderLine] -> Decimal  pure=true  [("lines", "List[OrderLine]")]

An embedder can build a form, a validation step or a generated binding from this list, without hard-coding what the program takes.

Full names are exact. An entry's full name is its verb followed by its keywords, written together: orderTotal lines:, lineTotal quantity:unitPrice:. captain run accepts the short lineTotal as a convenience; the SDK does not. program.entry_point("orderTotal") fails with CAP-SDK-ENTRY-NOT-FOUND, because a name that is nearly right is not the entry you meant.

Planning a call

A call is planned before it runs. plan_pure takes the entry's full name, the arguments by name, and the execution limits:

rust
use captain_sdk::{Argument, ExecutionLimits, InputValue};

let dec = |mantissa, scale| InputValue::Decimal { mantissa, scale };
let line = |quantity, unit_price| InputValue::Record {
    type_name: "OrderLine".into(),
    fields: vec![("quantity".into(), quantity), ("unitPrice".into(), unit_price)],
};
let plan = program.plan_pure(
    "orderTotal lines:",
    vec![Argument {
        name: "lines".into(),
        value: InputValue::List(vec![
            line(dec(3, 0), dec(1999, 2)),
            line(dec(2, 0), dec(450, 2)),
        ]),
    }],
    ExecutionLimits::default(),
)?;

This is the SDK README's aggregate example, and the test an_order_total_is_one_call_over_a_list_of_records. A decimal is a mantissa and a scale: dec(1999, 2) is 19.99.

Planning checks everything that can be checked without running:

  • the artifact holds no secret reference, and the entry is pure;
  • every parameter is given exactly once, and no argument is unknown;
  • every value matches its declared type, all the way down (chapter 2);
  • the values and the limits are within bounds (chapter 3).

If anything is wrong, plan_pure returns an SdkError and nothing runs. If it succeeds, the PurePlan is frozen: its arguments are in the entry's order, its limits are copied in, and it has an identity, a PlanId, that binds the artifact, the manifest, the entry, its signature, the arguments and the execution context. The same call planned twice has the same PlanId.

Running it

execute runs a plan to the end, synchronously, on the calling thread:

rust
use captain_sdk::{execute, CancellationToken, ExecutionOutcome, OutputValue};

let execution = execute(&plan, &CancellationToken::new());
match &execution.outcome {
    ExecutionOutcome::Completed {
        value: OutputValue::Decimal { mantissa, scale },
        result_identity,
    } => println!("total {mantissa} scale {scale}, result {result_identity}"),
    other => println!("outcome {other:?}"),
}

For the two lines above this prints total 6897 scale 2: 3 × 19.99 + 2 × 4.50 = 68.97, exactly.

The Execution holds:

Field Is
outcome how the run ended (chapter 3)
instructions the VM instructions the run used
effects always 0 under this profile
run_record the canonical run record, as bytes
run_record_identity its RunRecordId
diagnostics codes and messages for people; never part of the outcome or the record

Execution is synchronous. A host that must not block puts it on a bounded worker of its own. CancellationToken can be cloned and shared across threads; a cancelled run stops between VM instructions.

Proving it later

The run record is the evidence of the call. verify_run_record checks a record against a plan, and for a completed run it executes the plan again and requires the same record, byte for byte:

rust
use captain_sdk::{verify_run_record, VerificationDisposition};

let verified = verify_run_record(&plan, &execution.run_record)?;
assert_eq!(verified.disposition, VerificationDisposition::Reexecuted);

Because the entry is pure and its inputs are frozen in the plan, anyone with the artifact, the arguments and the record can do the same, at any time. Chapter 3 describes the record line by line.

The whole program

Put together, an embedding is load, plan, execute, verify. This follows examples/pure_consumer.rs, which does the same for the SDK's fixture, an identity value: entry that returns its Text argument:

rust
use captain_sdk::{
    execute, verify_run_record, Argument, CancellationToken, ExecutionLimits, ExecutionOutcome,
    InputValue, LoadLimits, OutputValue, VerificationDisposition, VerifiedProgram,
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let bytes = include_bytes!("../fixtures/identity.capb");
    let program = VerifiedProgram::load(bytes, LoadLimits::default())?;
    let plan = program.plan_pure(
        "identity value:",
        vec![Argument {
            name: "value".into(),
            value: InputValue::Text(b"hello".to_vec()),
        }],
        ExecutionLimits::default(),
    )?;
    let execution = execute(&plan, &CancellationToken::new());
    match execution.outcome {
        ExecutionOutcome::Completed {
            value: OutputValue::Text(value),
            result_identity,
        } => {
            println!("result={}", String::from_utf8(value)?);
            println!("result_identity={result_identity}");
        }
        outcome => return Err(format!("unexpected outcome: {outcome:?}").into()),
    }
    let verified = verify_run_record(&plan, &execution.run_record)?;
    if verified.disposition != VerificationDisposition::Reexecuted {
        return Err("completed record was not independently re-executed".into());
    }
    println!("artifact_identity={}", plan.artifact_id());
    println!("plan_identity={}", plan.identity());
    println!("run_record_identity={}", verified.identity);
    Ok(())
}

The fixture's source is fixtures/identity.capt. As a module of its own, it is:

Captain
module Captain::SdkFixture.

export identity value: Text -> Text [
  ret value.
].