Artifact c2dc69a9a46de3e37f1ac13f8788408db250287fa2fbe4fa1d858b7c4ab5d17c:
- File
internal/bisect/bisect.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: 6893) [annotate] [blame] [check-ins using] [more...]
// Package bisect implements binary search through Fossil commit history. // It stores session state in the checkout DB's vvar table and uses BFS // path-finding to locate the midpoint between known-good and known-bad commits. package bisect import ( "database/sql" "errors" "fmt" "math" "strconv" "strings" libfossil "github.com/danmestas/go-libfossil/internal/fsltype" "github.com/danmestas/go-libfossil/internal/path" ) // ErrBisectComplete is returned by Next when the search has converged. var ErrBisectComplete = errors.New("bisect complete") // Session manages a bisect operation, persisting state in the vvar table. type Session struct { db *sql.DB } // StatusInfo describes the current bisect state. type StatusInfo struct { Good libfossil.FslID Bad libfossil.FslID Log string Steps int } // ListEntry describes a single node in the bisect path. type ListEntry struct { RID libfossil.FslID UUID string Date string Label string } // NewSession creates a new bisect session backed by the given checkout DB. func NewSession(db *sql.DB) *Session { if db == nil { panic("bisect.NewSession: db must not be nil") } return &Session{db: db} } // MarkGood records rid as a known-good commit. func (s *Session) MarkGood(rid libfossil.FslID) error { if rid <= 0 { panic("bisect.MarkGood: rid must be positive") } if _, err := s.db.Exec("REPLACE INTO vvar(name,value) VALUES('bisect-good',?)", strconv.FormatInt(int64(rid), 10)); err != nil { return fmt.Errorf("bisect: mark good: %w", err) } return s.appendLog(rid) } // MarkBad records rid as a known-bad commit. func (s *Session) MarkBad(rid libfossil.FslID) error { if rid <= 0 { panic("bisect.MarkBad: rid must be positive") } if _, err := s.db.Exec("REPLACE INTO vvar(name,value) VALUES('bisect-bad',?)", strconv.FormatInt(int64(rid), 10)); err != nil { return fmt.Errorf("bisect: mark bad: %w", err) } return s.appendLog(-rid) } // Skip marks rid as skipped (neither good nor bad). func (s *Session) Skip(rid libfossil.FslID) error { if rid <= 0 { panic("bisect.Skip: rid must be positive") } return s.appendLogEntry(fmt.Sprintf("s%d", rid)) } // Next returns the midpoint commit to test next. // If the bisect has converged, it returns ErrBisectComplete with the bad RID // embedded in the error message. func (s *Session) Next() (libfossil.FslID, error) { good, bad, err := s.loadEndpoints() if err != nil { return 0, err } skip := s.parseSkipSet() p, err := path.Shortest(s.db, good, bad, true, nil) if err != nil { return 0, fmt.Errorf("bisect: path: %w", err) } if len(p) <= 2 { return 0, fmt.Errorf("%w: first bad commit is %d", ErrBisectComplete, bad) } // Pick midpoint, avoiding skipped nodes. mid := len(p) / 2 if skip != nil { // Search outward from the midpoint for a non-skipped node. best := -1 for d := 0; d < len(p); d++ { for _, idx := range []int{mid + d, mid - d} { if idx > 0 && idx < len(p)-1 && !skip[p[idx].RID] { best = idx break } } if best >= 0 { break } } if best < 0 { return 0, fmt.Errorf("%w: first bad commit is %d", ErrBisectComplete, bad) } mid = best } return p[mid].RID, nil } // Status returns information about the current bisect session. func (s *Session) Status() StatusInfo { good, bad, _ := s.loadEndpoints() log := s.loadVvar("bisect-log") steps := 0 if good != 0 && bad != 0 { skip := s.parseSkipSet() p, err := path.Shortest(s.db, good, bad, true, skip) if err == nil && len(p) > 2 { steps = int(math.Log2(float64(len(p)))) } } return StatusInfo{ Good: good, Bad: bad, Log: log, Steps: steps, } } // List returns all commits between good and bad, labelled appropriately. func (s *Session) List(currentRID libfossil.FslID) ([]ListEntry, error) { good, bad, err := s.loadEndpoints() if err != nil { return nil, err } skip := s.parseSkipSet() p, err := path.Shortest(s.db, good, bad, true, nil) if err != nil { return nil, fmt.Errorf("bisect: list path: %w", err) } // Determine "next" for labelling. var nextRID libfossil.FslID pNoSkip, err := path.Shortest(s.db, good, bad, true, skip) if err == nil && len(pNoSkip) > 2 { nextRID = pNoSkip[len(pNoSkip)/2].RID } entries := make([]ListEntry, 0, len(p)) for _, node := range p { // The date as fossil's bisect ls shows it: datetime(event.mtime). var uuid, date string row := s.db.QueryRow(`SELECT b.uuid, COALESCE(datetime(e.mtime), '') FROM blob b LEFT JOIN event e ON e.objid=b.rid WHERE b.rid=?`, node.RID) if err := row.Scan(&uuid, &date); err != nil { uuid = "?" } label := "" switch { case node.RID == good: label = "GOOD" case node.RID == bad: label = "BAD" case node.RID == currentRID: label = "CURRENT" case node.RID == nextRID: label = "NEXT" case skip[node.RID]: label = "SKIP" } entries = append(entries, ListEntry{ RID: node.RID, UUID: uuid, Date: date, Label: label, }) } return entries, nil } // Reset clears all bisect state from the vvar table. func (s *Session) Reset() { if _, err := s.db.Exec("DELETE FROM vvar WHERE name IN ('bisect-good','bisect-bad','bisect-log')"); err != nil { panic(fmt.Sprintf("bisect.Reset: failed to clear bisect state: %v", err)) } } // --- internal helpers --- func (s *Session) loadEndpoints() (good, bad libfossil.FslID, err error) { gStr := s.loadVvar("bisect-good") bStr := s.loadVvar("bisect-bad") if gStr == "" || bStr == "" { return 0, 0, fmt.Errorf("bisect: good and bad must both be set") } g, err := strconv.ParseInt(gStr, 10, 64) if err != nil { return 0, 0, fmt.Errorf("bisect: parse good: %w", err) } b, err := strconv.ParseInt(bStr, 10, 64) if err != nil { return 0, 0, fmt.Errorf("bisect: parse bad: %w", err) } return libfossil.FslID(g), libfossil.FslID(b), nil } func (s *Session) loadVvar(name string) string { var val string if err := s.db.QueryRow("SELECT value FROM vvar WHERE name=?", name).Scan(&val); err != nil { return "" } return val } func (s *Session) appendLog(rid libfossil.FslID) error { return s.appendLogEntry(strconv.FormatInt(int64(rid), 10)) } func (s *Session) appendLogEntry(entry string) error { cur := s.loadVvar("bisect-log") if cur != "" { cur += " " } cur += entry _, err := s.db.Exec("REPLACE INTO vvar(name,value) VALUES('bisect-log',?)", cur) if err != nil { return fmt.Errorf("bisect: update log: %w", err) } return nil } func (s *Session) parseSkipSet() map[libfossil.FslID]bool { log := s.loadVvar("bisect-log") if log == "" { return nil } skip := make(map[libfossil.FslID]bool) for _, tok := range strings.Fields(log) { if strings.HasPrefix(tok, "s") { if id, err := strconv.ParseInt(tok[1:], 10, 64); err == nil { skip[libfossil.FslID(id)] = true } } } if len(skip) == 0 { return nil } return skip }