THUNDER-CLIENTS(3)

Reference index

NAME

thunder-clients — client libraries for reading and writing Thunder records

SYNOPSIS

A checkpoint records the step an agent should run next. Given an open Python connection db, these calls write the checkpoint and read it back.

key = b"agents/run-007/rev-003"
db.set(key, payload)
stored = db.get(key)

CONNECTION

Start the server and check the connection. Run the examples from the release-kit directory containing compose.yaml.

Server address
The default local server listens on 127.0.0.1:7380. The client connects there first and learns which shards each port serves.
Certificate
The client uses docker/tls/ca.crt to verify the server’s certificate. Pass the contents of that file to the client. The default local certificate uses the server name localhost.
Checkpoint file
Save checkpoint.json next to compose.yaml. In this file, the agent has finished extraction and normalization. Its next step is validate_batch.

CLIENTS

Each example stores checkpoint.json under the key agents/run-007/rev-003, then reads it back and checks that the bytes match. Choose your language for the installation command and code.

Pythonthunderstrike

Install the Python package. Save the example as checkpoint.py and run python checkpoint.py.

python -m pip install thunderstrike
import json
from pathlib import Path
from thunderstrike import Thunderstrike

key = b"agents/run-007/rev-003"
payload = Path("checkpoint.json").read_bytes()
ca = Path("docker/tls/ca.crt").read_text()

with Thunderstrike("127.0.0.1:7380", tls_server_name="localhost",
                   tls_ca_pem=ca) as db:
    db.set(key, payload)
    stored = db.get(key)
    if stored != payload:
        raise ValueError("checkpoint mismatch")
    print(json.loads(stored)["next_step"])

Expected output validate_batch

Node.js@shortsqueeze/thunderstrike

Save the example as checkpoint.mjs. After installing the package, run node checkpoint.mjs.

npm install @shortsqueeze/thunderstrike
import { readFileSync } from "node:fs";
import { ThunderstrikeClient } from "@shortsqueeze/thunderstrike";

const key = Buffer.from("agents/run-007/rev-003");
const payload = readFileSync("checkpoint.json");
const db = await ThunderstrikeClient.connect({
  endpoints: ["127.0.0.1:7380"],
  tlsServerName: "localhost",
  tlsCaPem: readFileSync("docker/tls/ca.crt"),
});

try {
  await db.set(key, payload);
  const stored = await db.get(key);
  if (!stored?.equals(payload)) throw Error("checkpoint mismatch");
  console.log(JSON.parse(stored.toString("utf8")).next_step);
} finally {
  db.close();
}

Expected output validate_batch

Gothunderstrike-client/go

Use a Go module with cgo enabled. Add the client dependency and save the example as main.go. Run go run main.go from the release-kit directory.

go get github.com/TheManhattanProject/thunderstrike-client/go@v0.1.3
package main

import (
    "bytes"
    "fmt"
    "log"
    "os"

    "github.com/TheManhattanProject/thunderstrike-client/go/thunderstrike"
)

func main() {
    ca, err := os.ReadFile("docker/tls/ca.crt")
    if err != nil { log.Fatal(err) }
    payload, err := os.ReadFile("checkpoint.json")
    if err != nil { log.Fatal(err) }
    db, err := thunderstrike.Connect(thunderstrike.Config{
        Endpoints: []string{"127.0.0.1:7380"},
        TLSServerName: "localhost", TLSCAPem: ca,
    })
    if err != nil { log.Fatal(err) }
    defer db.Close()

    key := []byte("agents/run-007/rev-003")
    if err := db.Set(key, payload); err != nil { log.Fatal(err) }
    stored, found, err := db.Get(key)
    if err != nil { log.Fatal(err) }
    if !found || !bytes.Equal(stored, payload) {
        log.Fatal("checkpoint mismatch")
    }
    fmt.Println("bytes match")
}

Expected output bytes match

Rustthunderstrike

Add the crate to a Cargo binary project and put the example in src/main.rs. Build the binary, then run it from the release-kit directory.

cargo add thunderstrike
use std::{error::Error, fs};
use thunderstrike::{Client, Config};

fn main() -> Result<(), Box<dyn Error>> {
    let ca = fs::read("docker/tls/ca.crt")?;
    let payload = fs::read("checkpoint.json")?;
    let config = Config::new("127.0.0.1:7380").tls("localhost", ca);
    let db = Client::connect(&config)?;
    let key = b"agents/run-007/rev-003";

    db.set(key, &payload)?;
    let stored = db.get(key)?;
    if stored.as_deref() != Some(payload.as_slice()) {
        return Err("checkpoint mismatch".into());
    }
    println!("bytes match");
    Ok(())
}

Expected output bytes match

.NETThunderstrike

Add the package to a C# console project and save the example in Program.cs. Run the compiled program from the release-kit directory.

dotnet add package Thunderstrike
using System;
using System.IO;
using System.Linq;
using Thunderstrike;

using var db = new ThunderstrikeClient(new ThunderstrikeOptions {
    Endpoints = { "127.0.0.1:7380" },
    TlsServerName = "localhost",
    TlsCaPem = File.ReadAllBytes("docker/tls/ca.crt"),
});
var key = "agents/run-007/rev-003"u8.ToArray();
var payload = File.ReadAllBytes("checkpoint.json");
db.Set(key, payload);
var stored = db.Get(key);
if (stored is null || !stored.SequenceEqual(payload))
    throw new InvalidDataException("checkpoint mismatch");
Console.WriteLine("bytes match");

Expected output bytes match

Javathunderstrike-client

Use JDK 22 or later. Add the dependency to a Gradle project that uses Maven Central and save the example as Checkpoint.java. Start the JVM with --enable-native-access=ALL-UNNAMED.

implementation("io.github.maverick-ai:thunderstrike-client:0.1.3")
import dev.thunderstrike.client.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.Arrays;

public class Checkpoint {
    public static void main(String[] args) throws Exception {
        var ca = Files.readAllBytes(Path.of("docker/tls/ca.crt"));
        var options = new ThunderstrikeOptions()
                .endpoint("127.0.0.1:7380").tls("localhost", ca);
        try (var db = ThunderstrikeClient.connect(options)) {
            var key = "agents/run-007/rev-003"
                    .getBytes(StandardCharsets.UTF_8);
            var payload = Files.readAllBytes(Path.of("checkpoint.json"));
            db.set(key, payload);
            if (!Arrays.equals(payload, db.get(key)))
                throw new IllegalStateException("checkpoint mismatch");
            System.out.println("bytes match");
        }
    }
}

Expected output bytes match

PHPthunderstrike-client

Install the package and native library in the release-kit directory. Enable the PHP FFI extension and save the example as checkpoint.php. Run php -d ffi.enable=true checkpoint.php.

composer require themanhattanproject/thunderstrike-client
vendor/bin/thunderstrike-install
<?php
require __DIR__ . '/vendor/autoload.php';

use Thunderstrike\{Client, Options};

$ca = file_get_contents('docker/tls/ca.crt');
$payload = file_get_contents('checkpoint.json');
if ($ca === false || $payload === false) {
    throw new RuntimeException('could not read CA or checkpoint');
}
$db = Client::connect(
    (new Options())->endpoint('127.0.0.1:7380')->tls('localhost', $ca)
);
$key = 'agents/run-007/rev-003';
$db->set($key, $payload);
if ($db->get($key) !== $payload) {
    throw new RuntimeException('checkpoint mismatch');
}
echo "bytes match\n";

Expected output bytes match

Cthunderstrike_client.h

Download the native library and C header for your platform. Include the header and link against the library. Pass the CA certificate and checkpoint file to check_record as byte buffers with their lengths. It returns zero when the stored bytes match.

#include <stdint.h>
#include <string.h>
#include "thunderstrike_client.h"

int check_record(const uint8_t *ca, size_t ca_len,
                 const uint8_t *payload, size_t len) {
    const uint8_t key[] = "agents/run-007/rev-003";
    const size_t klen = sizeof(key) - 1;
    thunderstrike_config *cfg = thunderstrike_config_new();
    thunderstrike_client *db = NULL;
    thunderstrike_buf result = {0};
    if (!cfg) return 1;

    int rc = thunderstrike_config_add_endpoint(cfg, "127.0.0.1:7380");
    if (rc == THUNDERSTRIKE_OK)
        rc = thunderstrike_config_set_tls(cfg, "localhost", ca, ca_len);
    if (rc == THUNDERSTRIKE_OK) rc = thunderstrike_connect(cfg, &db);
    thunderstrike_config_free(cfg);
    if (rc != THUNDERSTRIKE_OK) return 1;

    rc = thunderstrike_set(db, key, klen, payload, len);
    if (rc == THUNDERSTRIKE_OK)
        rc = thunderstrike_get(db, key, klen, &result);
    int match = rc == THUNDERSTRIKE_OK && result.len == len &&
                (len == 0 || memcmp(result.data, payload, len) == 0);
    thunderstrike_buf_free(&result);
    thunderstrike_client_free(db);
    return match ? 0 : 1;
}
C++thunderstrike.hpp

Compile with C++17 or later. Use the C++ wrapper with its matching native library and C header. Pass the CA certificate text and the checkpoint bytes to check_record. The function returns true on a match. Client errors raise an exception.

#include <string_view>
#include "thunderstrike.hpp"

bool check_record(std::string_view ca, std::string_view payload) {
    thunderstrike::options options;
    options.endpoint("127.0.0.1:7380").tls("localhost", ca);
    auto db = thunderstrike::client::connect(options);
    constexpr std::string_view key = "agents/run-007/rev-003";

    db.set(key, payload);
    auto stored = db.get(key);
    return stored && stored->view() == payload;
}

All nine libraries use the same native client code to discover the server’s ports and pool connections. The client repository documents the types and methods for each language.

OPERATIONS

The signatures below use Python. Other languages represent keys and values with their own byte types.

db.set(key, payload)
Write the bytes under the given key. Thunder confirms the write after its journal record reaches disk.
db.get(key)
Return the stored bytes. An absent key gives None. A stored empty value gives b"".
db.mget(keys)
Read several keys in one call. Results follow the input order. A missing key contributes None at its position.
db.mset(items)
Write several records from a mapping or a sequence of key/value pairs. For example, a prompt and a test case can have separate keys.
db.append(key, bytes)
Add bytes to the end of a value and return its new length in bytes. When appending a message to a newline-delimited JSON transcript, include the newline.
db.exists(key) / db.delete(key)
Check for a key or remove it. Deleting an existing key returns True.
prompt, source = db.mget([
    b"prompts/support/v3", b"sources/thunder-docs/v1"
])

VERIFICATION

Python and Node.js decode the saved JSON and print validate_batch. Go, Rust, .NET, Java, and PHP print bytes match. C reports a match with a zero return value and C++ with true.

A write can reach disk even if the client times out waiting for the reply. Before retrying a checkpoint write, read the same revision key and compare its value with the bytes you intended to save.

SEE ALSO