Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Delegated Tasks

A "delegated task" is any nanotransaction whose main functionality is not implemented within magpie. In these cases, a "wrapping" nanotransaction orchestrates the execution of an external action (e.g. launching an external binary), and also establishes downstream tasks that depend on this delegated action. These tasks could, for instance, consume the output of the delegated task or monitor its status, notifying other components of a failure.

Delegated tasks are also called "async tasks" because, as we explain below, we do not impose the same execution requirements on them like we would on regular nanotransactions. Since they correspond to actions of external systems, we don't try to impose the nanotransaction run-to-completion regime nor do we expect them to finish in a strongly synchronous way. Synchronous nanotransactions establish a partial task graph for interacting with the external components, and then asynchronous tasks are responsible for reacting to changes of interest to the programmer and advancing an epic.

Implementation Details

To integrate external effects into epics, we introduce a new macro to declare a nanotransaction as async, nandoize_lib_async, and a set of new macros to express that a spawned nanotransaction should be executed by a worker's async thread pool as opposed to a regular executor. These macros also enable us to establish control and data dependencies between synchronous and asynchronous tasks, and are basically the existing nando_{spawn,yield} macros with an _async suffix.

In addition to these macros, we have a new library called action (code), which provides helpful utilities for orchestrating external actions (e.g. launching an external binary and awaiting its completion). For more on the facilities it provides, check out the examples.

Restrictions on async tasks

We don't do effect tracking for async tasks, so they are not allowed to receive mutable arguments, they can only read pre-existing objects. They cannot allocate new objects. They also cannot spawn new tasks, although this restriction could be relaxed in the future to allow for different kinds of patterns (e.g. recurring tasks on a timer).

Examples

Launch a Python Program

For this example, we want to launch the below python program from magpie, and read its output value. You can imagine that this program will perform some long-running computation and produce a value that we want to consume downstream in magpie and further process in an epic.

import random
import time

time.sleep(5)
random_integer = random.randint(1, 100)
print(random_integer)

The top-level nanotransaction that launches this program is shown below.

#![allow(unused)]
fn main() {
#[repr(C)]
#[derive(PersistableDeriveLib)]
pub struct SpawnConfig {
    // Program to launch.
    pub cmd: PString,
    // Arguments to pass to the program.
    pub args: PVec<PString>,

    // Local paths to redirect stdout and stderr.
    // If not set, output will be sent to /dev/null.
    pub stdout_file: Option<PString>,
    pub stderr_file: Option<PString>,
}


#[nandoize_lib]
pub fn call_rand() -> IPtr {
    let object_tracker = object_tracker_tls::get_local_object_tracker_instance();
    let spawn_config = allocate_and_init!(object_tracker, SpawnConfig);
    let spawn_config_iptr: IPtr = spawn_config.iptr_of();
    let spawn_config_data = spawn_config.read_into_mut::<SpawnConfig>(None).unwrap();

    let mut working_dir = env::current_dir().expect("Failed to get working directory");
    working_dir.push("../applications/external-invocations/external-programs/rand-print.py");

    spawn_config_data.set_cmd("python3");
    spawn_config_data.set_args(&vec![&working_dir.to_str().unwrap()]);

    // Redirect stdout so that we can read later
    spawn_config_data.set_stdout("/tmp/rand-print-output");

    let counter_iptr: IPtr = init_counter();
    let spawn_result = nando_spawn!("action::spawn_finite", spawn_config_iptr);
    nando_yield!(
        "external_invocations::set_counter_from_output",
        counter_iptr,
        spawn_config_iptr,
        spawn_result
    );

    register_initial!(spawn_config, object_tracker);
    spawn_config_iptr
}
}

action::spawn_finite() is a special nanotransaction that will launch the binary specified in the passed SpawnConfig with the appropriate configuration, and then will spawn an async nanotransaction to await the spawned process' exit before signaling downstream nanotransactions. The waiting is performed by an async task, await_process_completion, that performs a waitpid() syscall, and blocks until it receives an update by the OS about the target process.

#![allow(unused)]
fn main() {
#[nandoize_lib]
pub fn spawn_finite(spawn_config: &SpawnConfig) {
    let spawn_config_iptr = iptr_of_ref!(spawn_config);
    // spawn_internal simply uses Rust's `std::process` library to spawn a child process, captures
    // its PID, and returns a reference to an object containing information about the spawned
    // process.
    let process_object = nando_spawn!("action::spawn_internal", spawn_config_iptr);
    let exit_code = nando_yield_async!("action::await_process_completion", process_object.clone());
    nando_yield!(
        "action::update_process_exit_code",
        process_object,
        exit_code
    );
}

#[nandoize_lib_async]
pub fn await_process_completion(spawned_target: &SpawnedTarget) -> i32 {
    use nix::sys as nix_sys;
    let child: i32 = spawned_target
        .pid
        .try_into()
        .expect("pid conversion failed");
    match nix_sys::wait::waitpid(nix::unistd::Pid::from_raw(child), None) {
        Ok(nix_sys::wait::WaitStatus::Exited(_pid, code)) => code,
        r @ _ => panic!("unhandled waitpid result: {:#?}", r),
    }
}
}

Once the spawned process exits, we notify the spawned external_invocations::set_counter_from_output() nanotransaction to execute. It proceeds to read the file that the spawned process' output was redirected to, and tries to parse the numeric value from the output.

#![allow(unused)]
fn main() {
#[nandoize_lib]
pub fn set_counter_from_output(
    counter: &mut Counter,
    spawn_config: &action::SpawnConfig,
    spawned_target: &action::SpawnedTarget,
) {
    // Application-level check: we expect the called binary to successfully exit. If that did not
    // happen, we cannot proceed, and we abort this epic.
    let SpawnedTargetStatus::Exited(0) = spawned_target.status else {
        panic!(
            "Process exited with {:?}, cannot read output",
            spawned_target.status
        );
    };

    let stdout_file_string: String = spawn_config.stdout_file.as_ref().unwrap().into();
    let line_reader: BufReader = { /* open file for reading and get reader */ };
    for line in line_reader.lines() {
        let Ok(line) = line else {
            break;
        };
        let elem: usize = line
            .parse()
            .expect(&format!("failed to parse numeric value: {}", line));
        counter.set_count(elem);
        break;
    }
}
}

The resulting physical task graph is shown below.

Spawn Rand Plan

Handling faults

Since we are embedding external programs into the existing task graphs, we leverage the existing infrastructure for signaling errors. We have infrastructure-level errors (e.g. there was a problem while trying to spawn a child process because a path is misconfigured) but also application-level errors (e.g. a process did not exit successfully).

For unrecoverable errors, the infrastructure (i.e. the action library) uses panic!() and associated methods. For potentially recoverable errors, the user is free to either direct control flow appropriately or to also treat them as unrecoverable, as we do for instance if we detect a non-zero exit code in set_counter_from_output().

By default we treat external tasks as non-effectful. It is up to the application programmer to orchestrate tasks for the cleanup of intermediate state or any effects that they do not want to persist as part of their error handling logic in their programs (e.g. deleting temporary files).

Launch a daemon-like program

Some external programs are not finite in duration. For instance, we would like to be able to launch and manage a container through magpie, or to manage long-running database instances. For this example, we will manage a Redis instance, and also proxy requests to it. The whole code for this example can be found here.

The following nanotransaction launches a local instance of Redis after customizing its configuration file to attach to the user-specified port.

#![allow(unused)]
fn main() {
// Contains information about the launched redis instance, like the final paths of associated files
// as well as a reference to the spawned instance returned by `action`, containing the process PID
// etc.
pub struct RedisInstanceConfig {
    pub(crate) port: usize,
    pub(crate) config_path: PString,
    pub(crate) log_file_path: PString,
    pub(crate) db_file_path: PString,
    pub(crate) spawned_instance: Option<TypedIPtr<action::SpawnedTarget>>,
}

#[nandoize_lib]
pub fn run_redis(redis_server_path: String, port: usize) -> IPtr {
    let object_tracker = object_tracker_tls::get_local_object_tracker_instance();
    let spawn_config = allocate_and_init!(object_tracker, action::SpawnConfig);
    let spawn_config_iptr: IPtr = spawn_config.iptr_of();
    let spawn_config_data = spawn_config
        .read_into_mut::<action::SpawnConfig>(None)
        .unwrap();

    let mut config_template_path = env::current_dir().expect("Failed to get working directory");
    config_template_path.push("../applications/external-invocations/resources/redis.conf.template");
    let mut config_path = PathBuf::from("/tmp");
    config_path.push(&format!("redis_{}.conf", port));
    fs::copy(config_template_path, &config_path).expect(&format!(
        "Failed to copy config template to {:?}",
        config_path
    ));
    let log_path = format!("/tmp/redis_log_{}", port);
    // truncate existing log file
    let _file = fs::OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open(&log_path)
        .expect("Failed to open log file and truncate to 0");

    // specify database dump file
    let db_path = format!("dump_{}.rdb", port);

    // update copy of config template with fixed details and paths
    update_config(&config_path, port, &log_path, &db_path);

    let config_path: String = config_path.to_string_lossy().into_owned();
    spawn_config_data.set_cmd(&format!("{redis_server_path}/redis-server"));
    spawn_config_data.set_args(&vec![&config_path, "--daemonize", "yes"]);

    let redis_config = allocate_and_init!(object_tracker, RedisInstanceConfig);
    let redis_config_iptr: IPtr = redis_config.iptr_of();
    let redis_config_data = redis_config
        .read_into_mut::<RedisInstanceConfig>(None)
        .unwrap();
    redis_config_data.port = port;
    redis_config_data.config_path.from(&config_path);
    redis_config_data.log_file_path.from(&log_path);
    redis_config_data.db_file_path.from(&db_path);

    // Spawn redis daemonized process
    let spawned_process = nando_spawn!("action::spawn_long_running", spawn_config_iptr);
    // Validate that redis started up successfully.
    let health_check = nando_yield_async!(
        "external_invocations::check_redis_health",
        redis_config_iptr,
        spawned_process.clone()
    );

    // If redis started up successfully, update config object with reference to spawned process
    // information returned by `spawn_long_running()`.
    nando_yield!(
        "external_invocations::redis_post_startup",
        redis_config_iptr,
        spawned_process,
        health_check
    );

    register_initial!(spawn_config, object_tracker);
    register_initial!(redis_config, object_tracker);

    redis_config_iptr
}
}

run_redis() invokes action::spawn_long_running which performs the same work as spawn_finite() but does not spawn action::await_process_completion(). Instead, it immediately returns the process object corresponding to the launched external process and delegates responsibility for managing the external process to the programmer. Here, we implement an async nanotransaction, check_redis_health(), that checks the Redis logs of the spawned instance until a successful launch message is detected, or the preconfigured number of unsuccessful checks elapses, at which point the epic is aborted.

This async task also performs something unthinkable for traditional nanotransactions: it sleeps between iterations. If a regular nanotransaction were to sleep, it would block its executor thread and render it unusable. Since this is running inside an async executor, sleeping simply parks the task until it is ready to be resumed, and the async worker can switch to a different task that can make progress instead.

#![allow(unused)]
fn main() {
#[nandoize_lib_async]
pub fn check_redis_health(
    redis_instance_config: &RedisInstanceConfig,
    spawned_target: &action::SpawnedTarget,
) -> i32 {
    use std::thread;
    use std::time::Duration;
    let successful_startup_msg = "Ready to accept connections tcp";

    let stdout_file_string: String = (&redis_instance_config.log_file_path).into();
    for _ in 1..5 {
        if !fs::exists(path).expect("exists err") {
            thread::sleep(Duration::from_secs(1));
            continue;
        }

        let stdout_file = /* open file */;
        let mut line_reader = BufReader::new(stdout_file);
        // skip over already read output.
        if last_idx > 0 {
            line_reader
                .seek_relative(last_idx)
                .expect(&format!("failed to advance to idx {}", last_idx));
        }

        for line in line_reader.lines() {
            let Ok(line) = line else {
                break;
            };

            if line.contains(successful_startup_msg) {
                return 0;
            }
            last_idx += 1;
        }

        thread::sleep(Duration::from_secs(1));
    }

    panic!("Redis failed to start up, or did not start up in time");
}
}

Proxying Requests

If Redis launches successfully, the run_redis() epic retuns a reference to a RedisInstanceConfig object that other code can use to refer to the spawned instance. This instance reference can be used to facilitate proxying of requests to this Redis instance.

We can extend our Redis library to mediate SET/GET requests to a running, managed Redis instance. Below we show the code for SET.

#![allow(unused)]
fn main() {
#[nandoize_lib]
pub fn put(redis_instance_config: &RedisInstanceConfig, key: String, value: u32) {
    let port = redis_instance_config.port;
    nando_spawn_async!("external_invocations::put_submit_command", port, key, value);
}

#[nandoize_lib_async]
pub fn put_submit_command(redis_port: usize, key: String, value: u32) {
    // Client connection to the running Redis instance.
    let mut stream = TcpStream::connect(format!("127.0.0.1:{redis_port}"))
        .expect("failed to connect to redis instance");

    // Encode the request.
    let command = vec![
        resp::Value::Bulk("SET".to_string()),
        resp::Value::Bulk(key),
        resp::Value::Bulk(value.to_string()),
    ];
    let command_array = resp::Value::Array(command);
    let encoded_command_array = resp::encode(&command_array);
    let mut resp_stream = vec![0; 256];

    // Submit the request.
    stream
        .write(&encoded_command_array)
        .expect("failed to write shutdown command");
    // Read the response.
    let response_size = stream
        .read(&mut resp_stream)
        .expect("failed to read response");

    let response = {
        let mut decoder = resp::Decoder::new(BufReader::new(resp_stream.as_slice()));
        decoder.decode().expect("failed to decode SET response")
    };

    // Check if command was executed successfully.
    match response {
        resp::Value::Error(s) => panic!("SET failed: {s}"),
        _ => {}
    }
}
}

The top-level put() nanotransaction simply extracts the corresponding instance's port from the specified RedisInstanceConfig (the one returned by run_redis()) and invokes the async nanotransaction put_submit_command() which is responsible for i) encoding the put command into Redis' binary wire format ii) submitting it to the running instance and iii) inspecting the response it receives.

You've added latency, and for what?

Interacting with external systems through delegated tasks leads to higher latency compared to implementing all functionality inside magpie. On the flipside, magpie's existing facilities around auto-paralellization and distribution allow us to leverage existing single-node systems with little effort, while enhancing them with i) auto-parallelization ii) transparent distribution and iii) enhanced durability.

In this Redis example, associating a running database instance with an object means that we can cheaply parallelize KVS queries by spawning a set of instances and partitioning keys over them (basically the exact setup we used during our paper KVS implementation), leveraging magpie's executor object ownership scheme to execute parallel queries. Similarly, we can distribute these "bucket" objects across available workers and achieve a setup similar to Redis Cluster, with the added benefits of adaptive placement for co-accessed data.

Enhancing the durability of existing grey-box components is also possible through an application library. For instance, before submitting the SET request to the local Redis instance, we could append it to an operation log, which we could also replicate. Combined with Redis' snapshotting facilities like BGSAVE and LASTSAVE, we could enhance Redis with a durability mechanism with incremental snapshots and replay.