HydraIssues

hydracluster: a head's slot claim is overwritten by the next body in the listing, so claims land on the wrong body
open bug Priority: high Project: hydracluster Parent: #504 Reporter: 18 Oct 2026 16:26

Description

Summary

slotClaims.claims is map[string]slotClaim keyed by head id alone (pkg/api/slotclaims.go:45), so a head holds exactly ONE claim fleet-wide. But Claim is called once per body inside the eligibility loop (pkg/api/handlers_api.go:1062), so each call overwrites the last. A head that lists two multi-slot bodies ends up holding a claim on whichever body the loop happened to visit last, not the one it uses.

The head is still TOLD a port for every body, so the ports are promised and not held.

Why it was invisible until 2026-10-18

Claim returns early for a single-slot body without writing to the map:

ports := normalizeSlotPorts(slotPorts)
if len(ports) <= 1 {
    return defaultSlotPort   // no map write
}

While cosmic-pretzel-98 was the only body in the fleet reporting more than one port, it was the only writer, so every claim landed on it and the allocator was correct. boom-pickle-38 began reporting two ports today (#829) and became a second writer. The bug is in the allocator, not in either body.

Measured, 2026-10-18 16:22 UTC, GET /api/v1/bodies/eligible?district=bxl1

cosmic-pretzel-98   free_slots=3  stream_count=1   <- STREAMING, yet every slot reported free
boom-pickle-38      free_slots=0 -> 1 -> 2          <- no streams at all, yet claims churning

Cosmic is serving a stream while reporting all three slots free, because the streaming head's claim was overwritten onto boom-pickle. boom-pickle holds claims for streams it is not running.

free_slots=0 is itself proof the ports are reported correctly: FreeSlots returns a hard-coded 1 when len(ports) <= 1, so zero is only reachable when a body has ports and all are taken.

All four online heads in bxl1 and both bodies share owner=visit.flanders, and the filter is if !sameVenue && !sameOwner { continue }, so every head sees both bodies regardless of venue and claims on both. boom-pickle (created 2026-03-25) is iterated after cosmic (2026-03-24).

Consequence

This is the exact fault the feature exists to prevent. With no claims recorded on cosmic, taken is empty there, so every head is handed the first free port, 47989, slot 0. Three iPads at cloud-seven would all be directed into one lane: the Sint-Niklaas three-kiosks-one-picture collapse described in the file's own header comment.

No venue was live when this was found, so nothing was harmed.

The obvious fix is NOT sufficient

Keying by (headID, bodyID) fixes the overwrite but introduces a false-full, because taken counts every OTHER head that merely LISTED the body:

for id, cl := range c.claims {
    if id != headID && cl.bodyID == bodyID { taken[cl.port] = true }
}

A head reserves a lane on every body it can see, so a body looks full once the number of heads that can see it exceeds its slot count. cosmic has 3 slots and 4 visible heads today, so the fourth head would be handed StreamPort = 0. That is a worse failure than the one being fixed, and it is already reachable in this fleet.

Candidate designs, for an owner decision

  1. Key by (head, body). Correct per-body collision avoidance, smallest diff, but the false-full above bites immediately at cloud-seven. Would need taken to stop counting heads that are not actually using the body.
  2. Claim only the body the head will use. Move the Claim call after the sort and claim the top-ranked candidate only. Matches the header comment's intent, that the head picks a body and then streams. Weakness: heads probe in sorted order and fail over, so a head that falls through to the second body holds no claim on it.
  3. Reconcile claims from real sessions. The cluster already learns the streaming client UUID per body (sessionStore.openSession in handlers_body.go), so claims could follow actual sessions rather than listings. Strongest, largest change, and it reintroduces the gap the header comment rejected: the head picks a body before it talks to it.

I have not implemented any of these. The choice changes allocator semantics fleet-wide and belongs to whoever owns #504.

Workaround until then

Keeping exactly one multi-slot body per owner restores the old correct behaviour, since single-slot bodies never write a claim. Removing slots.yaml from boom-pickle and restarting HydraBody is a one-minute revert if a venue needs to go live before this is fixed.

Session Context

Venue
cloud-seven

Comments (4)

api 18 Oct 2026 16:29

Three corrections and a fourth design option, all verified against the DEPLOYED tree (origin/main = 608b5f8 = v2.0.130) rather than the checkout I first read.

Correction 1: my line numbers were from a stale checkout

My tree was at 64385d5, thirteen commits behind v2.0.130. The Claim/FreeSlots calls are at handlers_api.go:1072-1073, not 1062-1063. The claims map is at slotclaims.go:46, not 45.

The analysis itself is unaffected. git diff 64385d5 origin/main -- pkg/api/slotclaims.go is empty, so the file is byte-identical in the deployed version, and both call sites are still inside the per-body loop. The measurements were always taken against live production.

Correction 2: hydracluster contains TWO independent slot allocators

This is the part that changes the decision, and I could not see it from the stale tree.

pkg/api/slotclaims.go    in-memory, keyed by head id, assigns a PORT during eligibility
pkg/api/slot_lease.go    durable leases in allocation.yaml, with a LIFECYCLE
pkg/store/slot_lease.go

They do not reference each other at all. Grepping slot_lease.go for slotClaims, .Claim(, FreeSlots or slotClaim returns 0. The only lease hits inside slotclaims.go are the substring in Release, so the true cross-reference count is zero in both directions.

They arrived from different branches: the lease came in with d4cbb90 Deliver owned stop behind a durable slot lease (#771), merged to main today as part of v2.0.130.

So a body's occupancy has two truths in one process:

slotClaims slot lease
holds the port body id, head id, epoch, client id
lifetime in memory, dies with the process durable, survives restart
states one, with a 95s TTL granted / streaming / draining / terminal, 90s TTL
drives which port a head is told admission, and whether an owned stop may fire

A head can hold a lease on one body while its slotClaim has been overwritten onto another. That is the symptom in this issue wearing a different hat, and re-keying slotClaims alone would make the two disagree more precisely rather than less.

Correction 3: the premise that forced claiming-during-listing is no longer true

slotclaims.go's header comment justifies claiming inside the eligibility listing like this:

the head picks a body and then streams, with no step in between where it could claim anything

That is now false, and it is falsified by code in the same package. v2.0.130 serves:

POST   /api/v1/heads/{id}/slot-claims
DELETE /api/v1/heads/{id}/slot-claims/{lease_id}

and slotClaimRequest carries PreferBodyID, Experience, StreamMode and ClientID. There IS a step in between now, and the head already names the body it wants.

Since that premise is the entire reason a claim is taken while merely LISTING bodies, and claiming while listing is the direct cause of this bug, the constraint that shaped options 1 and 2 has lapsed.

Option 4 (from the #771 session, and now my recommendation)

Make the lease authoritative and move the port into it, rather than keying slotClaims better. The lease already carries body id, head id, epoch, client id and a lifecycle, which is most of an allocator; slotClaims carries the port, which the lease lacks. Merging them leaves one answer to "is this body free" with one lifetime, and the claim happens at the dedicated endpoint where the head names its body, so no claim is ever taken on a body the head merely listed.

That also dissolves the taken-counting hazard rather than working around it: a head only ever holds a lane on a body it actually asked for.

Still an owner decision, and a larger one than it looked, because it touches admission for every head type. Nothing implemented.

Not blocking

chunky-turnip-23 is single-slot, so the #771 panel work is on the one path this bug cannot reach: Claim returns early without writing to the map when len(ports) <= 1. boom-pickle-38 stays on two slots as a reproducer. No venues are live.

api 18 Oct 2026 16:32

The duplication is wider than two files, and one of the other mechanisms is body-wide, which multi-slot cannot survive. Verified on origin/main (v2.0.130).

The matching TTLs, as suggested

slotClaimTTL = 95 * time.Second   // slotclaims.go:29, "tolerates two missed 30s ticks"
leaseTTL     = 90 * time.Second   // slot_lease.go:20,  renewed on the heartbeat

Two expiry policies, five seconds apart, for "this head has stopped caring about this body". Both files also exist to prevent the same incident: slotclaims.go's header cites Sint-Niklaas, and the lease prevents the same recurrence by marking a body occupied while any lease on it is granted, streaming or draining.

There are not two sources of occupancy truth, there are six

The eligibility loop at handlers_api.go:1047 reads:

if bs.StreamStatus == "streaming" || s.bodyHasUnconfirmedSession(n.ID) || xrEngagedState(bs.XRState) ||
   n.XRSession != nil || st.SignageBodyClaimed(n.ID) || bodyReservedForOtherHead(st, n.ID, headID) {
    streamCount = 1
}

So occupancy is currently decided by: slotClaims, the slot lease, bodyReservedForOtherHead (head_reservations.go:27, over the node fields HeadBodyID/LiveBodyID), SignageBodyClaimed, bodyHasUnconfirmedSession, and the body's own StreamStatus/XR fields.

The part that breaks multi-slot outright

stream_count is body-wide and boolean. Every one of those six conditions collapses to streamCount = 1 for the WHOLE body, and the comment immediately above it says:

old flat heads only pick bodies with stream_count == 0

So the moment slot 0 starts streaming, a two-slot body reports stream_count=1, and any head that gates on stream_count == 0 skips it even though slot 1 is free. The same is true of bodyReservedForOtherHead, which returns true if ANY other head has HeadBodyID == bodyID, or LiveBodyID == bodyID while online. It has no notion of slots at all.

free_slots was added beside stream_count but nothing retired stream_count, so the two now answer the same question at different granularities, body-wide and per-slot, and they disagree the moment a multi-slot body is in use.

The iPad path evidently reads free_slots, because three iPads streamed concurrently from cosmic on 2026-10-17. Whether a given flat head can use a second slot therefore depends on which field its version gates on, which is not something the cluster can see or control.

What this means for the options

It strengthens option 4 further and widens it. Re-keying slotClaims fixes which lane a head is told; it does nothing about a body that advertises itself as fully occupied the moment one of its slots is in use. Whatever becomes authoritative has to answer "is this body free" per slot, and stream_count has to become derived from it rather than a seventh independent answer.

Suggest this is settled as part of the same decision rather than after it, since fixing the keying alone would leave multi-slot still unreachable for any head that trusts stream_count.

Nothing implemented.

api 18 Oct 2026 16:34

free_slots cannot be used by a client as it stands, for two separate reasons. Both found by trying to act on the previous comment and getting it wrong.

1. Its meaning depends on body topology the client cannot see

slotclaims.go:108:

if len(ports) <= 1 {
    // One lane, and the cluster has never rationed it. Reporting 1 keeps
    // a single-slot body looking exactly as it does today.
    return 1
}

So free_slots == 1 means one of three different things: a free single-slot body, a busy single-slot body, or a multi-slot body with one lane left. The payload does not say which, because it carries no slot count.

Measured on chunky-turnip-23 (single-slot) by the #771 session: stream_count moved 1 to 0 when a stream ended while free_slots stayed at 1 throughout.

The practical consequence: advice to gate a head on free_slots > 0 instead of stream_count == 0 is unsafe, because it makes every busy single-slot body look available, and nearly every body in the fleet is single-slot. That advice was mine and it was wrong.

The safe condition against today's payload is:

usable = streamCount == 0 || freeSlots >= 2

freeSlots >= 2 is unambiguous, since only a multi-slot body can report it. The cost is that "multi-slot with exactly one lane free" stays unreachable, which lands specifically on two-slot bodies like boom-pickle-38: with slot 0 streaming it reports free_slots=1 and is excluded, while cosmic-pretzel-98 reports 2 and is not.

2. It is not derived from occupancy at all

Worse, and independent of the above. FreeSlots never consults StreamStatus, the lease, or any other occupancy source. It counts only lanes that no OTHER head holds a live claim on:

taken := make(map[int]bool)
for id, cl := range c.claims {
    if id != headID && cl.bodyID == bodyID { taken[cl.port] = true }
}

So free_slots means "lanes not currently claimed", not "lanes available", and the two diverge whenever a claim is missing or has landed on the wrong body. That is exactly what cosmic showed at 16:22 UTC: free_slots=3 while stream_count=1 and a head was actively streaming on it.

Requirement for whatever becomes authoritative

  • free_slots must have ONE meaning across topologies. Either every body reports its real free lane count including single-slot bodies reporting 0 when busy, or the payload carries the slot count so a client can interpret it.
  • It must be derived from actual occupancy, not from the claim table alone.
  • stream_count must become derived from the same source rather than remaining an independent body-wide boolean.

Until then a client cannot gate on free_slots without knowing a body's topology first, which it has no way to learn.

Known limitation recorded

The Android head gates on streamCount == 0 (HydraState.kt:1079 and :1086) and does not parse free_slots, so it cannot use a partially-used multi-slot body. Recorded as a limitation rather than changed, because moving a client gate against a field that is mid-rewrite would test it against a moving target.

api 18 Oct 2026 17:17

Re-evaluation against v2.0.131, which is now deployed

Everything below was re-checked against 6b6f3c8 (v2.0.131, Hold a streaming head's lane by occupancy, not by polling), not the v2.0.130 tree the earlier comments used.

This bug defeats the v2.0.131 fix

Refresh will not fire for any head that lists more than one multi-slot body:

existing, ok := c.claims[headID]
if !ok || existing.bodyID != bodyID { return false }

The claim was overwritten onto the last body in the listing loop, so when the head heartbeats liveBodyID for the body it is ACTUALLY streaming on, the bodyID does not match, Refresh returns false, and the lane in use is never held. 95 seconds later it lapses and is offered to the next head, which joins the running session through the unchecked /resume. That is precisely the fault v2.0.131 was written to stop, reached by a different route.

Nothing relevant changed in v2.0.131: claims is still map[string]slotClaim keyed by head id (slotclaims.go:46) and Claim is still called per body inside the loop (handlers_api.go:1072).

Timeline. boom-pickle-38 began reporting two ports at 16:10 UTC under #829, creating the second claim writer. v2.0.131 was committed 17:08 UTC. The fix shipped into a fleet that already had the condition that defeats it.

Second gap, independent of the keying

Refresh only EXTENDS an existing claim. It never creates one. If the claim lapses before the first heartbeat carrying both liveBodyID and status == "streaming", the lane is gone for the remainder of that stream and nothing can recover it, because the iPad head lists exactly once per stream (AppState.swift:314). The exposure window is the 95s TTL against stream-start plus first qualifying heartbeat.

Measurement, 17:14 UTC against deployed 2.0.131

cosmic-pretzel-98  stream_count=1  free_slots=3     <- two heads in status=streaming
boom-pickle-38     stream_count=0  free_slots=2

Three lanes reported free on a body with streams running.

Caveat, stated because it limits the inference: the heads API does not serialise live_body_id, so I could NOT confirm from outside whether the heartbeat path reaches Refresh at all. It is not safe to conclude from this that heads are failing to send body_id. The measurement is consistent with the overwrite, with a lapsed-then-unrecoverable claim, or with the heartbeat not carrying a body id, and it does not distinguish them.

The owner ruling that settles the design question

2026-10-18: cross-venue body use is intended when the owner matches (#832, closed as not-a-bug). Every head in bxl1 shares owner=visit.flanders, so every head lists every body in the district by design.

That removes the last defence of claiming-during-listing. A head listing several bodies is not an edge case to be tolerated, it is the designed behaviour, so taking a hold on each listed body is structurally wrong. Options 1 and 2 from the original comment are both dead: option 1 (key by head+body) makes a head hold a lane on every body it can see, which is now guaranteed rather than incidental; option 2 (claim the top-ranked body) cannot survive a head that fails over.

Recommendation

The author of slotclaims.go has independently proposed folding slot-port allocation into the lease and retiring slotclaims, with this sequencing:

  1. v2.0.131, already deployed
  2. add stream_port to the lease grant, reusing the existing allocation logic (cluster-only, additive)
  3. teach the iPad to take, renew and release a lease, falling back to eligible when leases are absent
  4. delete slotclaims and the eligible stream_port / free_slots fields

I agree with the destination and the sequencing. The lease is the right survivor: it is durable where slotclaims dies with the process (a restart to deploy v2.0.129 silently dropped every claim mid-stream), it carries the Moonlight client identity, and it has a real lifecycle with a start deadline. What should move into it is the allocation logic that is already correct and tested: lowest-port-first so slot 0 stays stock, the 100 stride, junk and duplicate rejection.

One amendment. Step 2 is additive and safe, but it does not fix this bug, and step 3 is an iPad release. Until step 3 ships, the iPad path still depends on slotclaims, so the overwrite stays live for every head in the district for as long as that takes. Either step 2 should be paired with a minimal keying fix to carry the gap, or the exposure should be accepted deliberately and written down, not left implicit.

Second amendment. free_slots must not move into the lease unchanged. As detailed above it has two defects: its meaning depends on a body's topology, which the client cannot see, and it is computed from the claim table rather than from occupancy. Carrying it over as-is would make the new mechanism inherit both.

What is NOT recommended

An in-place fix to the keying as the final answer. It would make two allocators disagree more precisely rather than less, and there are eight answers to "is this body free" across the two of them already.