Metering

A host that runs scripts for its customers needs to know what each customer used. ztcl counts the use of each thread and child interpreter in a meter: compute units, wall time, CPU time, memory, and I/O. ztcl::meter has the commands.

Bill by compute units

A compute unit is one command, one loop pass, or the work on 4,096 bytes of data (Limits). The count depends only on the script and its inputs:

CPU seconds change with the machine, the load, the cache, and the JIT. A bill in compute units is the same each time the customer runs the same job, and a customer can check it: the customer runs the script on their own machine and counts the same units.

The meter also counts wall time, CPU time, and memory. Use them for a second price, such as a price for memory over time (mem_byte_ms), or to check the cost of a customer against the cost of the machine.

A hosting example

The service runs each job of a customer in a thread of the level process. Each tenant has a meter with a budget for the month. After each job, the service appends a signed record of the meter of the tenant to a log.

# The embedder sets Interp.meter_key, so the script signs with -sign.
proc run_job {tenant script} {
    if {$tenant ni [ztcl::meter list]} {
        ztcl::meter create $tenant -tenant $tenant -budget 50000000
    }
    set t [thread::create -joinable -isolation process -meter $tenant -compute 5000000 $script]
    thread::join $t
    set log [open usage.jsonl a]
    puts $log [ztcl::meter record $tenant -script $script -sign]
    close $log
    return [dict get [ztcl::meter get $tenant] left]
}

# At the start of each month, after the last record of the month:
proc new_month {} {
    foreach m [ztcl::meter list] {ztcl::meter reset $m}
}

The parts:

What a customer can check

A record has the SHA-256 of the script, the units, and the signature of the host. The customer can:

The signature shows that the host made the record. It does not show that the host ran the script with the counts of the record: a host can sign any counts. On attested hardware (ztcl#180) a record can come with the attestation of the code that counted. This version has no such record.

Trust at each level

Level Where the counts come from
interp The interpreter of the thread, in the process of the host.
process The child reports its compute units, CPU time, memory, and I/O at its end. The parent measures the wall time, the start time, and the messages and bytes of the transport, and reads the counts of the system: the cgroup on Linux, the Job Object on Windows, and wait4 on macOS.
A child interpreter (interp create -meter) The child, in the process of the host.

A child process with a bad C package can report wrong counts. The counts of the system come from the kernel, so bill such work by process os_cpu_us and process os_mem_peak, or check the units of the child against them.

Not in this version