Skip to content

Commit f82dd16

Browse files
author
Uwe Schwaeke
committed
fix: round-9 review — dead failure check, vacuous pin, unshelve restarts its guest
Round 9 reviewed the round-8 fixes themselves and found two real defects in them, a product gap the round-8 guard newly exposed, and one product bug a full run caught by losing a race — all fixed: - run.sh's report_write failure check was dead code: '|| failed=1' wrote a GLOBAL (the 'local failed=0' came later and re-initialized it), so an unwritable results dir with a healthy JSONL still exited 0 green. The declaration is hoisted above the call and verified with an isolated replica of the exact structure. - TestAddImageTagEvictsCache was vacuous: the tag was a substring of the image name, so the assertion matched every response, tagged or not — proven by deleting the eviction and watching the test pass. The tag is now distinct and the assertion is the exact tags array; both eviction pins now fail with the eviction removed. - CreatePort persisted fixed_ips with a BLANK ip_address for pools the round-8 allocateIP guard refuses (/29-/30, the IPv6 overflow) — the 500 had become silent bad data. It is a clean 400 now, pinned by a test that also asserts nothing was persisted. - unshelve never restarted the guest shelve stopped: the record said ACTIVE over a stopped guest, and the state reconciler (whose job is exactly that correction) flipped it back to SHUTOFF within one 30s sweep — 'server unshelve' observably did nothing, and the conformance case failed whenever the sweep won the race. Unshelve now starts the guest BEFORE writing ACTIVE (winning the reconciler's compare-and-set by construction: a SHELVED row is never a candidate), self-healing via reviveGuest like os-start when the domain is gone. Pinned by TestUnshelveRestartsGuest; the full run now logs zero guest-off corrections where it logged one. - Migration 077 makes volumes.project_id and ports.project_id NOT NULL: both are scanned into plain strings by the ownership labels round 8 added, and no writer can produce NULL — which is exactly why the invariant belongs in the schema. One metadata test fixture inserted a NULL port directly; it binds the seeded project now. - Harness polish from the same round: a half-started compose stack no longer outlives a failed startup (teardown before the exit 2 — the trap is not installed yet at that point), the zero-suite error no longer interpolates an array that is necessarily empty, the cache tests' Redis cleanup actually matches its keys (DeletePattern prepends the prefix — a prefixed pattern doubled it and matched nothing), and neutron's dead 'networks:*' eviction patterns are gone (only network:<project>:<id> keys are ever written). Verified at this HEAD: full run 249 pass / 0 fail / 2 known-failing / 0 skipped, exit 0, zero reconciler corrections; coverage gate PASSED; full internal Go suite green. Signed-off-by: Uwe Schwaeke <uwe.schwaeke@sap.com>
1 parent c7e167a commit f82dd16

10 files changed

Lines changed: 198 additions & 19 deletions

File tree

‎internal/glance/spec028_round8_test.go‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,10 @@ func newGlanceCacheRouter(t *testing.T) (*gin.Engine, *cache.Cache) {
3131
t.Skipf("no local Redis for the cache regression: %v", err)
3232
}
3333
t.Cleanup(func() {
34-
cacheInst.DeletePattern(context.Background(), "spec028-r8glance:*")
34+
// DeletePattern prepends the instance's KeyPrefix itself, so the
35+
// pattern is just "*" — a prefixed pattern would double the prefix
36+
// and match nothing (round 9).
37+
cacheInst.DeletePattern(context.Background(), "*")
3538
})
3639

3740
gin.SetMode(gin.TestMode)
@@ -61,7 +64,11 @@ func TestAddImageTagEvictsCache(t *testing.T) {
6164
r, _ := newGlanceCacheRouter(t)
6265

6366
hdr := map[string]string{"X-Test-Project": "00000000-0000-0000-0000-000000000002"}
64-
name := "spec028-r8-tag-" + uuid.NewString()[:8]
67+
// The tag is deliberately NOT a substring of the image name: the first
68+
// version of this test asserted on a tag that matched the name in every
69+
// response, so the check passed with the eviction deleted (round 9).
70+
name := "spec028-r8-addtag-" + uuid.NewString()[:8]
71+
const tag = "round8-evict-pin"
6572
code, body := doReqBody(r, http.MethodPost, "/images",
6673
`{"name":"`+name+`","disk_format":"raw","container_format":"bare"}`, hdr)
6774
if code != http.StatusCreated {
@@ -83,18 +90,19 @@ func TestAddImageTagEvictsCache(t *testing.T) {
8390
if code, body := doReq(r, http.MethodGet, "/images/"+imageID, hdr); code != http.StatusOK {
8491
t.Fatalf("prime show: code=%d body=%s", code, body)
8592
}
86-
code, body = doReq(r, http.MethodPut, "/images/"+imageID+"/tags/spec028-r8-tag", hdr)
93+
code, body = doReq(r, http.MethodPut, "/images/"+imageID+"/tags/"+tag, hdr)
8794
if code != http.StatusNoContent {
8895
t.Fatalf("add tag: code=%d body=%s; want 204", code, body)
8996
}
9097

9198
// The follow-up show must see the tag — a stale cache would answer the
92-
// primed body with tags: [].
99+
// primed body with tags: []. The assertion is the exact single-element
100+
// array: a loose substring could match unrelated response fields.
93101
code, body = doReq(r, http.MethodGet, "/images/"+imageID, hdr)
94102
if code != http.StatusOK {
95103
t.Fatalf("post-tag show: code=%d body=%s", code, body)
96104
}
97-
if !strings.Contains(body, "spec028-r8-tag") {
105+
if !strings.Contains(body, `"tags":["`+tag+`"]`) {
98106
t.Errorf("post-tag show does not see the tag — cache not evicted: %s", body)
99107
}
100108
}
@@ -135,7 +143,8 @@ func TestDeleteImageTagEvictsCache(t *testing.T) {
135143
if code != http.StatusOK {
136144
t.Fatalf("post-untag show: code=%d body=%s", code, body)
137145
}
138-
if strings.Contains(body, "spec028-r8-gone") {
146+
// Exact-array form, symmetric with the add-tag pin above.
147+
if strings.Contains(body, `"tags":["spec028-r8-gone"]`) {
139148
t.Errorf("post-untag show still sees the tag — cache not evicted: %s", body)
140149
}
141150
}

‎internal/metadata/identity_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@ func seedGuest(t *testing.T, ip string) string {
3232
ctx := context.Background()
3333
var portID string
3434
if err := testPool.QueryRow(ctx,
35-
`INSERT INTO ports (device_id, device_owner, fixed_ips) VALUES ($1, 'compute:nova', $2::jsonb) RETURNING id`,
36-
id, fmt.Sprintf(`[{"ip_address":%q}]`, ip)).Scan(&portID); err != nil {
35+
`INSERT INTO ports (device_id, device_owner, project_id, fixed_ips) VALUES ($1, 'compute:nova', $2, $3::jsonb) RETURNING id`,
36+
id, seededProjectID, fmt.Sprintf(`[{"ip_address":%q}]`, ip)).Scan(&portID); err != nil {
3737
t.Fatalf("insert port: %v", err)
3838
}
3939
t.Cleanup(func() { testPool.Exec(ctx, "DELETE FROM ports WHERE id=$1", portID) })

‎internal/neutron/network.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1157,9 +1157,10 @@ func (svc *Service) DeleteNetwork(c *gin.Context) {
11571157

11581158
// Invalidate cache. Entries are keyed per caller (networkCacheKey), so evicting this
11591159
// network means evicting every project's view of it, not just the deleter's.
1160+
// (Only `network:<project>:<id>` keys are ever written — networkCacheKey —
1161+
// so this one pattern is the complete eviction.)
11601162
if svc.cache != nil {
11611163
svc.cache.TryDeletePattern(ctx, "network:*:"+id)
1162-
svc.cache.TryDeletePattern(ctx, "networks:*")
11631164
}
11641165

11651166
c.Status(http.StatusNoContent)
@@ -1326,7 +1327,6 @@ func (svc *Service) UpdateNetwork(c *gin.Context) {
13261327
// reason DeleteNetwork's does.
13271328
if svc.cache != nil {
13281329
svc.cache.TryDeletePattern(c.Request.Context(), "network:*:"+networkID)
1329-
svc.cache.TryDeletePattern(c.Request.Context(), "networks:*")
13301330
}
13311331
svc.writeNetworkResponse(c, networkID)
13321332
}

‎internal/neutron/ports.go‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,14 @@ func (svc *Service) CreatePort(c *gin.Context) {
8585

8686
var fixedIPs []map[string]any
8787
if err == nil {
88-
// Allocate IP from subnet
88+
// Allocate IP from subnet. A pool the allocator must refuse (/29-/30,
89+
// IPv6 with its int64 overflow) is a clean 400 — persisting a port
90+
// with a blank ip_address would be silent bad data (round 9).
8991
allocatedIP := allocateIP(cidr)
92+
if allocatedIP == "" {
93+
common.SendError(c, common.NewBadRequestError("subnet's cidr has no usable address for a port"))
94+
return
95+
}
9096
fixedIPs = []map[string]any{
9197
{
9298
"subnet_id": subnetID,

‎internal/neutron/spec028_conformance_test.go‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -686,7 +686,10 @@ func TestGetNetworkCacheDoesNotCrossRoles_DB(t *testing.T) {
686686
t.Skipf("no local Redis for the cache regression: %v", err)
687687
}
688688
t.Cleanup(func() {
689-
cacheInst.DeletePattern(context.Background(), "spec028-cachetest:network:*")
689+
// DeletePattern prepends the instance's KeyPrefix itself, so the
690+
// pattern is just "*" — a prefixed pattern would double the prefix
691+
// and match nothing (round 9).
692+
cacheInst.DeletePattern(context.Background(), "*")
690693
})
691694

692695
ctx := context.Background()
@@ -957,3 +960,53 @@ func TestAllocateIPRefusesUntenablePools(t *testing.T) {
957960
t.Errorf("allocateIP(\"10.0.0.0/24\") = \"\"; want an address")
958961
}
959962
}
963+
964+
// TestCreatePortRefusesUntenablePool — CreatePort on a /30 subnet used to
965+
// persist fixed_ips with a BLANK ip_address once the allocateIP panic guard
966+
// landed (the 500 became silent bad data); the refusal must be a clean 400,
967+
// mirroring AddRouterInterface's handling (SPEC-028, round 9).
968+
func TestCreatePortRefusesUntenablePool(t *testing.T) {
969+
requireDB(t)
970+
ctx := context.Background()
971+
r := newNeutronTestRouter()
972+
hdr := map[string]string{"X-Test-Project": seededProjectID, "X-Test-Roles": "member"}
973+
974+
code, body := doReqBody(r, http.MethodPost, "/v2.0/networks",
975+
`{"network":{"name":"spec028-r9-tiny-net"}}`, hdr)
976+
if code != http.StatusCreated {
977+
t.Fatalf("create network: code=%d (body=%s)", code, body)
978+
}
979+
var net struct {
980+
Network struct {
981+
ID string `json:"id"`
982+
} `json:"network"`
983+
}
984+
if err := json.Unmarshal([]byte(body), &net); err != nil {
985+
t.Fatalf("unmarshal network: %v (body=%s)", err, body)
986+
}
987+
t.Cleanup(func() {
988+
testPool.Exec(ctx, "DELETE FROM ports WHERE network_id=$1", net.Network.ID)
989+
testPool.Exec(ctx, "DELETE FROM subnets WHERE network_id=$1", net.Network.ID)
990+
testPool.Exec(ctx, "DELETE FROM networks WHERE id=$1", net.Network.ID)
991+
})
992+
993+
code, body = doReqBody(r, http.MethodPost, "/v2.0/subnets",
994+
`{"subnet":{"name":"spec028-r9-tiny-sub","network_id":"`+net.Network.ID+`","cidr":"10.198.0.0/30","ip_version":4}}`, hdr)
995+
if code != http.StatusCreated {
996+
t.Fatalf("create /30 subnet: code=%d (body=%s)", code, body)
997+
}
998+
999+
code, body = doReqBody(r, http.MethodPost, "/v2.0/ports",
1000+
`{"port":{"network_id":"`+net.Network.ID+`","name":"spec028-r9-tiny-port"}}`, hdr)
1001+
if code != http.StatusBadRequest {
1002+
t.Errorf("port create on /30 subnet: code=%d body=%s; want 400 (no usable address)", code, body)
1003+
}
1004+
// And nothing was persisted.
1005+
var n int
1006+
if err := testPool.QueryRow(ctx, "SELECT count(*) FROM ports WHERE network_id=$1", net.Network.ID).Scan(&n); err != nil {
1007+
t.Fatalf("count ports: %v", err)
1008+
}
1009+
if n != 0 {
1010+
t.Errorf("port create on /30 subnet persisted %d row(s) despite the 400", n)
1011+
}
1012+
}

‎internal/nova/advanced_actions.go‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"time"
1010

1111
"github.com/cobaltcore-dev/lightstack/internal/common"
12+
"github.com/cobaltcore-dev/lightstack/pkg/hypervisor"
1213
"github.com/gin-gonic/gin"
1314
"github.com/google/uuid"
1415
"github.com/jackc/pgx/v5"
@@ -289,11 +290,13 @@ func (svc *Service) ShelveInstance(c *gin.Context, instanceID, projectID string)
289290
func (svc *Service) UnshelveInstance(c *gin.Context, instanceID, projectID string) {
290291

291292
// Get instance
293+
var domainScan *string
292294
var status string
293295
err := svc.pool.QueryRow(c.Request.Context(),
294-
"SELECT status FROM instances WHERE id = $1 AND project_id = $2",
296+
"SELECT COALESCE(libvirt_domain_id, ''), status FROM instances WHERE id = $1 AND project_id = $2",
295297
instanceID, projectID,
296-
).Scan(&status)
298+
).Scan(&domainScan, &status)
299+
libvirtDomainID := guestDomain(domainScan)
297300

298301
if errors.Is(err, pgx.ErrNoRows) {
299302
common.SendError(c, common.NewNotFoundError("instance"))
@@ -324,6 +327,37 @@ func (svc *Service) UnshelveInstance(c *gin.Context, instanceID, projectID strin
324327
return
325328
}
326329

330+
// Restart the guest shelve stopped — BEFORE the record claims ACTIVE. The
331+
// state reconciler exists to correct records that disagree with the
332+
// hypervisor, so a record written ACTIVE over a stopped guest was flipped
333+
// back to SHUTOFF within one 30s sweep: `server unshelve` observably did
334+
// nothing (SPEC-028, round 9). Starting first also wins the reconciler's
335+
// compare-and-set by construction: a SHELVED row is never a reconcile
336+
// candidate, and once the guest is up no verdict disagrees with ACTIVE.
337+
// A domain that has gone missing since the shelve self-heals the way
338+
// os-start does (FR-025) rather than answering 202 over nothing.
339+
if svc.vmManager != nil && libvirtDomainID != "" {
340+
ctx, cancel := context.WithTimeout(c.Request.Context(), common.LifecycleResponseSlack)
341+
defer cancel()
342+
if err := svc.vmManager.StartVM(ctx, libvirtDomainID); err != nil {
343+
if !errors.Is(err, hypervisor.ErrDomainNotFound) {
344+
sendLifecycleError(c, "unshelve", err)
345+
return
346+
}
347+
healedDomain, herr := svc.reviveGuest(ctx, instanceID)
348+
if herr != nil {
349+
// The record must not go on claiming the server runs (FR-025c).
350+
svc.persistRunState(c, instanceID, projectID, "ERROR", 0, "")
351+
log.Error().Err(herr).Str("instance_id", instanceID).
352+
Msg("unshelve self-heal failed; the server has no guest and could not be given one")
353+
common.SendError(c, common.NewOperationConflictError("unshelve",
354+
"the server's guest is absent and could not be re-created"))
355+
return
356+
}
357+
svc.recordSelfHeal(c, instanceID, projectID, healedDomain)
358+
}
359+
}
360+
327361
// Update status to ACTIVE
328362
_, err = svc.pool.Exec(c.Request.Context(), `
329363
UPDATE instances

‎internal/nova/spec028_conformance_test.go‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@ import (
99
"net/http"
1010
"strings"
1111
"testing"
12+
"time"
1213

14+
"github.com/cobaltcore-dev/lightstack/pkg/hypervisor"
1315
"github.com/google/uuid"
1416
)
1517

@@ -254,3 +256,53 @@ func TestServerGroupDuplicateName409(t *testing.T) {
254256
t.Errorf("rows for (%s, %s) = %d; want exactly 1", seededProjectID, name, n)
255257
}
256258
}
259+
260+
// TestUnshelveRestartsGuest — shelve stops the guest; unshelve only wrote
261+
// ACTIVE to the record and never started it again, so the state reconciler
262+
// (whose whole job is correcting records that disagree with the hypervisor)
263+
// flipped the unshelved server back to SHUTOFF within one 30s sweep:
264+
// `server unshelve` observably did nothing. Upstream's unshelve boots the
265+
// restored instance; the guest must be up before the record claims ACTIVE
266+
// (SPEC-028, round 9 — caught by a full run losing the race).
267+
func TestUnshelveRestartsGuest(t *testing.T) {
268+
requireDB(t)
269+
_, r, mgr := newLifecycleService(t)
270+
id, domainID := seedLifecycleInstance(t, mgr, "spec028-r9-unshelve")
271+
hdr := lifecycleHdr()
272+
action := func(name string) (int, string) {
273+
return doReq(r, http.MethodPost, "/v2.1/servers/"+id+"/action",
274+
`{"`+name+`":null}`, hdr)
275+
}
276+
277+
if code, body := action("shelve"); code != http.StatusAccepted {
278+
t.Fatalf("shelve: code=%d body=%s; want 202", code, body)
279+
}
280+
// The record flips synchronously; the guest stop is asynchronous — wait
281+
// for the hypervisor to agree before unshelving, so the pin is about
282+
// unshelve's start, not shelve's stop timing.
283+
deadline := time.Now().Add(5 * time.Second)
284+
for {
285+
if status, _ := readInstanceState(t, id); status == "SHELVED" {
286+
if run, err := mgr.GuestRunState(t.Context(), domainID); err == nil && run == hypervisor.RunStateDown {
287+
break
288+
}
289+
}
290+
if time.Now().After(deadline) {
291+
t.Fatalf("shelve never stopped the guest (status=%s)", func() string { s, _ := readInstanceState(t, id); return s }())
292+
}
293+
time.Sleep(50 * time.Millisecond)
294+
}
295+
296+
if code, body := action("unshelve"); code != http.StatusAccepted {
297+
t.Fatalf("unshelve: code=%d body=%s; want 202", code, body)
298+
}
299+
300+
// The guest must be up — a record claiming ACTIVE over a stopped guest
301+
// is exactly what the reconciler exists to correct.
302+
if run, err := mgr.GuestRunState(t.Context(), domainID); err != nil || run != hypervisor.RunStateUp {
303+
t.Errorf("guest run state after unshelve = %v (err=%v); want up — unshelve must restart the guest shelve stopped", run, err)
304+
}
305+
if status, power := readInstanceState(t, id); status != "ACTIVE" || power != 1 {
306+
t.Errorf("instance state after unshelve = %s/%d; want ACTIVE/1", status, power)
307+
}
308+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
-- Reverts 077: the ownership-label invariant goes back to conventional
2+
-- (every writer binds the auth-context project) instead of structural.
3+
4+
ALTER TABLE volumes ALTER COLUMN project_id DROP NOT NULL;
5+
ALTER TABLE ports ALTER COLUMN project_id DROP NOT NULL;
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
-- Defense in depth for the ownership labels the cross-project listings and
2+
-- shows render: volumes.project_id and ports.project_id are scanned into
3+
-- plain strings, so a NULL would 500 the show and silently drop the row from
4+
-- the listing. No writer can produce NULL today (every INSERT binds the
5+
-- auth-context project, and an empty string fails the uuid cast), which is
6+
-- exactly why the constraint belongs in the schema: it makes the invariant
7+
-- structural instead of conventional (round 9).
8+
9+
ALTER TABLE volumes ALTER COLUMN project_id SET NOT NULL;
10+
ALTER TABLE ports ALTER COLUMN project_id SET NOT NULL;

‎test/cli/bin/run.sh‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -158,9 +158,10 @@ fi
158158

159159
# A selection that matches nothing must fail loudly, not run zero suites and
160160
# exit 0 — the exact vacuous-green class this harness exists to prevent
161-
# (e.g. `--fast --suite workflows`: the fast pool excludes workflows).
161+
# (e.g. `--fast --suite workflows`: the fast pool excludes workflows). The
162+
# selection is necessarily empty here, so there is nothing to interpolate.
162163
if (( ${#SUITES[@]} == 0 )); then
163-
log_error "--suite '${SUITES[*]:-?}' selected no suites under the current flags (--fast?)"
164+
log_error "the --suite selection matches no suite under the current flags (--fast excludes workflows)"
164165
exit 2
165166
fi
166167

@@ -177,8 +178,15 @@ fi
177178

178179
if ! curl -sf -o /dev/null --max-time 5 "$OS_AUTH_URL"; then
179180
if ! _start_compose_stack; then
181+
# The EXIT trap is not installed yet — anything the failed start left
182+
# behind must be torn down HERE, or a half-started stack (up succeeded,
183+
# readiness never came) would outlive the exit 2.
184+
if (( STARTED_STACK )) && (( ! KEEP_SERVER )); then
185+
(cd "$REPO_ROOT" && docker compose -p lightstack-binary-test -f deployments/docker-compose.binary-test.yml down -v) >/dev/null 2>&1 || true
186+
fi
180187
cat >&2 <<EOF
181-
[cli] ERROR: no lightstack server at $OS_AUTH_URL and no docker to start one.
188+
[cli] ERROR: no lightstack server at $OS_AUTH_URL, and starting one failed
189+
(docker missing, build failed, or the stack never became ready — see above).
182190
183191
Either start a server yourself:
184192
make build && make run
@@ -204,7 +212,10 @@ export CLI_RUNNER_ACTIVE=1
204212
source "$CLI_ROOT/lib/fixtures.sh"
205213

206214
cleanup() {
207-
local rc=$?
215+
# failed is declared HERE, before report_write's check below — a later
216+
# `local failed=0` would shadow an earlier assignment made while the
217+
# variable was still global, silently disabling the check (round 9).
218+
local rc=$? failed=0
208219
trap - EXIT INT TERM
209220
if (( ! NO_CLEANUP )); then
210221
fixtures_teardown || true
@@ -218,7 +229,6 @@ cleanup() {
218229
# it used to run after `rm -rf` and always saw a missing file, which
219230
# the old "missing means clean" reading silently absorbed (failure
220231
# detection at exit was dead code). Now it genuinely gates the exit.
221-
local failed=0
222232
if (( rc == 0 )) && report_failed; then
223233
failed=1
224234
fi

0 commit comments

Comments
 (0)