Skip to content

lab: the nested tax on a running workspace's I/O, and density on metal, for the metal-or-nested cost model #563

Done

Description

@aledbf

Context. A model of when spin should run workspaces on EC2 bare metal rather than nested instances (published page: https://claude.ai/artifact/K6wMFnb6ow11LBBax3Ywyf, for the blog post aledbf/blog#3) has two inputs nobody has measured. The decision is spin's infrastructure's (spin-stack/spin-terraform-aws, spin-stack/spin). The measurement is the machine's, because it is the machine's I/O path that crosses two hypervisors.

What is measured (v20261122.06, spin's shape, 20 boots each): the cold first login is 418 ms nested (c8id.4xlarge, lab 45074465204) against 363 on metal (c8i.metal-48xl, lab 45074680619). The gap sits in the kernel's boot and before it, where VM exits cluster. systemd's CPU-bound stretch runs at the same speed on both. A restore is 84 against 81 ms. What a running workspace pays for nesting is not measured, and neither is how many workspaces a metal host carries (#273 measured density nested only, idle, up to 16).

Why it decides something. In us-east-1 a metal-48xl costs exactly six 8xlarges on demand. On spot (30-day median, 2026-10-23 to 2026-11-22) c8id.metal-48xl is $2.73/h against $0.49 for c8id.8xlarge, 5.5 of them. With the website's 8 workspaces per runner, a metal host must hold 44 of its 48 to cost no more per workspace (spot), and all 48 on demand. The model takes the nested tax as extra host CPU per workspace. That tax moves the break-even from 44 to 39 at 10% and to 33 at 30%, and on demand it is metal's only gain. Density on metal decides whether 44 is reachable at all.

1. The I/O tax, nested against metal

Arms. One release, one image, spin's shape (1 vCPU, 2048 MiB plugged, login as spin), and the same storage type under the overlay on both hosts. Today they differ: the bench's scratch is local NVMe (/dev/md0) and bench-metal's is its EBS root (/dev/root), and restore's read-ahead took 68-81 ms against 909-1185 ms (labs 45074649532, 45075096303). So, either of these, and say which on every table:

  • local NVMe on both: bench (c8id.4xlarge) against a metal type with an instance store (c8id.metal-48xl). That needs a fleet in spin-stack/ci, as bench-metal is c8i.metal-48xl.
  • EBS gp3 on both: bench on an EBS scratch volume against bench-metal on an EBS scratch volume, each provisioned with the same size, IOPS and throughput, so the volume is not the limit.

Measure each with 1 vCPU and with 4, since the tax is per exit and a busier guest exits more.

Probes needed (in internal/lab, one each, so the next person runs the same thing):

  • io: fio inside the guest against its own disk (the overlay, as spin serves it) and against a disk attached after boot, as spin attaches extensions. Jobs: 4 KiB random read and write at QD1 and QD32, 1 MiB sequential read and write, each 30 s after a 5 s ramp. Report IOPS, MiB/s, p50/p99 completion latency, and the guest's and QEMU's CPU time per GiB moved. The CPU per GiB is the number the model needs. Throughput alone can tie while one side burns twice the CPU.
  • build: a fixed, cached workload a workspace actually runs, timed from start to exit: a docker build of a pinned Dockerfile with its base layers on the disk, or a Go build of a pinned tree if the image carries no Docker. Report wall time and the host CPU time QEMU's threads used (/proc/PID/task/*/schedstat, as run-delay reads it).
  • A network row, if the probes can drive one cheaply: iperf3 from the guest to the host over the workspace's network path, reporting CPU per GiB as above.

Rows. nested and metal × the storage arm × 1 and 4 vCPUs, 20 runs a cell, interleaved within a host. Nested and metal are two runs, so their difference is a lead sized against the bench's ~8 ms run-to-run drift for latency, and against each cell's own spread for throughput and CPU.

What it gives the model. The tax is (host CPU per unit of work, nested) ÷ (the same, metal) − 1, for each workload. The model's dial is that number.

2. Density on metal

Arms. density (#273, internal/lab/density.go) as it stands, on bench-metal: crowds of 0 16 32 48 64 96, with load=idle and with load=cpu, spin's shape with 2048 MiB plugged. And the same crowds scaled to the bench's 16 vCPUs (0 4 8 16 24), load=cpu, which #273 has not run.

Read. The largest crowd whose first login p95 stays within 25% of the empty host, per host and load, and the crowd's own boot-and-login time. Add the io probe as a load (load=io, every crowd member running the 4 KiB random-write job) if the first round shows CPU is not the limit, since a metal host shares one disk and one NIC across six times as many workspaces.

What would change the answer

  • The tax under ~5% for the build and fio's random 4 KiB jobs: nesting costs a running workspace nothing the model can see, metal pays only on spot and only above ~44 of 48 workspaces (c family), and spin stays nested.
  • The tax at 10% or more: metal's break-even falls under ~40 of 48 (80% full) on spot, and on demand metal wins at any fill above six times what a nested host holds after the tax (42 of 48 at 10%). Then a metal runner type is worth adding to spin-terraform-aws for fleets that keep it full.
  • Metal density under ~44 workspaces at 4 host vCPUs each (p95 past the 25% line, CPU-bound): metal never reaches break-even at the website's density, whatever the tax.
  • Storage held equal moves restore or the build by more than the noise: the storage choice (instance store against gp3) is a variable of its own in the model, and the d-variant's 18% premium is priced against that number.

Each result lands as a row in docs/boot-time.md and a dated entry in docs/log.md with its run, and the model's dial is set from it.

🤖 Generated with Claude Code

Activity

  1. aledbf commented on Nov 22, 2026

    @aledbf
    MemberAuthor

    The candidate search, us-west-2 (2026-11-22). The first model compared c8id/c8i in us-east-1 only. The model now ranks 118 us-west-2 types: every type whose processor reports nested-virtualization in the families and sizes a fleet of 8-48 workspaces runs on, and every x86 metal type from the 6th generation on, minus GPU hosts and the x families. Page: https://claude.ai/artifact/K6wMFnb6ow11LBBax3Ywyf. us-west-2 is also where spin-stack/ci's bench and bench-metal fleets run, so the two measured latencies are from the same region.

    Inputs. On demand from AWS's public price list (published 2026-11-21). Spot from DescribeSpotPriceHistory, 2026-10-23 to 2026-11-22, time-weighted over zones. Interruption bands from the Spot Instance Advisor. GetSpotPlacementScores for the metal types only, because the API refused new configurations after 50 in a day. gp3 costs $0.08/GB-mo, $0.005/IOPS-mo and $0.04/MiB/s-mo in us-west-2, the same as us-east-1. Everything was read-only.

    Nested candidates. The API and the EC2 user guide agree: C7i, M7i, R7i, C8i, M8i, R8i, the 8th-gen d variants, I7i, I7ie, R7iz, X8i and the flex types. No AMD type supports nested virtualization. So every AMD option is a metal option.

    Ranked, spin's website shape (4 host vCPUs, 2 GiB), spot p50, $/workspace-hour. Today's runner is c8id.8xlarge at $0.0763.

    Fleet 1st 2nd 3rd Best nested
    8 c7i.4xlarge ×2, $0.0677 c8id.8xlarge ×1, $0.0763 c7i.8xlarge, $0.0786 (1st)
    48 c8in.metal-48xl ×1, $0.0485 m8idn.metal-48xl, $0.0495 c8i.metal-48xl, $0.0538 c8id.24xlarge, $0.0640
    96 c8in.metal-96xl ×1, $0.0439 c6in.metal ×3, $0.0469 c8in.metal-48xl ×2, $0.0485 c8id.24xlarge, $0.0640
    480 c8in.metal-96xl ×5, $0.0439 c6in.metal ×15, $0.0469 c8in.metal-48xl ×10, $0.0485 c8id.24xlarge, $0.0640

    With the filter set to interruption under 5%, c8i.metal-48xl ranks first at 48, 96 and 480 ($0.0538, 29% under today's runner), and at 8 the first is c8i.4xlarge ×2 ($0.0838).

    On demand at 4 vCPUs, nested c7i.8xlarge wins at 8 ($0.1822). From 48 up the first is c6a.metal ($0.1584), an AMD host that nested cannot use. With 1 vCPU or less per workspace, nested d types (c8id.12xlarge and 24xlarge, m8id) win up to 96. Metal first wins at 480 (m8idn.metal-48xl, $0.0148 against $0.0160). At 0.5 vCPU, a 30 GiB cache per workspace on the instance store is what limits the d types.

    What moved from the first model.

    • c8i.metal-48xl's break-even against today's runner drops from about 42 of 48 to 33 of 48 (spot, no tax). The metal host costs the same in both regions ($2.32 vs $2.33). The nested reference costs more in us-west-2 ($0.61 vs $0.49 for c8id.8xlarge). c8id.metal-48xl needs 42 of 48 (44 in us-east-1).
    • The cheapest metal on spot is outside the c8 family. It is the network-optimized types (c8in, m8idn) and the 6th generation (c6in, m6in, c6a). Their low price looks like low demand, not capacity. The advisor has no data for c8in or m8idn. Every metal type scored 1-3 of 10 for placement, asked for enough hosts to hold 96 workspaces. That matches docs/log.md's 11-13 entry, where bench-metal spot failed UnfulfillableCapacity in every zone.
    • Small metal sizes (c7i/m7i/r7i.metal-24xl, c8a/m8a/r8a.metal-24xl, m8azn.metal-12xl) shorten the fleet's step. c7i.metal-24xl breaks even at 19 of 24. At 8 workspaces nested still wins.
    • AMD is unmeasured. AMD 7th and 8th gen give each vCPU a whole core (DefaultThreadsPerCore 1), so the page has an AMD vCPU speed dial, flagged unmeasured, at 1.0. At 1.0, AMD metal is never first on spot. On demand, c6a.metal is first from 48 up.

    The options worth measuring next.

    1. c8i.metal-48xl density and I/O tax (the plan above, on the existing bench-metal fleet). It is the only metal type with both a measured boot and an interruption band under 5%. Changes the answer if 33 or more workspaces fit within the 25% p95 line. Then metal beats today's runner on spot at 48 or more. Under 33, it never does at 4 vCPUs.
    2. c8id.metal-48xl against bench's c8id.4xlarge, NVMe on both. This holds storage equal, as section 1 above asks. It needs a bench-metal-nvme runner in spin-stack/ci (family c8id.metal-48xl, no nested-virt, scratch on the instance store). Changes the answer if restore or the build moves by more than noise. Then the NVMe premium (break-even 42 against 33 for gp3) buys latency, and the model prices it. If not, gp3 metal is the cheaper metal.
    3. c8in.metal-48xl, capacity before latency. It is the cheapest Intel 8th-gen metal ($0.0485, 36% under today's runner), with the same CPU as bench-metal. It needs a runner with family = ["c8in.metal-48xl"], spot only, and a record of pending time and fulfilment failures over a week of lab runs, plus one cold-login run. Changes the answer if spot fills in most attempts and cold login matches c8i.metal-48xl's 363 ms. Then it replaces c8i.metal-48xl as the metal candidate. If spot rarely fills, the price is not real.
    4. AMD metal: c8a.metal-24xl (spot) or c6a.metal (on demand). A bench-metal-amd runner, cold login plus section 1's build probe for CPU time per build. That measures the AMD speed dial. Changes the answer if an AMD vCPU does 1.4 or more Intel vCPUs' work. Then c8a.metal-24xl holds 33 or more at 4 vCPU-equivalents and costs under c8i.metal-48xl per workspace, on a 24-workspace step. On demand, c6a.metal is already first from 48 up at 1.0, so only its cold login stands between it and a runner type.
    5. Nested c7i.4xlarge and c8i.12xlarge as the nested baseline. For fleets under ~40, nested still wins. c7i.4xlarge ×2 is 11% under today's c8id.8xlarge on spot, and c8id.12xlarge wins dense shapes. A bench-c7i runner (c7i.4xlarge, nested-virt, which AWS added to 7th-gen Intel on 2026-06-18) and one cold-login run. Changes the answer if 7th-gen nested is within noise of bench's 418 ms. Then spin-terraform-aws's runner types can add c7i for small fleets.

    Two runs are two machines, so each comparison is interleaved against bench in one run, as docs/measuring.md says.

    Scripts, all rerunnable and read-only: fetch_usw2.sh (describe, prices, spot, advisor, gp3), candidates.py, placement.sh, prices_usw2.py, model.js, rank.js and build.py.

    🤖 Generated with Claude Code

  2. aledbf commented on Nov 23, 2026

    @aledbf
    MemberAuthor

    The research's scripts, to rerun the model (us-west-2, read 2026-11-22). They are read-only: describe-instance-types, the public on-demand list, describe-spot-price-history, the public Spot Advisor data, gp3 from the Price List API, and get-spot-placement-scores (capped at 50 distinct queries a day). Each needs AWS credentials from the environment and names no account. The page's source is the published artifact (page.src.html, built by build.py).

    Order: fetch_usw2.sh OUT → prices_usw2.py → node rank.js (rankings) → build.py (the page). placement.sh reads "type hosts" lines on stdin. prices.py is the first model's us-east-1 reduction.

    fetch_usw2.sh
    #!/bin/sh
    # Every input the us-west-2 model reads, fetched read-only into $1 (default ../usw2):
    # instance descriptions, AWS's public on-demand list, 30 days of spot history, gp3's price, and the
    # public Spot Instance Advisor data. Nothing here launches or changes a resource.
    set -eu
    here=$(cd "$(dirname "$0")" && pwd)
    out=${1:-$here/../usw2}
    end=${END:-$(date -u +%Y-%m-%dT%H:00:00Z)}
    start=$(date -u -d "$end - 30 days" +%Y-%m-%dT%H:00:00Z)
    mkdir -p "$out"
    cd "$out"
    R=us-west-2
    aws ec2 describe-instance-types --region $R --filters "Name=processor-info.supported-features,Values=nested-virtualization" --output json > nested-types.json
    aws ec2 describe-instance-types --region $R --filters "Name=bare-metal,Values=true" "Name=processor-info.supported-architecture,Values=x86_64" --output json > metal-types.json
    python3 -I "$here/candidates.py" nested-types.json metal-types.json > candidates.json
    curl -fsS --compressed -o od.json "https://b0.p.awsstatic.com/pricing/2.0/meteredUnitMaps/ec2/USD/current/ec2-ondemand-without-sec-sel/US%20West%20(Oregon)/Linux/index.json"
    curl -fsS -o spot-advisor.json https://spot-bid-advisor.s3.amazonaws.com/spot-advisor-data.json
    for u in VolumeUsage VolumeP-IOPS VolumeP-Throughput; do
      aws pricing get-products --region us-east-1 --service-code AmazonEC2 --filters \
        "Type=TERM_MATCH,Field=regionCode,Value=$R" "Type=TERM_MATCH,Field=volumeApiName,Value=gp3" \
        "Type=TERM_MATCH,Field=usagetype,Value=USW2-EBS:$u.gp3" --output json > "gp3-$u.json"
    done
    python3 -I -c 'import json,sys; print("\n".join(r["type"] for r in json.load(open(sys.argv[1]))))' candidates.json > types.txt
    rm -f spot-*.part.json
    split -l 20 types.txt types.chunk.
    for f in types.chunk.*; do
      aws ec2 describe-spot-price-history --region $R --product-descriptions Linux/UNIX \
        --start-time "$start" --end-time "$end" --instance-types $(cat "$f") --output json > "spot-$f.part.json"
    done
    rm -f types.chunk.*
    echo "$start $end" > spot-window.txt
    candidates.py
    # The candidate set, from EC2's own description of us-west-2's instance types (describe-instance-types).
    # Nested: every type whose processor reports "nested-virtualization", narrowed to the families and sizes
    # a fleet of 8-48 workspaces would run on. Metal: every x86 bare-metal type from the 6th generation on,
    # minus GPU hosts and the 16-32 GiB-per-vCPU x families, whose memory a 2 GiB workspace cannot use.
    # Usage: candidates.py nested-types.json metal-types.json > candidates.json
    import json, sys
    NESTED_FAMILIES = {"c7i", "m7i", "r7i", "c8i", "m8i", "r8i", "c8id", "m8id", "r8id", "i7i", "i7ie"}
    NESTED_SIZES = {"4xlarge", "6xlarge", "8xlarge", "12xlarge", "16xlarge", "24xlarge", "48xlarge"}
    METAL_EXCLUDE_PREFIX = ("g4dn", "x2", "x8", "z1d", "c5", "m5", "r5", "i3en")
    def vendor(t):
        m = t["ProcessorInfo"].get("Manufacturer", "")
        return "AMD" if "AMD" in m else "Intel" if "Intel" in m else m
    def row(t, kind):
        name = t["InstanceType"]
        fam, size = name.split(".")
        disks = t.get("InstanceStorageInfo", {}).get("Disks", [])
        ebs = t["EbsInfo"].get("EbsOptimizedInfo", {})
        return {
            "type": name, "kind": kind, "family": fam, "size": size, "vendor": vendor(t),
            "cpu": t["ProcessorInfo"].get("SustainedClockSpeedInGhz"),
            "vcpu": t["VCpuInfo"]["DefaultVCpus"], "memGiB": t["MemoryInfo"]["SizeInMiB"] / 1024,
            "nvme": {"count": disks[0]["Count"], "gb": disks[0]["SizeInGB"]} if disks else None,
            "threadsPerCore": t["VCpuInfo"].get("DefaultThreadsPerCore", 1),
            "ebsMbps": ebs.get("BaselineBandwidthInMbps"), "network": t["NetworkInfo"]["NetworkPerformance"],
            "spotOffered": "spot" in t["SupportedUsageClasses"],
        }
    nested = [row(t, "nested") for t in json.load(open(sys.argv[1]))["InstanceTypes"]
              if t["InstanceType"].split(".")[0] in NESTED_FAMILIES and t["InstanceType"].split(".")[1] in NESTED_SIZES]
    metal = [row(t, "metal") for t in json.load(open(sys.argv[2]))["InstanceTypes"]
             if not t["InstanceType"].startswith(METAL_EXCLUDE_PREFIX)]
    out = sorted(nested + metal, key=lambda r: (r["kind"], r["family"], r["vcpu"]))
    json.dump(out, sys.stdout, indent=1)
    prices_usw2.py
    # Reduces fetch_usw2.sh's files to the page's price table: one row per candidate with its shape,
    # on-demand price, spot percentiles, and the Spot Instance Advisor's interruption band.
    # Spot: time-weighted percentiles over every zone's price, each price weighted by the hours it held
    # in its zone (the same reduction tools/prices.py made for us-east-1). Per-zone medians are kept too,
    # because a fleet launches in the zones that have capacity, not in the average.
    # Usage: prices_usw2.py DIR > prices-usw2.json
    import json, sys, glob, os, datetime as dt
    d = sys.argv[1]
    cands = json.load(open(os.path.join(d, "candidates.json")))
    od = json.load(open(os.path.join(d, "od.json")))
    odrows = {v["Instance Type"]: v for v in od["regions"]["US West (Oregon)"].values()}
    start, end = (dt.datetime.fromisoformat(x.replace("Z", "+00:00")) for x in open(os.path.join(d, "spot-window.txt")).read().split())
    hist = []
    for f in sorted(glob.glob(os.path.join(d, "spot-types.chunk.*.part.json"))):
        hist += json.load(open(f))["SpotPriceHistory"]
    by = {}
    for e in hist:
        by.setdefault(e["InstanceType"], {}).setdefault(e["AvailabilityZone"], []).append(
            (dt.datetime.fromisoformat(e["Timestamp"]), float(e["SpotPrice"])))
    adv = json.load(open(os.path.join(d, "spot-advisor.json")))
    bands = {r["index"]: r["label"] for r in adv["ranges"]}
    advisor = adv["spot_advisor"]["us-west-2"]["Linux"]
    def gp3(u):
        p = json.loads(json.load(open(os.path.join(d, f"gp3-{u}.json")))["PriceList"][0])
        t = list(p["terms"]["OnDemand"].values())[0]
        return float(list(t["priceDimensions"].values())[0]["pricePerUnit"]["USD"]), t["effectiveDate"]
    def weighted(pts):
        out = []
        pts.sort()
        for i, (ts, p) in enumerate(pts):
            a, b = max(ts, start), (pts[i + 1][0] if i + 1 < len(pts) else end)
            if b > a:
                out.append((p, (b - a).total_seconds()))
        return out
    def pct(w, q):
        w = sorted(w)
        total, acc = sum(x for _, x in w), 0
        for p, x in w:
            acc += x
            if acc >= q * total:
                return p
    # Spot placement scores from placement.sh, where it ran: "type hosts score" per line.
    placement = {}
    pp = os.path.join(d, "placement-ok.txt")
    if os.path.exists(pp):
        for line in open(pp):
            t, n, sc = line.split()
            placement[t] = {"hosts": int(n), "score": int(sc)}
    gib, eff = gp3("VolumeUsage")
    iops, _ = gp3("VolumeP-IOPS")
    mibps, _ = gp3("VolumeP-Throughput")
    out = {"region": "us-west-2", "onDemandPublished": od["manifest"]["hawkFilePublicationDate"],
           "spotWindow": [start.isoformat(), end.isoformat()], "read": "2026-11-22",
           "gp3": {"gibMonth": gib, "iopsMonth": iops, "mibpsMonth": round(mibps / 1024, 4), "effective": eff},
           "types": {}}
    for c in cands:
        t = c["type"]
        if t not in odrows:
            continue
        zones = by.get(t, {})
        allw, zmed = [], {}
        for z, pts in zones.items():
            w = weighted(pts)
            if w:
                allw += w
                zmed[z] = pct(w, 0.5)
        a = advisor.get(t)
        row = dict(c, onDemand=float(odrows[t]["price"]), zones=len(zmed), zoneP50=zmed,
                   advisorBand=bands[a["r"]] if a else None, advisorSavingPct=a["s"] if a else None, placement=placement.get(t))
        if allw:
            row.update(spotP10=pct(allw, 0.1), spotP50=pct(allw, 0.5), spotP90=pct(allw, 0.9))
        out["types"][t] = row
    json.dump(out, sys.stdout, indent=1)
    placement.sh
    #!/bin/sh
    # Spot placement scores (1-10, read-only GetSpotPlacementScores) in us-west-2 for each type named on
    # stdin as "type hosts": how likely AWS thinks a request for that many spot hosts is to be filled.
    # Prints "type hosts score" lines; a refusal (the API caps distinct queries a day) prints the error.
    while read -r t n; do
      s=$(aws ec2 get-spot-placement-scores --region us-west-2 --region-names us-west-2 --instance-types "$t" \
          --target-capacity "$n" --query 'SpotPlacementScores[0].Score' --output text 2>&1) || { echo "$t $n ERR $s"; continue; }
      echo "$t $n $s"
    done
    model.js
    // The model. Pure functions of (prices, params); the page and tools/rank.js both run this file.
    // An option is one instance type, run nested or on metal as the type allows, with its cache on the
    // instance store when it has one and on gp3 when it has none. A type with NVMe never pays for gp3 on
    // top: it has already paid for the disk.
    const HOURS_PER_MONTH = 730;
    const GP3_VOLUME = { maxGiB: 65536, maxIops: 80000, maxMibps: 2000, freeIops: 3000, freeMibps: 125 };
    const GB_TO_GIB = 1e9 / 2 ** 30;
    
    // What one vCPU of this type does, relative to an 8th-generation Intel vCPU (one hyperthread).
    // Nothing in spin-machine has measured a workspace on AMD or on an older generation, so both are dials
    // at 1.0 by default. AMD's 7th and 8th generation give each vCPU a whole core (one thread per core),
    // which is the reason the dial exists; how much that buys a workspace is unmeasured.
    function cpuClass(t) {
      if (t.vendor === "AMD" && t.threadsPerCore === 1) return "amdCore";
      return Number(t.family.match(/\d/)[0]) < 8 ? "older" : "intel8";
    }
    function speed(t, p) { return { intel8: 1, amdCore: p.amdSpeed, older: p.olderSpeed }[cpuClass(t)]; }
    function storageOf(t) { return t.nvme ? "nvme" : "ebs"; }
    
    // Workspaces one host holds, and what binds it: the tightest of CPU, memory, the cache's space on the
    // instance store, and the instance's EBS bandwidth for a gp3 cache. The nested I/O tax makes a nested
    // workspace need more host CPU for the same work, so it divides the CPU side on nested hosts only.
    function capacity(t, p) {
      const vcpuEach = (p.vcpuPerWs * (t.kind === "nested" ? 1 + p.tax : 1)) / speed(t, p);
      const limits = {
        cpu: (t.vcpu - p.reserveVcpu) / vcpuEach,
        memory: (t.memGiB - p.reserveMemGiB) / p.memPerWsGiB,
      };
      if (t.nvme) limits.disk = (t.nvme.count * t.nvme.gb * GB_TO_GIB) / p.cacheGiBPerWs;
      else if (p.mibpsPerWs > 0) limits["EBS bandwidth"] = ((t.ebsMbps * 1e6) / 8 / 2 ** 20) / p.mibpsPerWs;
      let bound = "cpu";
      for (const k in limits) if (limits[k] < limits[bound]) bound = k;
      return { cap: Math.max(0, Math.floor(limits[bound])), bound };
    }
    
    // gp3 a month for d workspaces' cache, split over as many volumes as one volume's limits need,
    // each volume bringing its own free 3,000 IOPS and 125 MiB/s.
    function gp3Month(prices, d, p) {
      const g = prices.gp3, gib = d * p.cacheGiBPerWs, iops = d * p.iopsPerWs, mibps = d * p.mibpsPerWs;
      const v = Math.max(1, Math.ceil(gib / GP3_VOLUME.maxGiB), Math.ceil(iops / GP3_VOLUME.maxIops), Math.ceil(mibps / GP3_VOLUME.maxMibps));
      return gib * g.gibMonth + Math.max(0, iops - v * GP3_VOLUME.freeIops) * g.iopsMonth + Math.max(0, mibps - v * GP3_VOLUME.freeMibps) * g.mibpsMonth;
    }
    // A host's disks an hour: its root gp3, and for a gp3-cache option the cache sized for d workspaces.
    function diskHourly(prices, t, d, p) {
      return (p.rootGiB * prices.gp3.gibMonth + (storageOf(t) === "ebs" ? gp3Month(prices, d, p) : 0)) / HOURS_PER_MONTH;
    }
    function hostHourly(prices, t, d, p) { return t[p.market] + diskHourly(prices, t, d, p); }
    function perWorkspace(prices, t, d, p) { return d > 0 ? hostHourly(prices, t, d, p) / d : Infinity; }
    
    // One option at fleet size N: enough hosts to hold every workspace, each disk sized for a full host.
    function option(prices, t, p) {
      const { cap, bound } = capacity(t, p);
      const host = cap > 0 ? hostHourly(prices, t, cap, p) : Infinity;
      const hosts = cap > 0 ? Math.ceil(p.fleet / cap) : Infinity;
      return { type: t.type, t, kind: t.kind, storage: storageOf(t), cpuClass: cpuClass(t), cap, bound, host,
        full: cap > 0 ? host / cap : Infinity, hosts, fleetPerWs: (hosts * host) / p.fleet };
    }
    
    // The fewest workspaces on one host at which it costs no more per workspace than ref does full.
    function breakEven(prices, o, ref, p) {
      for (let d = 1; d <= o.cap; d++) if (perWorkspace(prices, o.t, d, p) <= ref.full + 1e-12) return d;
      return null;
    }
    
    // Advisor bands, in order; an option passes the filter when its band is at or under p.maxBand.
    const BANDS = ["<5%", "5-10%", "10-15%", "15-20%", ">20%"];
    function passes(o, p) {
      if (!(o.t[p.market] > 0) || o.cap === 0) return false;
      if (p.kinds !== "all" && o.kind !== p.kinds) return false;
      if (p.vendors !== "all" && o.t.vendor !== p.vendors) return false;
      if (p.storageFilter !== "all" && o.storage !== p.storageFilter) return false;
      if (p.market !== "onDemand" && p.maxBand < BANDS.length - 1) {
        const b = BANDS.indexOf(o.t.advisorBand);
        if (b < 0 || b > p.maxBand) return false;
      }
      return true;
    }
    
    // The best fleet that fills k metal hosts and tops up with nested hosts of one type, over every
    // metal and nested option that passes the filters. Metal pays when it is full; this is how a fleet
    // keeps it full without paying for metal's empty slots.
    function bestMix(options, p) {
      const metal = options.filter((o) => o.kind === "metal"), nested = options.filter((o) => o.kind === "nested");
      let best = null;
      for (const m of metal) for (let k = 1; k * m.cap < p.fleet; k++) for (const n of nested) {
        const rest = p.fleet - k * m.cap, h = Math.ceil(rest / n.cap);
        const cost = (k * m.host + h * n.host) / p.fleet;
        if (!best || cost < best.fleetPerWs) best = { metal: m, k, nested: n, h, fleetPerWs: cost };
      }
      return best;
    }
    
    function evaluate(prices, p) {
      const all = Object.values(prices.types).map((t) => option(prices, t, p));
      const ref = all.find((o) => o.type === p.reference);
      for (const o of all) o.breakEven = o === ref ? null : breakEven(prices, o, ref, p);
      const ranked = all.filter((o) => passes(o, p)).sort((a, b) => a.fleetPerWs - b.fleetPerWs || a.full - b.full);
      return { all, ranked, ref, mix: bestMix(ranked, p) };
    }
    
    if (typeof module !== "undefined") module.exports = { BANDS, HOURS_PER_MONTH, cpuClass, storageOf, capacity, gp3Month, hostHourly, perWorkspace, option, breakEven, evaluate };
    rank.js
    // Prints the ranked options at the fleet sizes the report names, for each shape and market.
    // Usage: node rank.js ../usw2/prices-usw2.json [top]
    const m = require("./model.js");
    const prices = require(require("path").resolve(process.argv[2]));
    const top = Number(process.argv[3] || 6);
    const base = { market: "spotP50", vcpuPerWs: 4, memPerWsGiB: 2, tax: 0, reserveVcpu: 0, reserveMemGiB: 0, rootGiB: 30,
      cacheGiBPerWs: 30, iopsPerWs: 250, mibpsPerWs: 16, fleet: 96, reference: "c8id.8xlarge", amdSpeed: 1, olderSpeed: 1,
      kinds: "all", vendors: "all", storageFilter: "all", maxBand: 4 };
    const $ = (v) => "$" + v.toFixed(4);
    function show(label, over) {
      for (const fleet of [8, 48, 96, 480]) {
        const p = Object.assign({}, base, over, { fleet });
        const { ranked, ref, mix } = m.evaluate(prices, p);
        console.log(`-- ${label} | fleet ${fleet} | today ${ref.type} ${$(ref.fleetPerWs)} (${ref.hosts}x${ref.cap})`);
        ranked.slice(0, top).forEach((o, i) => console.log(`  ${i + 1}. ${o.kind.padEnd(6)} ${o.type.padEnd(17)} ${$(o.fleetPerWs)} ${o.hosts}x cap ${o.cap} (${o.bound}) full ${$(o.full)} band ${o.t.advisorBand} ${o.t.vendor}`));
        if (mix) console.log(`  mix: ${mix.k}x ${mix.metal.type} + ${mix.h}x ${mix.nested.type} ${$(mix.fleetPerWs)}`);
        const bestMetal = ranked.find((o) => o.kind === "metal"), bestNested = ranked.find((o) => o.kind === "nested");
        console.log(`  best metal ${bestMetal && bestMetal.type} ${bestMetal && $(bestMetal.fleetPerWs)} | best nested ${bestNested && bestNested.type} ${bestNested && $(bestNested.fleetPerWs)}`);
      }
    }
    const shapes = { "4 vCPU/2 GiB": {}, "1 vCPU/2 GiB": { vcpuPerWs: 1 }, "0.5 vCPU/2 GiB": { vcpuPerWs: 0.5 } };
    const markets = (process.env.MARKETS || "spotP50,onDemand").split(",");
    for (const [s, o] of Object.entries(shapes)) for (const mk of markets) show(`${s} ${mk}`, Object.assign({ market: mk }, o, JSON.parse(process.env.OVER || "{}")));
    build.py
    import json, sys
    src, prices, model, out = sys.argv[1:5]
    s = open(src).read()
    m = open(model).read().split("if (typeof module")[0]
    s = s.replace("/*PRICES*/", json.dumps(json.load(open(prices)), separators=(",", ":")))
    s = s.replace("/*MODEL*/", m)
    s = s.replace("/*ISSUE*/", "https://github.com/spin-stack/machine/issues/563").replace("/*ISSUE_TEXT*/", "spin-stack/machine#563")
    open(out, "w").write(s)
    prices.py
    # Reduces AWS's on-demand price list and 30 days of spot history to the page's price table.
    # Spot: time-weighted percentiles over every zone's price, each zone weighted by the hours it held a price.
    import json, sys, datetime as dt
    od_path, spot_path, end = sys.argv[1], sys.argv[2], sys.argv[3]
    types = [f"{f}{d}.{s}" for f in ("c8i", "m8i", "r8i") for d in ("", "d") for s in ("8xlarge", "metal-48xl")]
    od = json.load(open(od_path))
    rows = {v["Instance Type"]: v for v in od["regions"]["US East (N. Virginia)"].values()}
    hist = json.load(open(spot_path))["SpotPriceHistory"]
    end = dt.datetime.fromisoformat(end)
    start = end - dt.timedelta(days=30)
    out = {"onDemandPublished": od["manifest"]["hawkFilePublicationDate"], "spotWindow": [start.isoformat(), end.isoformat()], "types": {}}
    for t in types:
        r = rows[t]
        zones = {}
        for e in hist:
            if e["InstanceType"] == t:
                zones.setdefault(e["AvailabilityZone"], []).append((dt.datetime.fromisoformat(e["Timestamp"]), float(e["SpotPrice"])))
        weighted = []
        for pts in zones.values():
            pts.sort()
            for i, (ts, p) in enumerate(pts):
                a = max(ts, start)
                b = pts[i + 1][0] if i + 1 < len(pts) else end
                if b > a:
                    weighted.append((p, (b - a).total_seconds()))
        weighted.sort()
        total = sum(w for _, w in weighted)
        def pct(q):
            acc = 0
            for p, w in weighted:
                acc += w
                if acc >= q * total:
                    return p
        out["types"][t] = {
            "vcpu": int(r["vCPU"]), "memGiB": float(r["Memory"].split()[0]), "storage": r["Storage"],
            "onDemand": float(r["price"]), "spotP10": pct(0.1), "spotP50": pct(0.5), "spotP90": pct(0.9), "zones": len(zones),
        }
    json.dump(out, sys.stdout, indent=1)
    Spot placement scores, metal types (type, hosts, score of 10)
    c6a.metal 2 3
    c6i.metal 3 2
    c6id.metal 3 3
    c6in.metal 3 1
    c7a.metal-48xl 2 1
    c7i.metal-24xl 4 3
    c7i.metal-48xl 2 3
    c8a.metal-24xl 4 3
    c8a.metal-48xl 2 3
    c8i.metal-48xl 2 3
    c8i.metal-96xl 1 3
    c8id.metal-48xl 2 3
    c8id.metal-96xl 1 3
    c8in.metal-48xl 2 3
    c8in.metal-96xl 1 3
    i4i.metal 3 3
    i7i.metal-24xl 4 3
    i7i.metal-48xl 2 3
    i7ie.metal-24xl 4 3
    i7ie.metal-48xl 2 3
    m6a.metal 2 3
    m6i.metal 3 3
    m6id.metal 3 3
    m6idn.metal 3 1
    m6in.metal 3 1
    m7a.metal-48xl 2 3
    m7i.metal-24xl 4 3
    m7i.metal-48xl 2 3
    m8a.metal-24xl 4 3
    m8a.metal-48xl 2 3
    m8azn.metal-12xl 8 1
    m8azn.metal-24xl 4 1
    m8i.metal-48xl 2 3
    m8i.metal-96xl 1 3
    m8id.metal-48xl 2 3
    m8id.metal-96xl 1 3
    m8idn.metal-48xl 2 3
    m8idn.metal-96xl 1 3
    r6a.metal 2 1
    r6i.metal 3 1
    r6id.metal 3 3
    r6idn.metal 3 1
    r6in.metal 3 1
    r7a.metal-48xl 2 3
    r7i.metal-24xl 4 2
    r7i.metal-48xl 2 1
    r7iz.metal-16xl 6 3
    r7iz.metal-32xl 3 3
    r8a.metal-24xl 4 1
    r8a.metal-48xl 2 1
    
  3. aledbf commented on Nov 23, 2026

    @aledbf
    MemberAuthor

    Section 2, density on metal: measured (2026-11-23)

    density ran as it stands: v20261123.04, spin's shape (1 of 16 vCPUs, 2048 MiB plugged) and spin's login. The cell is the first login's p50/p95 in ms. "Within 25%" means a p95 within 25% of the empty host's in the same run.

    host load rows within 25% lab
    nested c8id.4xlarge, 16 CPUs cpu 0: 387/417 · 4: 378/431 · 8: 441/450 · 16: 1015/1215 · 24: 941/1196 up to 8 45110655407 (10 a row)
    metal c8i.metal-48xl, 192 CPUs cpu 0: 337/447 · 16: 331/488 · 32: 335/344 · 48: 336/341 up to 48 45110663095 (10 a row)
    metal cpu 0: 342/363 · 64: 327/366 · 96: 466/486 up to 64, not 96 45110670764 (8 a row)
    metal idle 0: 345/368 · 16: 336/343 · 32: 329/341 · 48: 334/352 all 45110678888 (10 a row)
    metal idle 0: 342/356 · 64: 328/350 · 96: 331/340 all 45110688511 (8 a row)
    • Idle crowds cost a metal host nothing up to 96. The bench showed the same up to 16 (lab: density, workspaces per host before the first login degrades, nested and metal #273).
    • CPU-bound crowds of 1-vCPU workspaces start to hurt at about a third to a half of the host's CPUs. Nested, 8 of 16 is fine and 16 of 16 is +628 ms p50. Metal, 64 of 192 is fine and 96 of 192 is +124 ms p50.
    • For the model: at 1 busy vCPU a workspace, a metal-48xl keeps the first login within 25% with at least 64 workspaces running. That is past the 44 break-even. The range between 64 and 96 is not measured. Neither are workspaces with more than one vCPU, which the model prices at 4 vCPUs. A run at cpus=4 would answer that one.
    • Metal's rows are split into two runs, because a 96 crowd takes ~83 s to boot and 10 rows do not fit in bench-metal's 60 minutes. A row compares only with the empty row of its own run.

    The rows are in docs/boot-time.md ("The bench fleet is nested, not metal") and docs/log.md via #633.

    Section 1, the I/O tax: still open

    Nothing has been run for it. It needs new io and build probes in internal/lab. It also needs equal storage on both hosts, either an NVMe metal fleet in spin-stack/ci or EBS scratch on both. The issue stays open for that.

  4. aledbf commented on Nov 27, 2026

    @aledbf
    MemberAuthor

    Section 1, the nested tax on a running workspace's I/O and build: measured (2026-11-23)

    Measured by #671's io and build probes on its branch, with release-era parts of 2026-11-23. Shape: 1 of 16 vCPUs, 2048 MiB plugged, spin's login. The disk sits on the host's tmpfs in both hosts, so what differs is one hypervisor against two and not the device. The cell is the p50 of the tree with 1 vCPU.

    metal c8i.metal-48xl nested c8id.4xlarge
    4K random read, QD32 (IOPS) 222k 115k (−48%)
    4K random write, QD32 (IOPS) 213k 117k (−45%)
    4K random read, QD1 (IOPS) 24.3k 16.6k (−32%)
    4K random write, QD1 (IOPS) 18.9k 16.4k (−13%)
    guest CPU per unit of work, 4K rows 1029-2451 2032-5375 (~2×)
    1M sequential read / write (MiB/s) 19014 / 6174 17086 / 6117
    go build cmd/go, empty cache, wall 38.3 s 42.2 s (+10%)

    Runs: io on metal lab 45237396777, io nested lab 45243154692 (10 a row); build on metal lab 45247518766, build nested lab 45250242635 (15 each). Each run's result.json also has the four-vCPU tree, completion latency p50/p99 and QEMU's host CPU.

    Reading for the cost model: nesting costs a small random I/O about half its IOPS and about twice its guest CPU. Large sequential I/O and a CPU-bound build lose 0-10%. The machine has changed since then only in its boot (PVH, jemalloc), not in the I/O path, so the reading stands until a release changes the block path (inferred).

    The probes stay on branch archive/lab-563-io-tax, not on main: one question's tool, which spin's cost model asks only when it is recomputed. To run it again, rebase that branch and dispatch lab.yml io or build on bench and bench-metal.

    With section 2 (density, above), both of this issue's sections are measured. The decision is spin's (spin-stack/spin#1652).

  5. aledbf commented on Nov 27, 2026

    @aledbf
    MemberAuthor

    Both sections measured (density on metal above, the nested I/O and build tax in the last comment). What to do with them is spin-stack/spin#1652's.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions