-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconsensus_events_test.go
More file actions
827 lines (693 loc) · 29.8 KB
/
Copy pathconsensus_events_test.go
File metadata and controls
827 lines (693 loc) · 29.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
package nara
import (
"context"
"testing"
"time"
"github.com/eljojo/nara/types"
)
// Test consensus with single observer (trivial case)
func TestConsensusEvents_SingleObserver(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
observer := types.NaraName("nara-a")
subject := types.NaraName("nara-target")
expectedStartTime := int64(1234567890)
expectedRestarts := int64(42)
// Single observer reports restart
event := NewRestartObservationEvent(observer, subject, expectedStartTime, expectedRestarts)
ledger.AddEvent(event)
// Derive consensus from events
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion := projection.DeriveOpinion(subject)
if opinion.StartTime != expectedStartTime {
t.Errorf("Expected StartTime=%d, got %d", expectedStartTime, opinion.StartTime)
}
if opinion.Restarts != expectedRestarts {
t.Errorf("Expected Restarts=%d, got %d", expectedRestarts, opinion.Restarts)
}
}
// Test consensus with multiple observers agreeing
func TestConsensusEvents_Agreement(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
agreedStartTime := int64(1234567890)
agreedRestarts := int64(100)
// Five observers all report the same values
observers := []types.NaraName{"nara-a", "nara-b", "nara-c", "nara-d", "nara-e"}
for _, observer := range observers {
event := NewRestartObservationEvent(observer, subject, agreedStartTime, agreedRestarts)
ledger.AddEvent(event)
}
// Consensus should match agreed values
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion := projection.DeriveOpinion(subject)
if opinion.StartTime != agreedStartTime {
t.Errorf("Expected consensus StartTime=%d, got %d", agreedStartTime, opinion.StartTime)
}
if opinion.Restarts != agreedRestarts {
t.Errorf("Expected consensus Restarts=%d, got %d", agreedRestarts, opinion.Restarts)
}
}
// Test consensus with observers disagreeing
func TestConsensusEvents_Disagreement(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
// 3 observers report StartTime=1000, Restarts=10
for i := 0; i < 3; i++ {
observer := types.NaraName("observer-" + string(rune('a'+i)))
event := NewRestartObservationEvent(observer, subject, 1000, 10)
ledger.AddEvent(event)
}
// 2 observers report StartTime=1000, Restarts=11 (same start, higher restarts)
for i := 0; i < 2; i++ {
observer := types.NaraName("observer-" + string(rune('d'+i)))
event := NewRestartObservationEvent(observer, subject, 1000, 11)
ledger.AddEvent(event)
}
// Consensus should pick:
// - StartTime: 1000 (clustering majority)
// - Restarts: 10 (cluster with more observers: 3 vs 2)
// Note: With tolerance=1, values 10 and 11 are in the same cluster,
// so median of [10,10,10,11,11] = 10
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion := projection.DeriveOpinion(subject)
if opinion.StartTime != 1000 {
t.Errorf("Expected consensus StartTime=1000 (clustering), got %d", opinion.StartTime)
}
if opinion.Restarts != 10 {
t.Errorf("Expected consensus Restarts=10 (median of cluster), got %d", opinion.Restarts)
}
}
// Test consensus with uptime-based weighting
func TestConsensusEvents_UptimeWeighting(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
// Two observers with LOW uptime report StartTime=1000
// Total uptime for cluster 1000: 100 + 100 = 200
// Note: Sleep between events to ensure unique timestamps (restart events dedupe by content+timestamp)
event1 := NewRestartObservationEventWithUptime("observer-a", subject, 1000, 5, 100)
ledger.AddEvent(event1)
time.Sleep(time.Microsecond) // Ensure different nanosecond timestamp
event2 := NewRestartObservationEventWithUptime("observer-b", subject, 1000, 5, 100)
ledger.AddEvent(event2)
time.Sleep(time.Microsecond)
// One observer with HIGH uptime reports StartTime=2000 (different cluster)
// Total uptime for cluster 2000: 10000
event3 := NewRestartObservationEventWithUptime("observer-elder", subject, 2000, 5, 10000)
ledger.AddEvent(event3)
// With trimmed mean:
// Values: [1000, 1000, 2000]
// Median: 1000
// All values within [500, 2000] (0.5x to 2x median)
// Average: (1000+1000+2000)/3 = 1333
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion := projection.DeriveOpinion(subject)
expectedAvg := int64(1333) // trimmed mean
if opinion.StartTime != expectedAvg {
t.Errorf("Expected StartTime=%d (trimmed mean), got %d", expectedAvg, opinion.StartTime)
}
}
// Test consensus uptime weighting when no cluster has 2+ observers
func TestConsensusEvents_UptimeWeighting_SingleObserverClusters(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
// Three observers each report different times (all in separate clusters)
// The elder with highest uptime should win
event1 := NewRestartObservationEventWithUptime("observer-young", subject, 1000, 5, 100)
event2 := NewRestartObservationEventWithUptime("observer-middle", subject, 2000, 5, 500)
event3 := NewRestartObservationEventWithUptime("observer-elder", subject, 3000, 5, 10000)
ledger.AddEvent(event1)
ledger.AddEvent(event2)
ledger.AddEvent(event3)
// With trimmed mean:
// Values: [1000, 2000, 3000]
// Median: 2000
// All values within [1000, 4000] (0.5x to 2x median)
// Average: (1000+2000+3000)/3 = 2000
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion := projection.DeriveOpinion(subject)
expectedAvg := int64(2000) // trimmed mean
if opinion.StartTime != expectedAvg {
t.Errorf("Expected StartTime=%d (trimmed mean), got %d", expectedAvg, opinion.StartTime)
}
}
// Test consensus with time tolerance clustering (±60s)
func TestConsensusEvents_ToleranceClustering(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
baseTime := int64(1234567890)
// Three observers report times within ±60s (should cluster together)
observers := []types.NaraName{"nara-a", "nara-b", "nara-c"}
offsets := []int64{-30, 0, 40} // Within tolerance
for i, observer := range observers {
event := NewRestartObservationEvent(observer, subject, baseTime+offsets[i], 10)
ledger.AddEvent(event)
}
// One outlier observer reports time 120s away (outside tolerance)
outlierEvent := NewRestartObservationEvent("nara-outlier", subject, baseTime+120, 10)
ledger.AddEvent(outlierEvent)
// Consensus should cluster the three within-tolerance observations
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion := projection.DeriveOpinion(subject)
// Should be close to baseTime (within the cluster)
if opinion.StartTime < baseTime-60 || opinion.StartTime > baseTime+60 {
t.Errorf("Expected consensus within tolerance of %d, got %d", baseTime, opinion.StartTime)
}
}
// Test consensus with first-seen events
func TestConsensusEvents_FirstSeen(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
firstSeenTime := int64(1234567890)
// Three observers report first-seen at similar times
for i := 0; i < 3; i++ {
observer := types.NaraName("observer-" + string(rune('a'+i)))
event := NewFirstSeenObservationEvent(observer, subject, firstSeenTime+int64(i))
ledger.AddEvent(event)
}
// Consensus should derive StartTime from first-seen events
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion := projection.DeriveOpinion(subject)
if opinion.StartTime == 0 {
t.Error("Expected non-zero StartTime from first-seen consensus")
}
// Should be close to firstSeenTime
if opinion.StartTime < firstSeenTime-10 || opinion.StartTime > firstSeenTime+10 {
t.Errorf("Expected StartTime near %d, got %d", firstSeenTime, opinion.StartTime)
}
}
// Test consensus with backfill events
func TestConsensusEvents_Backfill(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
backfillStartTime := int64(1624066568) // Long-running nara
backfillRestarts := int64(1137)
// Three observers backfill historical data
for i := 0; i < 3; i++ {
observer := types.NaraName("observer-" + string(rune('a'+i)))
event := NewBackfillObservationEvent(observer, subject, backfillStartTime, backfillRestarts, time.Now().Unix())
ledger.AddEvent(event)
}
// Consensus should treat backfill events like regular observations
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion := projection.DeriveOpinion(subject)
if opinion.StartTime != backfillStartTime {
t.Errorf("Expected backfill StartTime=%d, got %d", backfillStartTime, opinion.StartTime)
}
if opinion.Restarts != backfillRestarts {
t.Errorf("Expected backfill Restarts=%d, got %d", backfillRestarts, opinion.Restarts)
}
}
// Test consensus with mixed backfill and real-time events
func TestConsensusEvents_MixedBackfillAndRealtime(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
historicalStartTime := int64(1624066568)
historicalRestarts := int64(1137)
// Two observers backfill historical data
for i := 0; i < 2; i++ {
observer := types.NaraName("backfill-" + string(rune('a'+i)))
event := NewBackfillObservationEvent(observer, subject, historicalStartTime, historicalRestarts, time.Now().Unix())
ledger.AddEvent(event)
// Add tiny delay to ensure different timestamps (avoids ID collision in tight test loop)
time.Sleep(time.Microsecond)
}
// Three observers report newer restart count in real-time
newRestarts := int64(1140)
for i := 0; i < 3; i++ {
observer := types.NaraName("realtime-" + string(rune('a'+i)))
event := NewRestartObservationEvent(observer, subject, historicalStartTime, newRestarts)
ledger.AddEvent(event)
}
// Consensus should average: (1137+1137+1140+1140+1140)/5 = 1138.8 → 1138
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion := projection.DeriveOpinion(subject)
expectedAvg := int64(1138) // trimmed mean of values
if opinion.Restarts != expectedAvg {
t.Errorf("Expected consensus Restarts=%d (trimmed mean), got %d", expectedAvg, opinion.Restarts)
}
}
// Test consensus with no events (fallback behavior)
func TestConsensusEvents_NoEvents(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-unknown")
// No events about this subject
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion := projection.DeriveOpinion(subject)
// Should return zero values or indicate no consensus
if opinion.StartTime != 0 {
t.Logf("No events available - StartTime defaulted to %d", opinion.StartTime)
}
if opinion.Restarts != 0 {
t.Logf("No events available - Restarts defaulted to %d", opinion.Restarts)
}
}
// Test consensus respects critical importance
func TestConsensusEvents_ImportanceAwareness(t *testing.T) {
ledger := NewSyncLedger(1000)
subject := types.NaraName("nara-target")
// Critical events (restart, first-seen) should always participate in consensus
criticalEvent := NewRestartObservationEvent("observer-a", subject, 1000, 10)
if criticalEvent.Observation.Importance != ImportanceCritical {
t.Fatal("Expected restart event to be Critical importance")
}
ledger.AddEvent(criticalEvent)
// Normal events (status-change) should also participate
normalEvent := NewStatusChangeObservationEvent("observer-b", subject, "ONLINE")
if normalEvent.Observation.Importance != ImportanceNormal {
t.Fatal("Expected status-change event to be Normal importance")
}
ledger.AddEvent(normalEvent)
// Both should be available for consensus
events := ledger.GetObservationEventsAbout(subject)
if len(events) != 2 {
t.Errorf("Expected 2 events for consensus, got %d", len(events))
}
}
// Test consensus with restart count progression
func TestConsensusEvents_RestartProgression(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
startTime := int64(1234567890)
// Observer reports restarts: 5, 7, 10 (progression over time)
restartCounts := []int64{5, 7, 10}
for i, count := range restartCounts {
observer := types.NaraName("observer-a")
event := NewRestartObservationEvent(observer, subject, startTime, count)
time.Sleep(time.Duration(i+1) * time.Millisecond) // Ensure ordering
ledger.AddEvent(event)
}
// Consensus should pick highest restart count (most recent)
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion := projection.DeriveOpinion(subject)
if opinion.Restarts != 10 {
t.Errorf("Expected consensus Restarts=10 (highest), got %d", opinion.Restarts)
}
}
// Test consensus determinism (same events = same opinion)
func TestConsensusEvents_Determinism(t *testing.T) {
ledger1 := NewSyncLedger(1000)
ledger2 := NewSyncLedger(1000)
projection1 := NewOpinionConsensusProjection(ledger1)
projection2 := NewOpinionConsensusProjection(ledger2)
subject := types.NaraName("nara-target")
// Add same events to both ledgers
events := []struct {
observer types.NaraName
startTime int64
restartNum int64
}{
{"observer-a", 1000, 10},
{"observer-b", 1001, 10},
{"observer-c", 1000, 11},
}
for _, e := range events {
event1 := NewRestartObservationEvent(e.observer, subject, e.startTime, e.restartNum)
event2 := NewRestartObservationEvent(e.observer, subject, e.startTime, e.restartNum)
ledger1.AddEvent(event1)
ledger2.AddEvent(event2)
}
// Both should derive same opinion
opinion1 := projection1.DeriveOpinion(subject)
opinion2 := projection2.DeriveOpinion(subject)
if opinion1.StartTime != opinion2.StartTime {
t.Errorf("Expected deterministic StartTime, got %d and %d", opinion1.StartTime, opinion2.StartTime)
}
if opinion1.Restarts != opinion2.Restarts {
t.Errorf("Expected deterministic Restarts, got %d and %d", opinion1.Restarts, opinion2.Restarts)
}
}
// Test consensus with personality-filtered events
func TestConsensusEvents_PersonalityFiltered(t *testing.T) {
// Very chill personality (>85) filters Normal importance events
chillPersonality := NaraPersonality{Chill: 90, Sociability: 50, Agreeableness: 50}
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
// Add critical event (should NOT be filtered)
criticalEvent := NewRestartObservationEvent("observer-a", subject, 1000, 10)
added := ledger.AddEventFiltered(criticalEvent, chillPersonality)
if !added {
t.Fatal("Critical event should not be filtered by personality")
}
// Add normal event (MAY be filtered by very chill personality)
normalEvent := NewStatusChangeObservationEvent("observer-b", subject, "OFFLINE")
ledger.AddEventFiltered(normalEvent, chillPersonality)
// Consensus should work even if some events were filtered
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion := projection.DeriveOpinion(subject)
// Should have at least the critical event
if opinion.StartTime == 0 {
t.Error("Expected consensus from critical event, got zero StartTime")
}
}
// Test consensus with LastRestart field
func TestConsensusEvents_LastRestart(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
startTime := int64(1234567890)
lastRestartTime := time.Now().Unix()
// Observers report restart with LastRestart timestamp
for i := 0; i < 3; i++ {
observer := types.NaraName("observer-" + string(rune('a'+i)))
event := NewRestartObservationEvent(observer, subject, startTime, 10)
// In implementation, LastRestart would be part of the event
ledger.AddEvent(event)
}
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion := projection.DeriveOpinion(subject)
// Should derive LastRestart from events
if opinion.LastRestart == 0 {
t.Log("LastRestart not yet implemented in consensus")
}
_ = lastRestartTime // Use to avoid warning
}
// Test consensus accuracy compared to newspaper mode (integration)
func TestConsensusEvents_VsNewspaperAccuracy(t *testing.T) {
t.Skip("Integration test - requires full implementation and newspaper comparison")
// This test would:
// 1. Run network in dual mode (newspapers + events)
// 2. Derive opinion from newspapers (old way)
// 3. Derive opinion from events (new way)
// 4. Assert >99% agreement between the two methods
// Example structure:
// newspaperOpinion := formOpinionFromNewspapers(subject)
// eventOpinion := formOpinionFromEvents(subject)
// assertSimilar(newspaperOpinion, eventOpinion, tolerance=1%)
}
// Test consensus when observer changes their mind about StartTime.
// Unlike the legacy newspaper-based system which only saw current observer state,
// the projection accumulates ALL observations. When the same observer changes their
// opinion, both values are used for clustering. The newer value needs network
// corroboration (other observers) to form a winning cluster.
func TestConsensusEvents_ChangeOfMind(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
// Observer-a initially reports StartTime=1000
event1 := NewRestartObservationEvent("observer-a", subject, 1000, 5)
ledger.AddEvent(event1)
time.Sleep(time.Millisecond) // Ensure different timestamp
// Same observer later reports StartTime=2000 (changed their mind, e.g., after restart)
event2 := NewRestartObservationEvent("observer-a", subject, 2000, 6)
ledger.AddEvent(event2)
// With no other observers, both values form single-observer clusters.
// The algorithm picks the first cluster with equal weight (deterministic).
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion := projection.DeriveOpinion(subject)
// Restarts uses "highest value wins" - so the newer observation wins
if opinion.Restarts != 6 {
t.Errorf("Expected Restarts=6 (highest value), got %d", opinion.Restarts)
}
// Now add corroborating observer that agrees with new StartTime
time.Sleep(time.Millisecond)
event3 := NewRestartObservationEvent("observer-b", subject, 2000, 6)
ledger.AddEvent(event3)
if _, err := projection.RunOnce(); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion = projection.DeriveOpinion(subject)
// With trimmed mean:
// Values: [1000, 2000, 2000] (observer-a's two reports + observer-b)
// Median: 2000, Average: (1000+2000+2000)/3 = 1666
expectedAvg := int64(1666)
if opinion.StartTime != expectedAvg {
t.Errorf("Expected StartTime=%d (trimmed mean), got %d", expectedAvg, opinion.StartTime)
}
}
// slight modification of the one above
func TestConsensusEvents_ChangeOfMind_two(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
// Observer-a initially reports StartTime=1000
event1 := NewRestartObservationEvent("observer-a", subject, 1000, 5)
ledger.AddEvent(event1)
time.Sleep(time.Millisecond) // Ensure different timestamp
// Same observer later reports StartTime=2000 (changed their mind, e.g., after restart)
event2 := NewRestartObservationEvent("observer-a", subject, 2000, 6)
ledger.AddEvent(event2)
// With no other observers, both values form single-observer clusters.
// The algorithm picks the first cluster with equal weight (deterministic).
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion := projection.DeriveOpinion(subject)
// Restarts uses "highest value wins" - so the newer observation wins
if opinion.Restarts != 6 {
t.Errorf("Expected Restarts=6 (highest value), got %d", opinion.Restarts)
}
// Now add corroborating observer that agrees with **original** StartTime
time.Sleep(time.Millisecond)
event3 := NewRestartObservationEvent("observer-b", subject, 1000, 6)
ledger.AddEvent(event3)
if _, err := projection.RunOnce(); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion = projection.DeriveOpinion(subject)
// With trimmed mean:
// Values: [1000, 2000, 1000] (observer-a's two reports + observer-b)
// Median: 1000, Average: (1000+2000+1000)/3 = 1333
expectedAvg := int64(1333)
if opinion.StartTime != expectedAvg {
t.Errorf("Expected StartTime=%d (trimmed mean), got %d", expectedAvg, opinion.StartTime)
}
}
// Test consensus with sparse observations
func TestConsensusEvents_SparseObservations(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
// Single first-seen event
event := NewFirstSeenObservationEvent("observer-a", subject, 1000)
ledger.AddEvent(event)
// Consensus should work with minimal data
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion := projection.DeriveOpinion(subject)
if opinion.StartTime != 1000 {
t.Errorf("Expected StartTime=1000 from sparse observation, got %d", opinion.StartTime)
}
}
// TestDeriveOpinionWithValidation_CheckpointComparison tests the shadow comparison
// between observation-based and checkpoint-based opinion derivation.
func TestDeriveOpinionWithValidation_CheckpointComparison(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
attester := testLocalNara(t, "attester")
// Add observation events
obs1 := NewRestartObservationEvent("observer-a", subject, 1000, 5)
obs2 := NewRestartObservationEvent("observer-b", subject, 1000, 5)
ledger.AddEvent(obs1)
ledger.AddEvent(obs2)
// Add a checkpoint that agrees with observations
observation := NaraObservation{
Restarts: 5,
TotalUptime: 3600,
StartTime: 1000,
}
checkpointEvent := testCheckpointEvent(subject, attester.Me.Name, attester.Keypair, observation)
ledger.AddEvent(checkpointEvent)
// Run projection
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
// DeriveOpinionWithValidation should return observation-based opinion
// and not warn since checkpoint agrees
opinion := projection.DeriveOpinionWithValidation(subject)
if opinion.Restarts != 5 {
t.Errorf("Expected Restarts=5, got %d", opinion.Restarts)
}
// DeriveOpinionFromCheckpoint should also return 5
checkpointOpinion, usedCheckpoint := projection.DeriveOpinionFromCheckpoint(subject)
if !usedCheckpoint {
t.Error("Expected checkpoint to be used")
}
if checkpointOpinion.Restarts != 5 {
t.Errorf("Expected checkpoint Restarts=5, got %d", checkpointOpinion.Restarts)
}
}
// TestDeriveOpinionFromCheckpoint_NoCheckpoint tests fallback when no checkpoint exists.
func TestDeriveOpinionFromCheckpoint_NoCheckpoint(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
// Only add observation events, no checkpoint
obs1 := NewRestartObservationEvent("observer-a", subject, 1000, 5)
ledger.AddEvent(obs1)
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
// Should fall back to observation-based
opinion, usedCheckpoint := projection.DeriveOpinionFromCheckpoint(subject)
if usedCheckpoint {
t.Error("Expected no checkpoint to be used")
}
if opinion.Restarts != 5 {
t.Errorf("Expected Restarts=5, got %d", opinion.Restarts)
}
}
// TestDeriveOpinionFromCheckpoint_WithPostCheckpointEvents tests that post-checkpoint
// restart events are counted on top of checkpoint baseline.
func TestDeriveOpinionFromCheckpoint_WithPostCheckpointEvents(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
attester := testLocalNara(t, "attester")
// Use times after cutoff to avoid filtering
timeOffset := CheckpointCutoffTime + 10000
checkpointTime := timeOffset + 1000
// Add checkpoint saying 10 restarts, 3600s uptime as of checkpointTime
observation := NaraObservation{
Restarts: 10,
TotalUptime: 3600,
StartTime: timeOffset + 500,
}
checkpointEvent := testCheckpointEvent(subject, attester.Me.Name, attester.Keypair, observation)
checkpointEvent.Checkpoint.AsOfTime = checkpointTime
ledger.AddEvent(checkpointEvent)
// Add 3 restart observations AFTER the checkpoint (different StartTimes)
obs1 := NewRestartObservationEvent("observer-a", subject, timeOffset+1100, 11) // StartTime > checkpoint
obs2 := NewRestartObservationEvent("observer-b", subject, timeOffset+1200, 12) // StartTime > checkpoint
obs3 := NewRestartObservationEvent("observer-c", subject, timeOffset+1300, 13) // StartTime > checkpoint
ledger.AddEvent(obs1)
ledger.AddEvent(obs2)
ledger.AddEvent(obs3)
// Add status-change events after checkpoint: ONLINE at +1100, OFFLINE at +1600 = 500 seconds
onlineEvent := NewStatusChangeObservationEvent("observer-a", subject, "ONLINE")
onlineEvent.Timestamp = (timeOffset + 1100) * 1e9 // Convert to nanoseconds
ledger.AddEvent(onlineEvent)
offlineEvent := NewStatusChangeObservationEvent("observer-a", subject, "OFFLINE")
offlineEvent.Timestamp = (timeOffset + 1600) * 1e9
ledger.AddEvent(offlineEvent)
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
// Checkpoint-based should be: 10 (baseline) + 3 (new unique StartTimes) = 13
opinion, usedCheckpoint := projection.DeriveOpinionFromCheckpoint(subject)
if !usedCheckpoint {
t.Error("Expected checkpoint to be used")
}
if opinion.Restarts != 13 {
t.Errorf("Expected Restarts=13 (10 checkpoint + 3 new), got %d", opinion.Restarts)
}
// StartTime should come from checkpoint
expectedStartTime := timeOffset + 500
if opinion.StartTime != expectedStartTime {
t.Errorf("Expected StartTime=%d from checkpoint, got %d", expectedStartTime, opinion.StartTime)
}
// TotalUptime should be: 3600 (checkpoint) + 500 (new online period) = 4100
if opinion.TotalUptime != 4100 {
t.Errorf("Expected TotalUptime=4100 (3600 checkpoint + 500 new), got %d", opinion.TotalUptime)
}
}
// TestDeriveOpinionFromCheckpoint_WithOfflinePeriods tests that uptime is calculated correctly
// when the nara goes offline and online multiple times after a checkpoint.
func TestDeriveOpinionFromCheckpoint_WithOfflinePeriods(t *testing.T) {
ledger := NewSyncLedger(1000)
projection := NewOpinionConsensusProjection(ledger)
subject := types.NaraName("nara-target")
attester := testLocalNara(t, "attester")
// Use times after cutoff to avoid filtering
timeOffset := CheckpointCutoffTime + 10000
checkpointTime := timeOffset + 1000
// Add checkpoint with 1000s of uptime as of checkpointTime
observation := NaraObservation{
Restarts: 5,
TotalUptime: 1000,
StartTime: timeOffset + 100,
}
checkpointEvent := testCheckpointEvent(subject, attester.Me.Name, attester.Keypair, observation)
checkpointEvent.Checkpoint.AsOfTime = checkpointTime
ledger.AddEvent(checkpointEvent)
// Add a restart observation so DeriveOpinion doesn't return early
// (DeriveOpinion returns empty if no restart/first-seen observations exist)
restartObs := NewRestartObservationEvent("observer-a", subject, timeOffset+100, 5)
ledger.AddEvent(restartObs)
// Simulate timeline after checkpoint (relative to timeOffset):
// +1100: ONLINE (start period 1)
// +1400: OFFLINE (end period 1: 300s online)
// +1500: ONLINE (start period 2)
// +1800: OFFLINE (end period 2: 300s online)
// +2000: ONLINE (start period 3)
// +2200: OFFLINE (end period 3: 200s online)
// Total new uptime: 300 + 300 + 200 = 800s
events := []struct {
timestamp int64
state string
}{
{timeOffset + 1100, "ONLINE"},
{timeOffset + 1400, "OFFLINE"},
{timeOffset + 1500, "ONLINE"},
{timeOffset + 1800, "OFFLINE"},
{timeOffset + 2000, "ONLINE"},
{timeOffset + 2200, "OFFLINE"},
}
for _, e := range events {
event := NewStatusChangeObservationEvent("observer-a", subject, e.state)
event.Timestamp = e.timestamp * 1e9 // Convert to nanoseconds
ledger.AddEvent(event)
}
if err := projection.RunToEnd(context.Background()); err != nil {
t.Fatalf("Failed to run projection: %v", err)
}
opinion, usedCheckpoint := projection.DeriveOpinionFromCheckpoint(subject)
if !usedCheckpoint {
t.Error("Expected checkpoint to be used")
}
// Restarts should be unchanged (no new restart events)
if opinion.Restarts != 5 {
t.Errorf("Expected Restarts=5 (no new restarts), got %d", opinion.Restarts)
}
// TotalUptime should be: 1000 (checkpoint) + 800 (new periods) = 1800
expectedUptime := int64(1000 + 300 + 300 + 200) // 1800
if opinion.TotalUptime != expectedUptime {
t.Errorf("Expected TotalUptime=%d (1000 checkpoint + 800 new), got %d", expectedUptime, opinion.TotalUptime)
}
// Also verify observation-based method matches (they should derive same uptime)
obsOpinion := projection.DeriveOpinion(subject)
if obsOpinion.TotalUptime != expectedUptime {
t.Errorf("Observation-based TotalUptime=%d should match checkpoint-based=%d", obsOpinion.TotalUptime, expectedUptime)
}
}