Skip to content
go-libfossil Artifact [e72e2351dd]
Login

Artifact [e72e2351dd]

Artifact e72e2351ddecb14d0a609b357015341577184ee707e359af269bdda9de4bbeaa:


package conformance

import (
	"context"
	"fmt"
	"net/http/httptest"
	"os"
	"path/filepath"
	"slices"
	"strings"
	"testing"
	"time"

	"github.com/danmestas/go-libfossil/internal/cone"
	"github.com/danmestas/go-libfossil/internal/deck"
	libfossil "github.com/danmestas/go-libfossil/internal/fsltype"
	"github.com/danmestas/go-libfossil/internal/horizon"
	"github.com/danmestas/go-libfossil/internal/manifest"
	"github.com/danmestas/go-libfossil/internal/repo"
	"github.com/danmestas/go-libfossil/internal/sync"
	"github.com/danmestas/go-libfossil/internal/xfer"
)

var (
	horizonHeldClient  = Case{ID: "horizon.6.1.held-entries-client", Req: "HZ-6.1-3"}
	horizonHeldOrigin  = Case{ID: "horizon.6.2.served-set-origin", Req: "HZ-6.2-22"}
	horizonNameTieDrop = Case{ID: "horizon.6.2.7.mtime-tie-ancestry", Req: "HZ-6.2-23"}
)

func horizonHeldCases() []Case {
	return []Case{horizonHeldClient, horizonHeldOrigin, horizonNameTieDrop}
}

func TestHorizonHeld(t *testing.T) {
	check(t, horizonHeldClient, func(t *testing.T) error { return hzHeldClient(t) })
	check(t, horizonHeldOrigin, func(t *testing.T) error { return hzHeldOrigin(t) })
	check(t, horizonNameTieDrop, func(t *testing.T) error { return hzNameTieAncestry(t) })
}

// hzHeldGraph sets up c1 -> c2 -> c3 (C) -> c4, plus a childless branch
// `side` forked at c2 so under the leaves rule K initially includes {c2, c3,
// c4, side} and c2 is an entry of K. Merging `side` into c4 later makes `side`
// non-childless, so K shrinks to {c3, c4, merge} unless the clone states c2
// via pragma horizon-held.
type hzHeldGraph struct {
	f              *scRepo
	c1, c2, c3, c4 libfossil.FslID
	side           libfossil.FslID
	c2UUID, c3UUID string
	sideUUID       string
}

func newHZHeldGraph(t *testing.T) *hzHeldGraph {
	t.Helper()
	f := newSCSyncRepo(t, scSyncFiles())
	g := &hzHeldGraph{f: f, c1: f.c1}
	g.c2 = hzCommit(t, f, "c2", []libfossil.FslID{g.c1}, nil)
	g.c3 = hzCommit(t, f, "c3", []libfossil.FslID{g.c2}, nil)
	g.c4 = hzCommit(t, f, "c4", []libfossil.FslID{g.c3}, nil)
	g.side = hzCommit(t, f, "side1", []libfossil.FslID{g.c2}, hzBranch("side"))
	g.c2UUID = hzUUID(t, f.r, g.c2)
	g.c3UUID = hzUUID(t, f.r, g.c3)
	g.sideUUID = hzUUID(t, f.r, g.side)
	return g
}

type hzHeldTap struct {
	inner    sync.Transport
	requests []*xfer.Message
}

func (p *hzHeldTap) Exchange(ctx context.Context, req *xfer.Message) (*xfer.Message, error) {
	p.requests = append(p.requests, req)
	return p.inner.Exchange(ctx, req)
}

// hzHeldClient verifies HZ-6.1-3: a structural clone states its held entries
// via pragma horizon-held, receives new children of a branch K lost when a
// childless check-in gained a child, keeps branch tags seeded, omits C, and
// drops its cursor if held entries change.
func hzHeldClient(t *testing.T) error {
	g := newHZHeldGraph(t)
	h, err := cone.NewHorizon(g.c3UUID, cone.RuleLeaves, cone.DepthStructural)
	if err != nil {
		return err
	}
	sc, err := cone.NewWithHorizon(nil, nil, h)
	if err != nil {
		return err
	}
	rec := &hzHeldTap{inner: &scSyncPeer{r: g.f.r}}
	clone, _, err := sync.Clone(context.Background(), filepath.Join(t.TempDir(), "c.fossil"),
		rec, sync.CloneOpts{StoreCone: sc, PullPhantoms: true, Origin: "origin"})
	if err != nil {
		return err
	}
	t.Cleanup(func() { clone.Close() })

	// Merge side into c4 (so side is no longer childless and leaves-K loses c2)
	// and commit a new child on side that the clone must still receive.
	hzCommit(t, g.f, "merge-side", []libfossil.FslID{g.c4, g.side}, nil)
	side2 := hzCommit(t, g.f, "side2", []libfossil.FslID{g.side}, nil)
	side2UUID := hzUUID(t, g.f.r, side2)

	rec.requests = nil
	if _, err := sync.Sync(context.Background(), clone, rec, sync.SyncOpts{
		Pull: true, Origin: "origin",
	}); err != nil {
		return err
	}
	if err := checkHeldPragmasSent(rec.requests, g.c2UUID, g.c3UUID); err != nil {
		return err
	}
	if _, err := hzRID(clone, side2UUID); err != nil {
		return expectf("clone did not receive side2 (%.10s) after K lost c2: %v", side2UUID, err)
	}
	return checkBranchTag(clone, side2UUID, "side")
}

func checkHeldPragmasSent(reqs []*xfer.Message, wantEntry, forbidC string) error {
	var seen []string
	for _, req := range reqs {
		for _, vals := range hzPragmas(req, "horizon-held") {
			if len(vals) == 1 {
				seen = append(seen, vals[0])
			}
		}
	}
	if !slices.Contains(seen, wantEntry) {
		return expectf("structural pull did not send pragma horizon-held %.10s (saw %v)",
			wantEntry, seen)
	}
	if slices.Contains(seen, forbidC) {
		return expectf("structural pull sent C (%.10s) as pragma horizon-held", forbidC)
	}
	return nil
}

func checkBranchTag(r *repo.Repo, uuid, wantBranch string) error {
	rid, err := hzRID(r, uuid)
	if err != nil {
		return err
	}
	var got string
	err = r.DB().QueryRow(`SELECT tx.value FROM tagxref tx JOIN tag t ON t.tagid=tx.tagid
		WHERE tx.rid=? AND t.tagname='branch' AND tx.tagtype>0`, rid).Scan(&got)
	if err != nil || got != wantBranch {
		return expectf("branch on %.10s = %q (%v), want %q", uuid, got, err, wantBranch)
	}
	return nil
}

// hzHeldOrigin verifies HZ-6.2-22: origin serves K union descendants of stated
// held entries, ignores unknown hashes and surplus beyond 1024, ignores
// horizon-held on content-level requests, and keys its memo on held entries.
func hzHeldOrigin(t *testing.T) error {
	g := newHZHeldGraph(t)
	hzCommit(t, g.f, "merge-side", []libfossil.FslID{g.c4, g.side}, nil)
	side2 := hzCommit(t, g.f, "side2", []libfossil.FslID{g.side}, nil)
	side2UUID := hzUUID(t, g.f.r, side2)

	// 1. Without horizon-held, descendants-rule at c3 withholds side2.
	noHeld, err := hzAskStructural(g.f.r, g.c3UUID, "descendants", nil)
	if err != nil {
		return err
	}
	if hzAnnounces(noHeld, side2UUID) {
		return expectf("without horizon-held, origin announced side2 (%.10s)", side2UUID)
	}
	// 2. With horizon-held c2 (plus an unknown hash), origin serves side2.
	unknown := strings.Repeat("a", 64)
	withHeld, err := hzAskStructural(g.f.r, g.c3UUID, "descendants", []string{unknown, g.c2UUID})
	if err != nil {
		return err
	}
	if !hzAnnounces(withHeld, side2UUID) {
		return expectf("with horizon-held c2, origin withheld side2 (%.10s)", side2UUID)
	}
	// 3. Re-asking without horizon-held hits the memo under its own key and
	// still withholds side2.
	again, err := hzAskStructural(g.f.r, g.c3UUID, "descendants", nil)
	if err != nil {
		return err
	}
	if hzAnnounces(again, side2UUID) {
		return expectf("memo confused held-entry keys: second no-held request announced side2")
	}
	// 4. Surplus past 1024 entries is ignored (entry #1025 is c2).
	surplus := make([]string, cone.MaxHeldEntries+1)
	for i := 0; i < cone.MaxHeldEntries; i++ {
		surplus[i] = fmt.Sprintf("%064x", i+1)
	}
	surplus[cone.MaxHeldEntries] = g.c2UUID
	capped, err := hzAskStructural(g.f.r, g.c3UUID, "descendants", surplus)
	if err != nil {
		return err
	}
	if hzAnnounces(capped, side2UUID) {
		return expectf("origin honoured horizon-held entry past the 1024 cap")
	}
	// 5. Content-level request ignores horizon-held (no error, serves content).
	pc, err := hzProjectCode(g.f.r)
	if err != nil {
		return err
	}
	contentResp, err := sync.HandleSync(context.Background(), g.f.r, &xfer.Message{Cards: []xfer.Card{
		&xfer.PullCard{ServerCode: pc, ProjectCode: pc},
		&xfer.PragmaCard{Name: "horizon", Values: []string{g.c3UUID, "descendants"}},
		&xfer.PragmaCard{Name: "horizon-held", Values: []string{g.c2UUID}},
	}})
	if err != nil {
		return err
	}
	if len(smCardsOf[*xfer.ErrorCard](contentResp)) != 0 {
		return expectf("content request with horizon-held drew error: %v",
			smCardsOf[*xfer.ErrorCard](contentResp))
	}
	return nil
}

func hzAskStructural(r *repo.Repo, cHash, rule string, held []string) (*xfer.Message, error) {
	pc, err := hzProjectCode(r)
	if err != nil {
		return nil, err
	}
	cards := []xfer.Card{
		&xfer.PullCard{ServerCode: pc, ProjectCode: pc},
		&xfer.PragmaCard{Name: "horizon", Values: []string{cHash, rule}},
		&xfer.PragmaCard{Name: "horizon-structural"},
	}
	for _, h := range held {
		cards = append(cards, &xfer.PragmaCard{Name: "horizon-held", Values: []string{h}})
	}
	cards = append(cards, &xfer.PragmaCard{Name: "horizon-seed", Values: []string{"-"}})
	return sync.HandleSync(context.Background(), r, &xfer.Message{Cards: cards})
}

func hzAnnounces(msg *xfer.Message, uuid string) bool {
	for _, card := range msg.Cards {
		switch c := card.(type) {
		case *xfer.IGotCard:
			if c.UUID == uuid {
				return true
			}
		case *xfer.FileCard:
			if c.UUID == uuid {
				return true
			}
		}
	}
	return false
}

// hzNameTieAncestry verifies HZ-6.2-23: when check-ins tied on event mtime are
// candidates for a name, an ancestor of another tied candidate is dropped
// before lowest full hash decides, both through primary parents and through
// merge parents.
func hzNameTieAncestry(t *testing.T) error {
	if err := hzCheckTieDrop(t, false); err != nil {
		return fmt.Errorf("primary parent tie: %w", err)
	}
	if err := hzCheckTieDrop(t, true); err != nil {
		return fmt.Errorf("merge parent tie: %w", err)
	}
	return nil
}

func hzCheckTieDrop(t *testing.T, viaMerge bool) error {
	f := newSCSyncRepo(t, scSyncFiles())
	sameTime := f.when.Add(2 * time.Hour)
	aRID, aUUID := commitAtTime(t, f.r, "a", []libfossil.FslID{f.c1}, sameTime, nil)
	parents := []libfossil.FslID{aRID}
	if viaMerge {
		other := hzCommit(t, f, "other", []libfossil.FslID{f.c1}, hzBranch("other"))
		parents = []libfossil.FslID{other, aRID}
	}
	// Find a descendant at the exact same timestamp whose full hash sorts
	// strictly HIGHER than aUUID so lowest-hash alone would choose aUUID.
	var bUUID string
	for i := 0; i < 64; i++ {
		name := fmt.Sprintf("child-%d", i)
		var tags []deck.TagCard
		if viaMerge {
			tags = []deck.TagCard{{Type: deck.TagSingleton, Name: "sym-trunk", UUID: "*"}}
		}
		_, u := commitAtTime(t, f.r, name, parents, sameTime, tags)
		if u > aUUID {
			bUUID = u
			break
		}
	}
	if bUUID == "" {
		return expectf("failed to find child with hash > %.10s", aUUID)
	}
	got, err := horizon.ResolveName(f.r.DB(), "trunk", 0)
	if err != nil {
		return err
	}
	if got.Hash == aUUID {
		return expectf("ResolveName picked ancestor %.10s over higher-hash descendant %.10s",
			aUUID, bUUID)
	}
	tip, err := horizon.ResolveName(f.r.DB(), horizon.NameTip, 0)
	if err != nil {
		return err
	}
	if tip.Hash == aUUID {
		return expectf("ResolveName(tip) picked ancestor %.10s over descendant", aUUID)
	}
	return nil
}

func commitAtTime(
	t *testing.T, r *repo.Repo, name string, parents []libfossil.FslID,
	when time.Time, tags []deck.TagCard,
) (libfossil.FslID, string) {
	t.Helper()
	rid, uuid, err := manifest.Checkin(r, manifest.CheckinOpts{
		Files:        []manifest.File{{Name: name, Content: []byte(name + "\n")}},
		Comment:      name,
		User:         "u",
		Parent:       parents[0],
		MergeParents: parents[1:],
		Time:         when,
		Tags:         tags,
	})
	if err != nil {
		t.Fatal(err)
	}
	return rid, uuid
}

// TestZitHorizonHeldInterop verifies pragma horizon-held against live zit
// 0.14.22 in both directions: a go-libfossil structural clone pulling from zit
// and a zit structural clone pulling from go-libfossil after leaves-K loses
// an entry.
func TestZitHorizonHeldInterop(t *testing.T) {
	bin := zitHorizonBinary(t)
	g := newHZHeldGraph(t)
	dir := t.TempDir()
	home := filepath.Join(dir, "home")
	if err := os.Mkdir(home, 0o755); err != nil {
		t.Fatal(err)
	}
	origin := httptest.NewServer(sync.XferHandler(g.f.r, sync.HandleSync))
	defer origin.Close()

	zclone := filepath.Join(dir, "zclone")
	zitRun(t, bin, home, dir, "clone", origin.URL, zclone, "--no-open", "--once",
		"--horizon="+g.c3UUID, "--horizon-rule=leaves", "--structural")

	hzCommit(t, g.f, "merge-side", []libfossil.FslID{g.c4, g.side}, nil)
	side2 := hzCommit(t, g.f, "side2", []libfossil.FslID{g.side}, nil)
	side2UUID := hzUUID(t, g.f.r, side2)

	out, err := zitCommand(bin, home, zclone, "pull", origin.URL)
	if err != nil {
		// zit exits 9 when a pull introduces an open fork; that's still success.
		if !strings.Contains(out, "exit status 9") && !strings.Contains(err.Error(), "exit status 9") {
			t.Fatalf("zit pull failed: %v\n%s", err, out)
		}
	}
	info, err := zitCommand(bin, home, zclone, "info", side2UUID)
	if err != nil {
		t.Fatalf("zit clone did not receive side2 (%.10s): %v\n%s", side2UUID, err, info)
	}
}