Skip to content
quarry Artifact [03f156638b]
Login

Artifact [03f156638b]

Artifact 03f156638b14faec0d17191d782c82f894af0c856bd68e414c217789e63e0cf0:


package ingest

import (
	"context"
	"errors"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"sync/atomic"
	"testing"
	"time"

	"craftdesign.group/quarry/internal/artifact"
	"craftdesign.group/quarry/internal/events"
	"craftdesign.group/quarry/internal/index"
	"craftdesign.group/quarry/internal/zitcli"
)

// A store rewritten under the saved cursor (shun, pack) is rebuilt from
// its census off the lane, the way a missing cursor is; nothing is
// republished through the bus, and the lane slot is gone before the
// rebuild starts (#481).
func TestCursorLossRebuildsOffTheLane(t *testing.T) {
	pipe, ix, repo := testPipeline(t)
	if _, err := pipe.Sync(); err != nil {
		t.Fatal(err)
	}
	head, err := exec.Command("zit", "ls", "--long", "-R", repo, "tip").Output()
	if err != nil {
		t.Fatal(err)
	}
	run(t, repo, "shun", strings.Fields(string(head))[0], "--force")

	s := watchSpans(t)
	var held atomic.Bool
	var heldAtRebuild atomic.Int32 // 1 = slot still held when the rebuild began
	old := rebuildSpan
	rebuildSpan = func(d int) {
		if d > 0 && held.Load() {
			heldAtRebuild.Store(1)
		}
		old(d)
	}
	t.Cleanup(func() { rebuildSpan = old })
	admit := func(body func(leave func()) error) error {
		held.Store(true)
		defer held.Store(false)
		return body(func() { held.Store(false) })
	}
	before := streamMsgs(t, pipe)
	if _, err := pipe.SyncIn(admit); err != nil {
		t.Fatalf("FAIL: round after a rewrite: %v", err)
	}
	if _, in := s.counts(); in != 1 {
		t.Errorf("FAIL: rebuilds started = %d, want 1", in)
	}
	if heldAtRebuild.Load() != 0 {
		t.Errorf("FAIL: the lane slot was still held when the rebuild started")
	}
	if got := streamMsgs(t, pipe); got != before {
		t.Errorf("FAIL: the stream grew from %d to %d messages: the census went through the bus", before, got)
	}
	_ = ix
	if !t.Failed() {
		t.Log("ok")
	}
}

func streamMsgs(t *testing.T, p *Pipeline) uint64 {
	t.Helper()
	info, err := p.ev.JS().StreamInfo(events.StreamName)
	if err != nil {
		t.Fatal(err)
	}
	return info.State.LastSeq
}

// A poll round queued for a lane slot does not hold the store: a write
// op's TrySync gets in, and when the slot comes the round finds the store
// held and skips instead of blocking.
func TestQueuedPollRoundDoesNotHoldTheStore(t *testing.T) {
	pipe, _, _ := testPipeline(t)
	admitted := make(chan struct{})
	release := make(chan struct{})
	admit := func(body func(leave func()) error) error {
		<-release // the lane is full until the test says otherwise
		close(admitted)
		return body(func() {})
	}
	done := make(chan error, 1)
	go func() { _, err := pipe.SyncIn(admit); done <- err }()
	time.Sleep(100 * time.Millisecond) // the poll is queued now

	if _, err := pipe.TrySync(); errors.Is(err, ErrRoundBusy) {
		t.Errorf("FAIL: a queued poll round held the store; TrySync = %v", err)
	}
	if !pipe.mu.TryLock() {
		t.Errorf("FAIL: p.mu held while the poll was queued for the lane")
	} else {
		pipe.mu.Unlock()
	}

	if t.Failed() { // the queued round holds the store; do not wait on it
		close(release)
		<-done
		return
	}
	// Admitted while another round holds the store: skipped, not blocked.
	pipe.mu.Lock()
	close(release)
	select {
	case err := <-done:
		if !errors.Is(err, ErrRoundBusy) {
			t.Errorf("FAIL: a skipped round answered %v, want ErrRoundBusy so the poll does not count the store as read", err)
		}
	case <-time.After(5 * time.Second):
		t.Errorf("FAIL: the admitted round blocked on the held store")
	}
	pipe.mu.Unlock()
	<-admitted
	if !t.Failed() {
		t.Log("ok")
	}
}

// A write that lands while the poll's round is skipped is indexed by the
// next round: the skip is busy, not success.
func TestSkippedPollRoundLeavesTheWriteForTheNext(t *testing.T) {
	pipe, ix, repo := testPipeline(t)
	if _, err := pipe.Sync(); err != nil {
		t.Fatal(err)
	}
	pipe.mu.Lock()
	commitFile(t, repo, "c.txt", "gamma\n", "add c")
	_, err := pipe.SyncIn(func(body func(func()) error) error { return body(func() {}) })
	pipe.mu.Unlock()
	if !errors.Is(err, ErrRoundBusy) {
		t.Fatalf("FAIL: a round skipped for a held store answered %v", err)
	}
	if _, err := pipe.SyncIn(func(body func(func()) error) error { return body(func() {}) }); err != nil {
		t.Fatalf("FAIL: next round: %v", err)
	}
	found := false
	tl, _, terr := ix.Timeline(index.TimelineFilter{Limit: 10, Kind: "ci"})
	if terr != nil {
		t.Fatal(terr)
	}
	for _, e := range tl {
		found = found || e.Comment == "add c"
	}
	if !found {
		t.Errorf("FAIL: the write was not indexed by the round after the skip")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// saturateGate fills the one-wide subprocess gate with an interactive
// call on a zit that holds, so every background call is refused busy
// after its wait. The hold ends with the test.
func saturateGate(t *testing.T, p *Pipeline) {
	t.Helper()
	real, err := exec.LookPath("zit")
	if err != nil {
		t.Skip("zit not on PATH")
	}
	bin := t.TempDir()
	script := fmt.Sprintf("#!/bin/sh\nif [ \"$1\" = ls ]; then exec sleep 30; fi\nexec %q \"$@\"\n", real)
	if err := os.WriteFile(filepath.Join(bin, "zit"), []byte(script), 0o755); err != nil {
		t.Fatal(err)
	}
	t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
	old := zitcli.Parallel()
	zitcli.SetParallel(1)
	ctx, cancel := context.WithCancel(context.Background())
	done := make(chan struct{})
	go func() { defer close(done); p.cli.Ls(ctx, "abc") }()
	t.Cleanup(func() { cancel(); <-done; zitcli.SetParallel(old) })
	time.Sleep(300 * time.Millisecond)
}

// A busy refusal is not an answer: the once-per-process tip check is not
// spent by it, and the dangling-parent probe reports unknown, not "the
// store does not hold it".
func TestBusyRefusalsAreRetriedNotRecordedAsAnswers(t *testing.T) {
	pipe, ix, _ := testPipeline(t)
	if _, err := pipe.Sync(); err != nil {
		t.Fatal(err)
	}
	const ghost = "deadbeef00000000000000000000000000000000000000000000000000000000"
	if _, err := ix.Fold([]index.Parsed{{Hash: "c0ffee0000000000000000000000000000000000000000000000000000000000",
		Art: &artifact.Artifact{Type: artifact.Manifest, Date: "2026-11-14T00:00:00", User: "ana", Parents: []string{ghost}}}}); err != nil {
		t.Fatal(err)
	}
	saturateGate(t, pipe)
	if _, err := pipe.lostArtifacts(); !errors.Is(err, zitcli.ErrBusy) {
		t.Errorf("FAIL: lostArtifacts under a busy gate = %v, want ErrBusy", err)
	}
	pipe.Sync()
	if pipe.tipChecked {
		t.Errorf("FAIL: a busy refusal spent the tip check")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}