GoSuda

Introducing GSTime and GSTimeAssure

By Lemon Mint
views ...

Zero-dependency, fault-tolerant time synchronization and certification engine in Go. Provides continuous SI-nanosecond tracking, dual-track separation between statistical estimation and interval certification, RFC 8915 Network Time Security (NTS), bounded leap smearing, and lock-free publication.

Requirements

Go 1.27.0 or newer. Zero external dependencies.

1go get gosuda.org/gstime

Upstream Sources Configuration

GSTime supports NTS-KE authenticated endpoints and standard NTPv4 pools across independent failure domains ( N ≄ 2 F + 1 N \ge 2F+1 7664f5c944556bd14c0346a41b41

 1cfg := config.Config{
 2	Assurance: config.AssuranceConfig{
 3		FaultBudget:       1,
 4		MinVotingDomains:  3,
 5		MinHonestCoverage: 2,
 6		MaxWidthNs:        32 * 1_000_000_000,
 7	},
 8	Raw: config.RawConfig{
 9		BackendProfile: "standard_monotonic",
10		ScaleLowerPpm:  -200.0,
11		ScaleUpperPpm:  200.0,
12		ReadBoundNs:    1000,
13	},
14	Sources: []config.SourceConfig{
15		{FaultDomainID: "cloudflare", Endpoint: "time.cloudflare.com:4460", NTS: true},
16		{FaultDomainID: "google",     Endpoint: "time.google.com:123",      NTS: false},
17		{FaultDomainID: "apple",      Endpoint: "time.apple.com:123",       NTS: false},
18		{FaultDomainID: "meta",       Endpoint: "time.facebook.com:123",    NTS: false},
19	},
20}
21cfgID, _ := cfg.ConfigID()

Minimal Examples by Use Case

Service & Background Sync Initialization

 1rawClock := clock.NewSystemRawClock()
 2leapHistory, _ := core.NewLeapHistory(10, nil) // Configured GSTL1 leap table
 3svc := gstime.NewClockService(rawClock, leapHistory, cfgID, 32_000_000_000)
 4
 5// Start background NTP/NTS synchronization engine
 6engine, err := gstime.NewSyncEngine(cfg, svc)
 7if err != nil {
 8	log.Fatal(err)
 9}
10
11ctx, cancel := context.WithCancel(context.Background())
12defer cancel()
13
14_ = engine.Start(ctx)
15defer engine.Close() // Best Practice: Gracefully stops background worker with zero goroutine leaks
16
17// Wait until initial synchronization is achieved
18_ = engine.WaitSync(ctx)

1. PublicClock: Monotonic Presentation Time

For logging, APIs, and metrics. Guaranteed strictly non-decreasing ( P k + 1 ≄ P k P_{k+1} \ge P_k 5c944556bd14c0346a41b41

1pub := svc.NowPublicAssured()
2
3fmt.Printf("Public Time: %d\n", pub.Center)                 // GstInstant (continuous SI-ns)
4fmt.Printf("Symmetric Uncertainty: ±%d ns\n", pub.PublicSymmetricEpsilon)
5fmt.Printf("Status: %s\n", pub.Status)                      // SYNCED, HOLDOVER, or DESYNC

2. GSTimeAssure: Distributed Transactions & CommitWait

For distributed databases requiring external consistency via certified interval and CommitWait.

 1now := svc.Now()
 2if now.Interval != nil {
 3	// Certified interval [Earliest, Latest] enclosing true SI time
 4	fmt.Printf("Certified Range: [%d, %d]\n", now.Interval.Earliest, now.Interval.Latest)
 5}
 6
 7// Tri-state causality check: CertainYes, CertainNo, or Unknown
 8decision, _, _ := svc.After(txTimestamp)
 9
10// Commit wait: blocks until certified lower watermark strictly exceeds commitTs
11ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
12defer cancel()
13
14err := svc.CommitWait(ctx, commitTs, now.AssuranceEpochID, now.LeapHistoryID, now.ConfigID)
15if err != nil {
16	// Handle ErrDeadlineExceeded, ErrDesynchronized, or ErrConfigurationMismatch
17}

3. Civil UTC with Leap Seconds

For civil calendrical display supporting positive leap seconds (SecondOfDay = 86400).

1earliest, latest, est, status, err := svc.NowUtc(leapHistory.ID)
2if est != nil {
3	fmt.Printf("UTC: %s\n", est.String())             // e.g. 2026-09-05T06:56:38.922254833Z
4	fmt.Printf("SecondOfDay: %d\n", est.SecondOfDay)   // 0..86399 (or 86400 on leap seconds)
5}

4. POSIX / Unix Projection

For compatibility with legacy Unix millisecond/nanosecond APIs.

1proj, err := svc.NowUnixProjection()
2fmt.Printf("UnixNanos: %d, InLeapSecond: %v\n", proj.Nanos, proj.IsLeapSecond)

5. Distributed Lock & Lease Validation (After / Before)

Non-blocking causality check to safely verify whether a distributed lock lease has expired.

1decision, status, reason := svc.After(leaseDeadline)
2if status != gstime.StatusSynced || decision != gstime.CertainNo {
3	// Lease may have expired or clock desynchronized: abort write
4}

6. VM Migration & Discontinuity Fail-Fast

Hardware counters detect suspend/resume and snapshot rollbacks, transitioning to StatusDesync.

1now := svc.Now()
2if now.Status == gstime.StatusDesync {
3	// Reason: ReasonBoundTooOld (VM paused) or ReasonRawDiscontinuity (snapshot rollback)
4}

Running Examples and Tests

Execute all Go Example tests:

1go test -v -run Example .

Run the standalone executable example:

1go run ./examples/main.go

Deterministic Simulation Testing (DST)

GSTime includes a deterministic simulation testing (DST) harness (dst_test.go) inspired by FoundationDB and Antithesis. It runs discrete time simulation with pseudorandom fault injection across PRNG seeds:

  • VM Snapshot Rollbacks: Hardware counter rewinds and continuity token changes (verifying fail-fast StatusDesync).
  • Hypervisor Freezes / Suspends: VM pause/migration for 10s–60s across validity horizons.
  • OS Clock Shaking: Oscillator frequency wander (up to ±180 ppm) and sampling noise.
  • Byzantine Upstreams: Outlier sources (+1 hour offsets) filtered by Marzullo/Hull consensus.
  • Strict Invariants: Proves public clock monotonicity ( P k + 1 ≄ P k P_{k+1} \ge P_k 5c944556bd14c0346a41b41
1go test -v -run TestDST .

Package Layout

 1gosuda.org/gstime
 2ā”œā”€ā”€ core/         # Semantic types, Q16.48 fixed-point math, GSTL1 leap codec
 3ā”œā”€ā”€ ntp/          # NTPv4 wire framing, 2036 era unfolding, reachability bitmap
 4ā”œā”€ā”€ nts/          # NTS-KE client, AEAD 15/30 (RFC 5297 / 8452), cookie lifecycle
 5ā”œā”€ā”€ source/       # Weighted regression, DP runs test, N-F consensus sweep (App. B)
 6ā”œā”€ā”€ clock/        # RawClock drivers, EstimateClock, slew planner, smear engine, clamp
 7ā”œā”€ā”€ assurance/    # Absolute anchor propagation, holdover tracking, status machine
 8ā”œā”€ā”€ publish/      # Lock-free atomic snapshot publication, publication guard
 9ā”œā”€ā”€ config/       # Canonical JSON configuration and RFC 8785 SHA-256 config hashing
10ā”œā”€ā”€ telemetry/    # Atomic metrics collectors (offsets, errors, smear, re-anchors)
11ā”œā”€ā”€ conformance/  # Conformance test suites (Levels A-F) and property verifications (P1-P14)
12└── service.go    # Unified ClockService facade

Verification

1go test -v -race -count=1 ./...
2gojgp check