Files
ilkerandClaude Opus 5 d67af5d6c3 hpcod: projects, and what a cluster cost
"How much did the protein run use" is a question about a piece of
work, not about c003-15. A tenant asks for clusters over months;
individually each one is an address, some hardware and a lease, and
nothing joined them up.

A project groups them, and is optional throughout. Somebody who wants
one cluster for an afternoon should not have to invent a project to
get it, and requiring one would mean every tenant carrying a
"default" that means nothing. The form does not even ask when there
are none: a field whose only option is "none" is a question with one
answer.

The cost side needed no new columns. The cluster record already said
when it was created and destroyed, and cluster_vm said how many cores
and how much memory it held; what was missing was anything that read
them. cluster_usage is that, and it is a view rather than a table
because a derived number stored is a number that can disagree with
what it was derived from. It works retroactively - every cluster this
estate has ever built now has a line.

Core-hours are reserved, not executed, and the view says so. That is
the honest unit for an on-demand cluster: the hardware was yours and
nobody else could have it, whether or not a job ran. What was
actually executed is a Slurm accounting question and there is no
slurmdbd.

The project is attached inside the allocating transaction, for the
same reason the placement and the applications are, and it is checked
there to be the tenant's own and still open - a cluster filed against
somebody else's project leaks what they are working on. Closing keeps
history and stops it being offered. There is no delete: the reference
from cluster is RESTRICT, because a project removed from under its
clusters leaves their cost attributed to nothing, and afterwards is
when the question gets asked.

A release now writes manifest.json beside home.tgz: the nodes, the
wall time, the core-hours. The database knows all of it and outlives
the cluster, but the tarball can be moved off this host and the
description travels with it. Not fatal if it fails - the data is
already safe by then, and holding hardware because a note could not
be written is the wrong trade.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 13:05:35 +02:00

424 lines
12 KiB
Go

package store
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
// These tests run against a real PostgreSQL. The invariants being checked -
// a partial unique index, a generated column, an advisory lock - are all
// database behaviour, so a fake would only test the fake.
//
// Each run builds the schema in a scratch schema of its own and drops it
// afterwards, so it can be pointed at the production database without
// touching the clusters recorded there.
func testStore(t *testing.T) *Store {
t.Helper()
dsn := os.Getenv("HPCOD_TEST_DSN")
if dsn == "" {
t.Skip("HPCOD_TEST_DSN not set; skipping database tests")
}
schema := fmt.Sprintf("store_test_%d", time.Now().UnixNano())
ctx := context.Background()
admin, err := pgxpool.New(ctx, dsn)
if err != nil {
t.Fatalf("connect: %v", err)
}
defer admin.Close()
files, err := filepath.Glob("../../db/*.sql")
if err != nil || len(files) == 0 {
t.Fatalf("no migrations found: %v", err)
}
sort.Strings(files)
var ddl []byte
for _, f := range files {
b, err := os.ReadFile(f)
if err != nil {
t.Fatalf("read %s: %v", f, err)
}
ddl = append(ddl, b...)
ddl = append(ddl, '\n')
}
if _, err := admin.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
t.Fatalf("create schema: %v", err)
}
// The file is written for the default schema; steer it into the scratch
// one for the length of this session only.
if _, err := admin.Exec(ctx, "SET LOCAL search_path TO "+schema); err != nil {
t.Fatalf("search_path: %v", err)
}
if _, err := admin.Exec(ctx, "SET search_path TO "+schema+"; "+string(ddl)); err != nil {
t.Fatalf("apply schema: %v", err)
}
sep := "?"
if strings.Contains(dsn, "?") {
sep = "&"
}
s, err := Open(ctx, dsn+sep+"search_path="+schema)
if err != nil {
t.Fatalf("open: %v", err)
}
t.Cleanup(func() {
s.Close()
drop, err := pgxpool.New(context.Background(), dsn)
if err != nil {
t.Logf("cleanup connect: %v", err)
return
}
defer drop.Close()
if _, err := drop.Exec(context.Background(), "DROP SCHEMA "+schema+" CASCADE"); err != nil {
t.Errorf("cleanup: scratch schema %s left behind: %v", schema, err)
}
})
// Guard the guard: if search_path did not take, every test below would
// be writing into the real cluster table.
var got string
if err := s.pool.QueryRow(ctx, "SELECT current_schema()").Scan(&got); err != nil {
t.Fatalf("current_schema: %v", err)
}
if got != schema {
t.Fatalf("tests would run against schema %q, not the scratch schema %q", got, schema)
}
return s
}
func TestEnsureTenantIsIdempotent(t *testing.T) {
s := testStore(t)
ctx := context.Background()
first, err := s.EnsureTenant(ctx, "acme", "ops@acme.example")
if err != nil {
t.Fatalf("first: %v", err)
}
second, err := s.EnsureTenant(ctx, "acme", "ops@acme.example")
if err != nil {
t.Fatalf("second: %v", err)
}
if first != second {
t.Errorf("asking twice made two tenants: %d then %d", first, second)
}
}
func TestAllocateTakesLowestFreeAddress(t *testing.T) {
s := testStore(t)
ctx := context.Background()
tenant := mustTenant(t, s, "acme")
for want := int16(1); want <= 3; want++ {
c, err := s.AllocateCluster(ctx, tenant, plainPlacement(), time.Hour, nil, nil)
if err != nil {
t.Fatalf("allocate: %v", err)
}
if c.ClusterID != want {
t.Fatalf("got cluster_id %d, want %d", c.ClusterID, want)
}
}
}
// The reason the schema exists: an address comes back after the cluster that
// held it is destroyed, but the accounting name it was used under does not.
func TestReleasedAddressIsReusedButAccountingNameIsNot(t *testing.T) {
s := testStore(t)
ctx := context.Background()
tenant := mustTenant(t, s, "acme")
first, err := s.AllocateCluster(ctx, tenant, plainPlacement(), time.Hour, nil, nil)
if err != nil {
t.Fatalf("allocate first: %v", err)
}
if err := s.Release(ctx, first.SerialID); err != nil {
t.Fatalf("release: %v", err)
}
second, err := s.AllocateCluster(ctx, tenant, plainPlacement(), time.Hour, nil, nil)
if err != nil {
t.Fatalf("allocate second: %v", err)
}
if second.ClusterID != first.ClusterID {
t.Errorf("address was not recycled: first %d, second %d", first.ClusterID, second.ClusterID)
}
if second.AccountingName == first.AccountingName {
t.Errorf("accounting name %q reused; two clusters' job records would merge", second.AccountingName)
}
}
func TestReleaseIsNotRepeatable(t *testing.T) {
s := testStore(t)
ctx := context.Background()
tenant := mustTenant(t, s, "acme")
c, err := s.AllocateCluster(ctx, tenant, plainPlacement(), 0, nil, nil)
if err != nil {
t.Fatalf("allocate: %v", err)
}
if err := s.Release(ctx, c.SerialID); err != nil {
t.Fatalf("release: %v", err)
}
if err := s.Release(ctx, c.SerialID); err == nil {
t.Error("releasing an already-released cluster reported success")
}
if err := s.SetState(ctx, c.SerialID, "ready"); err == nil {
t.Error("a destroyed cluster accepted a state change")
}
}
// The invariant the whole design is for. Twenty callers at once must come
// away with twenty different addresses, not twenty copies of number one.
func TestConcurrentAllocationNeverSharesAnAddress(t *testing.T) {
s := testStore(t)
ctx := context.Background()
tenant := mustTenant(t, s, "acme")
const n = 20
ids := make([]int16, n)
errs := make([]error, n)
var wg sync.WaitGroup
start := make(chan struct{})
for i := range n {
wg.Add(1)
go func() {
defer wg.Done()
<-start
c, err := s.AllocateCluster(ctx, tenant, plainPlacement(), time.Hour, nil, nil)
if err != nil {
errs[i] = err
return
}
ids[i] = c.ClusterID
}()
}
close(start)
wg.Wait()
seen := map[int16]int{}
for i, err := range errs {
if err != nil {
t.Fatalf("caller %d: %v", i, err)
}
seen[ids[i]]++
}
for id, count := range seen {
if count > 1 {
t.Errorf("address %d handed out %d times", id, count)
}
}
if len(seen) != n {
t.Errorf("got %d distinct addresses from %d callers", len(seen), n)
}
}
func TestExhaustionIsReportedNotWrappedAround(t *testing.T) {
s := testStore(t)
ctx := context.Background()
tenant := mustTenant(t, s, "acme")
for i := range 254 {
if _, err := s.AllocateCluster(ctx, tenant, plainPlacement(), 0, nil, nil); err != nil {
t.Fatalf("allocate %d: %v", i+1, err)
}
}
if _, err := s.AllocateCluster(ctx, tenant, plainPlacement(), 0, nil, nil); !errors.Is(err, ErrNoFreeID) {
t.Fatalf("255th allocation: got %v, want ErrNoFreeID", err)
}
live, err := s.Live(ctx)
if err != nil {
t.Fatalf("live: %v", err)
}
if len(live) != 254 {
t.Errorf("live count %d, want 254", len(live))
}
}
func TestExpiredListsOnlyPastDueLeases(t *testing.T) {
s := testStore(t)
ctx := context.Background()
tenant := mustTenant(t, s, "acme")
stale, err := s.AllocateCluster(ctx, tenant, plainPlacement(), time.Hour, nil, nil)
if err != nil {
t.Fatalf("allocate stale: %v", err)
}
past := time.Now().Add(-time.Minute)
if err := s.SetLease(ctx, stale.SerialID, &past); err != nil {
t.Fatalf("backdate lease: %v", err)
}
if _, err := s.AllocateCluster(ctx, tenant, plainPlacement(), time.Hour, nil, nil); err != nil {
t.Fatalf("allocate fresh: %v", err)
}
// No lease at all: deliberate, and the reaper must leave it alone.
if _, err := s.AllocateCluster(ctx, tenant, plainPlacement(), 0, nil, nil); err != nil {
t.Fatalf("allocate unbounded: %v", err)
}
expired, err := s.Expired(ctx)
if err != nil {
t.Fatalf("expired: %v", err)
}
if len(expired) != 1 || expired[0].SerialID != stale.SerialID {
t.Fatalf("expired = %+v, want only the stale cluster %d", expired, stale.SerialID)
}
if err := s.Release(ctx, stale.SerialID); err != nil {
t.Fatalf("release: %v", err)
}
after, err := s.Expired(ctx)
if err != nil {
t.Fatalf("expired after release: %v", err)
}
if len(after) != 0 {
t.Errorf("a released cluster is still reported expired: %+v", after)
}
}
func mustTenant(t *testing.T, s *Store, name string) int64 {
t.Helper()
id, err := s.EnsureTenant(context.Background(), name, name+"@example.invalid")
if err != nil {
t.Fatalf("tenant: %v", err)
}
return id
}
// A lease of zero is "no expiry", not "expired a moment ago" - the reaper
// must never mistake the first for the second.
func TestUnboundedLeaseIsNeverExpired(t *testing.T) {
s := testStore(t)
ctx := context.Background()
tenant := mustTenant(t, s, "acme")
c, err := s.AllocateCluster(ctx, tenant, plainPlacement(), 0, nil, nil)
if err != nil {
t.Fatalf("allocate: %v", err)
}
if c.LeaseExpiresAt != nil {
t.Fatalf("lease 0 recorded an expiry of %v", *c.LeaseExpiresAt)
}
expired, err := s.Expired(ctx)
if err != nil {
t.Fatalf("expired: %v", err)
}
if len(expired) != 0 {
t.Errorf("unbounded cluster reported expired: %+v", expired)
}
// And a lease can be attached later, at which point it does count.
past := time.Now().Add(-time.Minute)
if err := s.SetLease(ctx, c.SerialID, &past); err != nil {
t.Fatalf("set lease: %v", err)
}
expired, err = s.Expired(ctx)
if err != nil {
t.Fatalf("expired after set: %v", err)
}
if len(expired) != 1 || expired[0].SerialID != c.SerialID {
t.Errorf("after backdating the lease, expired = %+v", expired)
}
}
// The concurrency test above would also pass if the database were doing
// nothing and the callers merely happened not to overlap. This one checks
// the safety net directly: a deliberately naive allocator - scan for a free
// address, then insert it, with no lock and no single statement - is let
// loose, and the partial unique index has to stop it from ever seating two
// live clusters at the same address.
func TestUniqueIndexStopsANaiveAllocator(t *testing.T) {
s := testStore(t)
ctx := context.Background()
tenant := mustTenant(t, s, "acme")
const n = 20
var wg sync.WaitGroup
var mu sync.Mutex
var rejected int
start := make(chan struct{})
for range n {
wg.Add(1)
go func() {
defer wg.Done()
<-start
var free int16
err := s.pool.QueryRow(ctx, `
SELECT gs FROM generate_series(1, 254) AS gs
WHERE NOT EXISTS (SELECT 1 FROM cluster c
WHERE c.cluster_id = gs AND c.destroyed_at IS NULL)
ORDER BY gs LIMIT 1`).Scan(&free)
if err != nil {
return
}
_, err = s.pool.Exec(ctx,
`INSERT INTO cluster (cluster_id, tenant_id, site) VALUES ($1, $2, 'hv01')`,
free, tenant)
if isUniqueViolationOn(err, "cluster_live_id_unique") {
mu.Lock()
rejected++
mu.Unlock()
}
}()
}
close(start)
wg.Wait()
// Whatever the naive callers managed, the table must still hold at most
// one live cluster per address.
var dupes int
if err := s.pool.QueryRow(ctx, `
SELECT count(*) FROM (
SELECT cluster_id FROM cluster WHERE destroyed_at IS NULL
GROUP BY cluster_id HAVING count(*) > 1) d`).Scan(&dupes); err != nil {
t.Fatalf("count duplicates: %v", err)
}
if dupes != 0 {
t.Fatalf("%d addresses are held by more than one live cluster", dupes)
}
// And the collisions have to have actually happened, otherwise this run
// proved nothing about the index.
if rejected == 0 {
t.Skip("the naive allocators never overlapped; the index was not exercised")
}
t.Logf("index rejected %d of %d naive allocations", rejected, n)
}
// plainPlacement is the smallest placement that is valid: one head, one
// compute, no hardware. Tests about addresses and leases use it so they say
// nothing about devices.
func plainPlacement() Placement {
return Placement{
Site: "hv01",
VMs: []VM{
{Role: "head", NodeIndex: 0, HostNode: "hv01", Cores: 2, MemoryGB: 4},
{Role: "compute", NodeIndex: 1, HostNode: "hv01", Cores: 2, MemoryGB: 6},
},
}
}
// withGPU is the same placement with one card attached to the compute node.
func withGPU(host, nativeID string) Placement {
p := plainPlacement()
p.VMs[0].HostNode = host
p.VMs[1].HostNode = host
p.VMs[1].Devices = []Device{{NativeID: nativeID, Capability: "gpu"}}
return p
}