Artifact f2ab683cf5ec8e1cfbabe4fe5e1119d5ea24ed30042145371a451308ca5c3869:
- File
internal/verify/rebuild_fossil_test.go
— part of check-in
[d810a8118f]
at
2026-10-18 20:01:53
on branch main
— fix: handle time exactly as fossil does (#442)
* fix(manifest): round a caller's check-in and tag time as fossil does
Fossil reads a --date-override through SQLite's strftime, which rounds the seconds to the millisecond (holding a fraction past .999 in its second) rather than truncating them. A caller time finer than a millisecond now gets the D card fossil would write for it; the default clock time is still truncated, as fossil reads its clock.
fsltype.CardTime and CardTimeNow are the one place both rules live, and the checkout commit path and branch creation take their default time through them.
* fix(repo): stamp config and user rows in seconds since 1970
Fossil writes config.mtime and user.mtime with its now() SQL function, time(0). SetConfig, SetHashPolicy and CreateUser wrote julianday('now') instead, so fossil read those rows as dating from 1970 when comparing times in a configuration merge, and SetCaps and SetPassword left the user's mtime alone where fossil's user command restamps it.
* fix(auth): read and write user.cexpire as a Julian day
Fossil keeps user.cexpire as a Julian day (src/login.c). A sync login parsed it as RFC 3339 or 'YYYY-MM-DD HH:MM:SS' text, so any value fossil had written failed to parse and the login was refused as expired. The expiry is now read through julianday(), which takes both forms, and repo invite --ttl writes a Julian day; its write error is now checked.
* fix(checkout): set file times as fossil's --setmtime does
Fossil's --setmtime gives each unedited file the time of the newest check-in, among the version and its primary ancestors, that recorded the file's content, truncated to whole seconds (mtime_of_manifest_file), and it does so for every unedited file of the version once the checkout is up to date (vfile_check_signature with CKSIG_SETMTIME). SetMTime gave every written file the target check-in's time to the millisecond, and an update left the files it did not write alone.
* fix(stash): keep and show stash and bisect times as fossil does
Fossil stores stash.ctime as julianday('now') and lists it with datetime(ctime); go-libfossil stored CURRENT_TIMESTAMP text, which the two drivers returned in different forms, and showed a fossil-written time as a bare number. bisect's list now shows datetime(event.mtime), as fossil's bisect ls does, instead of the Julian day.
* test(verify): fossil rebuild keeps the times go-libfossil stores
A repository go-libfossil wrote, with check-ins at caller and clock times, a tag and a branch, is rebuilt by the fossil binary, and every check-in event, plink and tagxref time must come back unchanged.
* test(sync): a fossil clone and push agree on every synced time
The fossil binary clones a go-libfossil server, unversioned files included, commits at a time finer than a millisecond and pushes back. Each side derives check-in event, plink and tagxref times from the artifacts itself, and the unversioned time travels on the wire; both repositories must then hold the same values.
* fix(resolve): bound NAME:TIMESTAMP with julianday() as fossil does
Fossil resolves BRANCH:TIMESTAMP with event.mtime<=julianday(BOUND). The bound was computed in the text form event rows hold, so on a millisecond where that form is larger than julianday()'s, a check-in at the bound itself resolved here and not in fossil.
* fix(manifest): round a caller's card time with integer arithmetic
CardTime followed SQLite's printing of the seconds as a double, which is not a well-defined rounding: at exact half-millisecond ties fossil 2.28's SQLite gives .124 for .1245 but .020 for .0195, and other SQLite versions differ again. A caller time is now rounded to the nearest millisecond on its nanoseconds, ties up, held at .999 as fossil holds it. The fossil binary test compares every non-tie value, across second, minute, day and year ends; ties are asserted on their own.
* fix(auth): ignore user.cexpire at sync login, as fossil does
user.cexpire is the expiry of fossil's web-login cookie: fossil sets it at web login, writes 0 at logout, and its sync login (check_login) never reads it. Refusing a sync login on it locked out anyone who had logged into or out of fossil's web UI, or whose cookie had lapsed.
The invite TTL that relied on it now lives in a config row of its own, invite-expire:LOGIN, as a UTC instant checked at sync login; repo invite no longer writes cexpire, and the expiry is no longer written in local time and read as UTC. Deleting a user drops its invite expiry.
Tracked in #441.
* fix(repo): convert Julian config and user mtimes on open
Repositories go-libfossil wrote before config and user rows were stamped in seconds since 1970 still hold Julian days there, which fossil reads as January 1970. Open converts those rows to the seconds they stand for. It checks first and writes only when a row needs it, so it converts once and takes no write lock on an up-to-date repository.
* fix(checkout): set a file no check-in recorded to 1970, as fossil does
With no mlink row for a file's artifact in the version's ancestry, fossil's max(event.mtime) is NULL, which mtime_of_manifest_file reads as 0, so --setmtime sets the file to 1970. SetMTime skipped the file.
* fix(stash): list stashes by creation time, as fossil's stash ls does
fossil stash ls orders by ctime, oldest first. List ordered by stash id, newest first; it now orders by ctime with the id breaking a tie.
* fix(auth): clear a login's invite expiry with the user, atomically
DeleteUser removed the user and its invite expiry in two statements; a failure between them left the user's expiry behind or the user without it. Both now go in one transaction. A user fossil deleted leaves its invite-expire row behind, so CreateUser clears it in the same transaction as the insert; repo invite sets its own expiry afterwards.
The on-open conversion of Julian config and user mtimes is now best-effort: while another connection holds the write lock, Open skips it and a later open converts the rows, instead of failing. (user: [email protected], size: 8718) [annotate] [blame] [check-ins using] [more...]
package verify_test // verify.Rebuild against tables the fossil binary wrote (#258): a repository // made entirely by fossil is copied and rebuilt, and every event, plink and // tagxref row must come back with fossil's values, times bit for bit. import ( "fmt" "io" "os" "os/exec" "path/filepath" "reflect" "runtime" "strings" "testing" "time" "github.com/danmestas/go-libfossil/db" "github.com/danmestas/go-libfossil/internal/branch" "github.com/danmestas/go-libfossil/internal/fsltype" "github.com/danmestas/go-libfossil/internal/manifest" "github.com/danmestas/go-libfossil/internal/repo" "github.com/danmestas/go-libfossil/internal/tag" "github.com/danmestas/go-libfossil/internal/verify" "github.com/danmestas/go-libfossil/simio" "github.com/danmestas/go-libfossil/testutil" ) func fossilCmd(t *testing.T, bin, dir string, args ...string) { t.Helper() cmd := exec.Command(bin, args...) cmd.Dir = dir if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("fossil %s: %v\n%s", strings.Join(args, " "), err, out) } } // fossilHistory commits a few versions with the fossil binary, on trunk and // a branch, and tags one with a value and one without. func fossilHistory(t *testing.T) string { t.Helper() bin := testutil.RequireFossilBin(t) dir := t.TempDir() repoPath := filepath.Join(dir, "f.fossil") ck := filepath.Join(dir, "ck") if err := os.Mkdir(ck, 0o755); err != nil { t.Fatal(err) } fossilCmd(t, bin, dir, "init", repoPath) fossilCmd(t, bin, ck, "open", repoPath) path := filepath.Join(ck, "f.txt") mtime := time.Unix(1_700_000_000, 0) for v := 0; v < 4; v++ { if err := os.WriteFile(path, []byte(fmt.Sprintf("version %d\n", v)), 0o644); err != nil { t.Fatal(err) } mtime = mtime.Add(10 * time.Second) if err := os.Chtimes(path, mtime, mtime); err != nil { t.Fatal(err) } if v == 0 { fossilCmd(t, bin, ck, "add", "f.txt") } args := []string{"commit", "-m", fmt.Sprintf("v%d", v)} if v == 2 { args = append(args, "--branch", "feat") } fossilCmd(t, bin, ck, args...) } fossilCmd(t, bin, ck, "tag", "add", "release", "current") fossilCmd(t, bin, ck, "tag", "add", "note", "current", "with a value") return repoPath } // fossilTextTimesExact reports whether the fossil binary on this machine // writes text times the way TimeToTextJulian computes them: its %.17g runs in // long double, which is a 64-bit double on macOS arm64 and Windows but wider // on Linux and Intel macOS, where the 16th digit can differ. func fossilTextTimesExact() bool { return (runtime.GOOS == "darwin" && runtime.GOARCH == "arm64") || runtime.GOOS == "windows" } // textTime renders a column fossil writes as SQL text: bit for bit where // this machine's fossil computes it as TimeToTextJulian does, otherwise to // the millisecond the value stands for. func textTime(col string) string { if fossilTextTimesExact() { return "printf('%!.20g', " + col + ")" } return "CAST(round((" + col + " - 2440587.5) * 86400000) AS INTEGER)" } // derivedRows reads the derived tables #258 compares, in a stable order. // Tag times are SQLite's julianday() on every platform, so they are compared // bit for bit; see textTime for the others. func derivedRows(t *testing.T, path string) map[string][]string { t.Helper() return queryRows(t, path, map[string]string{ // Check-in events only: Rebuild does not yet recreate the events of // other artifacts (control artifacts, wiki, tickets, forum), a gap // apart from the values #258 is about. "event": "SELECT objid, type, " + textTime("mtime") + ", " + textTime("omtime") + ", user, comment FROM event WHERE type='ci' ORDER BY objid", "plink": "SELECT pid, cid, isprim, " + textTime("mtime") + " FROM plink ORDER BY cid, pid", "tagxref": `SELECT tagid, rid, tagtype, quote(value), printf('%!.20g', mtime) FROM tagxref ORDER BY tagid, rid`, }) } // derivedTimes reads the times fossil derives from the artifacts into // event, plink and tagxref, keyed by the row each belongs to. Events are // check-in events: go-libfossil does not write the event fossil adds for a // tag's control artifact, a missing row apart from the times compared here. func derivedTimes(t *testing.T, path string) map[string][]string { t.Helper() return queryRows(t, path, map[string]string{ "event": "SELECT objid, type, " + textTime("mtime") + ", " + textTime("omtime") + " FROM event WHERE type='ci' ORDER BY objid", "plink": "SELECT pid, cid, " + textTime("mtime") + " FROM plink ORDER BY cid, pid", "tagxref": `SELECT tagid, rid, srcid, origid, printf('%!.20g', mtime) FROM tagxref ORDER BY tagid, rid`, }) } // queryRows runs each named query against the repository at path and // returns its rows, each rendered as one string. func queryRows(t *testing.T, path string, queries map[string]string) map[string][]string { t.Helper() d, err := db.OpenSQL(path, db.OpenConfig{}, nil) if err != nil { t.Fatal(err) } defer func() { if err := d.Close(); err != nil { t.Errorf("close %s: %v", path, err) } }() out := map[string][]string{} for name, q := range queries { rows, err := d.Query(q) if err != nil { t.Fatalf("%s: %v", name, err) } cols, err := rows.Columns() if err != nil { t.Fatal(err) } for rows.Next() { vals := make([]any, len(cols)) ptrs := make([]any, len(cols)) for i := range vals { ptrs[i] = &vals[i] } if err := rows.Scan(ptrs...); err != nil { t.Fatal(err) } out[name] = append(out[name], fmt.Sprint(vals...)) } if err := rows.Err(); err != nil { t.Fatal(err) } if err := rows.Close(); err != nil { t.Fatal(err) } } return out } func copyFile(t *testing.T, from, to string) { t.Helper() src, err := os.Open(from) if err != nil { t.Fatal(err) } defer src.Close() dst, err := os.Create(to) if err != nil { t.Fatal(err) } if _, err := io.Copy(dst, src); err != nil { t.Fatal(err) } if err := dst.Close(); err != nil { t.Fatal(err) } } func TestRebuildMatchesFossilDerivedValues(t *testing.T) { orig := fossilHistory(t) rebuilt := filepath.Join(t.TempDir(), "rebuilt.fossil") copyFile(t, orig, rebuilt) r, err := repo.Open(rebuilt) if err != nil { t.Fatal(err) } if _, err := verify.Rebuild(r); err != nil { t.Fatalf("Rebuild: %v", err) } if err := r.Close(); err != nil { t.Fatal(err) } want, got := derivedRows(t, orig), derivedRows(t, rebuilt) for table := range want { if !reflect.DeepEqual(got[table], want[table]) { t.Errorf("%s after Rebuild:\n %s\nfossil wrote:\n %s", table, strings.Join(got[table], "\n "), strings.Join(want[table], "\n ")) } } } // goTimesHistory commits with go-libfossil at times given to the nanosecond // and at the clock's, tags one check-in and branches from it. func goTimesHistory(t *testing.T) string { t.Helper() path := filepath.Join(t.TempDir(), "g.fossil") r, err := repo.Create(path, "u", simio.CryptoRand{}, "") if err != nil { t.Fatal(err) } defer func() { if err := r.Close(); err != nil { t.Error(err) } }() base := time.Date(2026, 10, 18, 12, 34, 56, 0, time.UTC) times := []time.Time{base.Add(789600 * time.Microsecond), base.Add(time.Minute + 789500*time.Microsecond), {}} var parent fsltype.FslID for i, when := range times { rid, _, err := manifest.Checkin(r, manifest.CheckinOpts{ Files: []manifest.File{{Name: "f.txt", Content: []byte(fmt.Sprintf("v%d\n", i))}}, Comment: fmt.Sprintf("v%d", i), User: "u", Parent: parent, Time: when, }) if err != nil { t.Fatal(err) } parent = rid } if _, err := tag.AddTag(r, tag.TagOpts{TargetRID: parent, TagName: "sym-rel", TagType: tag.TagSingleton, User: "u", Time: base.Add(2*time.Minute + 123456789)}); err != nil { t.Fatal(err) } if _, _, err := branch.Create(r, branch.CreateOpts{Name: "feat", Parent: parent, User: "u"}); err != nil { t.Fatal(err) } return path } // TestFossilRebuildKeepsGoTimes rebuilds a repository go-libfossil wrote with // the fossil binary: every event, plink and tagxref time fossil derives from // the artifacts must be the one go-libfossil stored, bit for bit where this // machine's fossil computes text times as go-libfossil does (textTime). func TestFossilRebuildKeepsGoTimes(t *testing.T) { testutil.RequireFossilBin(t) path := goTimesHistory(t) stored := derivedTimes(t, path) if err := testutil.FossilRebuild(path); err != nil { t.Fatal(err) } rebuilt := derivedTimes(t, path) for table := range stored { if !reflect.DeepEqual(stored[table], rebuilt[table]) { t.Errorf("%s as go-libfossil stored it:\n %s\nafter fossil rebuild:\n %s", table, strings.Join(stored[table], "\n "), strings.Join(rebuilt[table], "\n ")) } } }