Repository navigation
Expand file tree
/
Copy pathwait-first-hour-capture.go.txt
More file actions
450 lines (439 loc) · 19.4 KB
/
Copy pathwait-first-hour-capture.go.txt
File metadata and controls
450 lines (439 loc) · 19.4 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
package harness
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math"
"os"
"reflect"
"slices"
"strconv"
"strings"
"testing"
"cloud-clicker/server/accrualhook"
"cloud-clicker/server/decimal"
"cloud-clicker/server/economy"
"cloud-clicker/server/multiplier"
"cloud-clicker/server/production"
"cloud-clicker/server/save"
)
type firstHourReferenceResearch struct {
Cash string `json:"cash"`
Lifetime string `json:"lifetime"`
}
// This exercises the CURRENT real consumer, not the proposed modern query.
// Existing public-tree fixture helpers own the non-unit bonus and legal assets.
func TestWaitFirstHourCandidateBoundaryResearch(t *testing.T) {
const horizon int64 = 1000
cases, references, rankedTransitions := 0, 0, int64(0)
delayed := map[string]int{}
rejected, unreachable, zeroRate := 0, 0, 0
for _, arm := range []string{"none", "unit", "tree"} {
for _, id := range []string{"generator.beige_tower", "upgrade.beige_tower_cache"} {
for _, maskName := range []string{"none", "generator", "upgrade", "removed_generator", "removed_upgrade", "removed_action"} {
for _, cashName := range []string{"immediate", "delayed"} {
t.Run(fmt.Sprintf("%s/%s/%s/%s", arm, id, maskName, cashName), func(t *testing.T) {
runtime := reputationReferenceFixture(t, arm)
suite, err := runtime.referenceRanker()
if err != nil {
t.Fatal(err)
}
mask := production.AblationMask{}
switch maskName {
case "generator":
mask.GeneratorIDs = []string{"generator.beige_tower"}
case "upgrade":
mask.UpgradeIDs = []string{"upgrade.beige_tower_cache"}
case "removed_generator":
mask.RemovedGeneratorIDs = []string{"generator.beige_tower"}
case "removed_upgrade":
mask.RemovedUpgradeIDs = []string{"upgrade.beige_tower_cache"}
case "removed_action":
mask.RemovedActionIDs = []string{"manual.click"}
}
resource, price, err := suite.candidateCost(runtime.company, id)
if err != nil || resource != "company.cash" {
t.Fatal("actual quote unavailable", resource, err)
}
balances := runtime.company.Ledger.Snapshot()
seed := price
if cashName == "delayed" {
seed = price.Sub(decimal.FromFloat64(2.5))
}
balances[resource] = seed.String()
runtime.company.Ledger, err = economy.RestoreLedger(suite.Catalog, economy.ScopeCompany, balances)
if err != nil {
t.Fatal("controlled ledger refused", err)
}
origin, err := save.EncodeState(runtime.company)
if err != nil {
t.Fatal(err)
}
at := int64(-1)
for candidateAt := int64(0); candidateAt <= horizon; candidateAt++ {
point, err := cloneState(suite.Catalog, runtime.company)
if err != nil {
t.Fatal(err)
}
if _, err := production.SimulateAdvance(point, suite.Catalog,
production.SimulationDependencies{Routes: suite.Routes, Hook: runtime.lifetimeHook()}, runtime.companyRevision(),
production.ModeOnline, relevanceNow(candidateAt), runtime.external(), mask); err != nil {
t.Fatal("actual chronological reference refused", candidateAt, err)
}
references++
balance, _ := point.Ledger.Balance(resource)
if balance.Gte(price) {
at = candidateAt
break
}
if candidateAt == horizon {
unreachable++
}
}
var want *save.State
var transition production.SimulationResult
var score relevanceProjection
expected := false
if at >= 0 {
want, err = cloneState(suite.Catalog, runtime.company)
if err != nil {
t.Fatal(err)
}
transition, err = production.SimulateTransition(candidateIntent(id, runtime.revision), want, suite.Catalog,
production.SimulationDependencies{Routes: suite.Routes, Hook: runtime.lifetimeHook()}, runtime.companyRevision(),
production.ModeOnline, relevanceNow(at), runtime.external(), nil, mask)
if err != nil {
t.Fatal("single-origin semantic reference failed", err)
}
if transition.Decision.Outcome == save.IntentApplied {
balance, _ := want.Ledger.Balance(resource)
target, err := decimal.ParseCanonical(suite.Scenario.Milestone.Amount)
if err != nil {
t.Fatal(err)
}
if balance.Gte(target) {
expected = true
score = relevanceProjection{Numerator: decimal.Zero, Denominator: decimal.One}
} else {
rate, err := production.SimulateResourceRateWithContributions(want, suite.Catalog, resource, runtime.external(), mask)
if err != nil {
t.Fatal(err)
}
if rate.Gt(decimal.Zero) {
expected = true
score = relevanceProjection{Numerator: target.Sub(balance).Mul(decimal.New(1, 3)), Denominator: rate}
} else {
zeroRate++
}
}
if at > 0 {
score.Numerator = score.Numerator.Add(score.Denominator.Mul(decimal.FromFloat64(float64(at))))
}
} else {
rejected++
}
}
counter := &relevanceCounter{limit: runtime.suite.Scenario.TransitionBudget}
got, ok, err := suite.rankCandidate(runtime.company, runtime.revision, 0, horizon, id, mask, counter)
rankedTransitions += counter.value
if err != nil || ok != expected {
t.Fatal("actual consumer changed reference availability", ok, expected, at, err)
}
if ok {
if got.ID != id || got.AtMS != at || got.Revision != runtime.revision+1 ||
!got.Projection.Numerator.Eq(score.Numerator) || !got.Projection.Denominator.Eq(score.Denominator) {
t.Fatal("actual candidate coordinates/score differ", got.ID, got.AtMS, at, got.Projection, score)
}
requireReferenceCompanyEqual(t, got.State, want)
if !slices.Equal(got.RoleActivations, transition.RoleActivations) {
t.Fatal("actual candidate loses/repeats role observations", got.RoleActivations, transition.RoleActivations)
}
if at > 0 {
delayed[id]++
if !got.State.LifetimeValue.Gt(runtime.company.LifetimeValue) {
t.Fatal("delayed purchase did not exercise lifetime work")
}
}
}
if after, err := save.EncodeState(runtime.company); err != nil || !bytes.Equal(origin, after) {
t.Fatal("actual candidate/reference consumed origin", err)
}
cases++
})
}
}
}
}
if cases != 72 || delayed["generator.beige_tower"] == 0 || delayed["upgrade.beige_tower_cache"] == 0 || rejected == 0 || unreachable == 0 || zeroRate == 0 {
t.Fatal("incomplete/non-discriminating candidate population", cases, delayed, rejected, unreachable, zeroRate)
}
t.Logf("actual candidate cases%d reference-advances%d ranked-transitions%d delayed%v rejected%d unreachable%d zero-rate%d; reference setup/action/rate/codec work separate, not total workload or modern-query integration", cases, references, rankedTransitions, delayed, rejected, unreachable, zeroRate)
}
type candidateErrorResearch struct {
inner production.AccrualHook
cause error
}
func (hook candidateErrorResearch) AfterAccrual(state *save.State, catalog *economy.Catalog, revision save.Revision, result accrualhook.Result, contributions []multiplier.Contribution) ([]save.EventWrite, error) {
if _, err := hook.inner.AfterAccrual(state, catalog, revision, result, contributions); err != nil {
return nil, err
}
return nil, hook.cause
}
func TestWaitFirstHourCandidateErrorsResearch(t *testing.T) {
runtime := reputationReferenceFixture(t, "tree")
suite, err := runtime.referenceRanker()
if err != nil {
t.Fatal(err)
}
origin, err := save.EncodeState(runtime.company)
if err != nil {
t.Fatal(err)
}
// An immediate affordable candidate must still charge its semantic action.
if got, ok, err := suite.rankCandidate(runtime.company, runtime.revision, 0, 1000, "generator.beige_tower", production.AblationMask{}, &relevanceCounter{limit: 0}); err == nil || ok || got.State != nil {
t.Fatal("budget exhaustion became success/unreachable", ok, err)
}
// Actual positive-elapsed evaluation/hook failure must propagate unchanged,
// even when the visible balance was affordable before the query.
cause := errors.New("injected candidate hook failure")
suite.hook = candidateErrorResearch{runtime.lifetimeHook(), cause}
if got, ok, err := suite.rankCandidate(runtime.company, runtime.revision, 1, 1000, "generator.beige_tower", production.AblationMask{}, &relevanceCounter{limit: runtime.suite.Scenario.TransitionBudget}); !errors.Is(err, cause) || ok || got.State != nil {
t.Fatal("semantic action hook failure was hidden/relabelled", ok, err)
}
if after, err := save.EncodeState(runtime.company); err != nil || !bytes.Equal(origin, after) {
t.Fatal("refused actual candidate consumed source", err)
}
}
type firstHourAnchorResearch struct {
At int64 `json:"at"`
State json.RawMessage `json:"state"`
Advance production.AdvanceSimulationResult `json:"advance"`
}
type firstHourQuoteResearch struct {
ID string `json:"id"`
Resource string `json:"resource"`
Cost string `json:"cost"`
CostMantissaBits string `json:"cost_mantissa_bits"`
CostExponent int64 `json:"cost_exponent"`
At int64 `json:"at"`
Affordable bool `json:"affordable"`
Transitions int64 `json:"transitions"`
Selected *firstHourAnchorResearch `json:"selected"`
}
type firstHourSnapshotResearch struct {
Label string `json:"label"`
State json.RawMessage `json:"state"`
Version int `json:"version"`
Revision save.Revision `json:"revision"`
NowMS int64 `json:"now_ms"`
HorizonMS int64 `json:"horizon_ms"`
ValueResource string `json:"value_resource"`
ExternalCount int `json:"external_count"`
References []firstHourReferenceResearch `json:"references"`
Anchors []firstHourAnchorResearch `json:"anchors"`
Quotes []firstHourQuoteResearch `json:"quotes"`
}
func TestWaitFirstHourCaptureResearch(t *testing.T) {
suite, err := LoadFirstHourSuite("../..", "balance/testdata/t0-t1/harness-scenario-v1.json", "balance/testdata/t0-t1/first-hour-policy-v1.json")
if err != nil {
t.Fatal(err)
}
var spec RunSpec
for _, candidate := range suite.Scenario.Runs {
if candidate.PolicyID == "reference.greedy" {
spec = candidate
}
}
policy, ok := suite.Policy.Policy(spec.PolicyID, spec.PolicyVersion)
if !ok || policy.ActionCadenceMS != 1000 {
t.Fatal("declared actual reference policy/cadence changed")
}
experiment := FirstHourExperiment{AcquihirePurchasedMinimum: 200, BurnoutPriceFactor: "2e0", RouteKnowledgeBonus: 50, SeedCapital: "1e4", GeneratedBeigeTowers: 10}
baseline, baselineCommands := suite.RunExperimentScript(spec, 0, experiment)
if baseline.Outcome != "completed" {
t.Fatal("actual public runner failed", baseline.InvariantFailures)
}
company, err := newFirstHourCompany(suite.Bundle.Economy)
if err != nil {
t.Fatal(err)
}
founder := &save.State{ReputationLevel: 0, RouteKnowledgeBalance: 0, LedgerFactKinds: map[string]bool{}, NetworkSlots: []save.NetworkSlot{}, ExitHistory: []save.ExitRecord{}}
commands := []FirstHourScriptCommand{}
runtime := firstHourRuntime{suite: suite, spec: spec, policy: policy, seed: 0, experiment: experiment, company: company, founder: founder,
revision: 1, milestones: map[string]*int64{}, lastSession: -1, commands: &commands}
boundaries, err := firstHourBoundaries(policy, 0, spec.HorizonMS)
if err != nil {
t.Fatal(err)
}
encode := func(state *save.State) []byte {
t.Helper()
result, err := save.EncodeState(state)
if err != nil {
t.Fatal(err)
}
return result
}
snapshots := []firstHourSnapshotResearch{}
seen := map[string]bool{}
unique := map[string]bool{}
for _, boundary := range boundaries {
if runtime.transitions >= suite.Scenario.TransitionBudget {
t.Fatal("actual runtime transition guard fired", runtime.transitions)
}
if err := runtime.step(boundary); err != nil {
t.Fatal("actual step failed", boundary, err)
}
for _, target := range []struct {
name string
ready bool
}{
{"run1_first_generator", runtime.company.RunSeq == 1 && runtime.company.GeneratorPurchasedTotal >= 1},
{"run1_tenth_generator", runtime.company.RunSeq == 1 && runtime.company.GeneratorPurchasedTotal >= 10},
{"run2_start", runtime.company.RunSeq == 2},
} {
if !target.ready || seen[target.name] {
continue
}
if err := validateFirstHourCompany(suite.Bundle.Economy, runtime.company); err != nil {
t.Fatal(err)
}
origin := encode(runtime.company)
identity := string(origin)
if unique[identity] {
t.Fatal("declared distinct snapshots collapsed", target.name)
}
unique[identity], seen[target.name] = true, true
ranker, err := runtime.referenceRanker()
if err != nil {
t.Fatal(err)
}
if len(ranker.external) != 0 {
t.Fatal("ordinary first-hour producer unexpectedly has external inputs")
}
nowMS := runtime.company.EvaluatedThrough.Sub(Epoch).Milliseconds()
if nowMS+1000 > spec.HorizonMS {
t.Fatal("snapshot lacks complete declared cadence", target.name)
}
row := firstHourSnapshotResearch{Label: target.name, State: origin, Version: save.VersionForState(runtime.company), Revision: runtime.companyRevision(),
NowMS: nowMS, HorizonMS: 1000, ValueResource: suite.Bundle.Prestige.ValueResourceID, ExternalCount: len(ranker.external),
References: []firstHourReferenceResearch{}, Anchors: []firstHourAnchorResearch{}, Quotes: []firstHourQuoteResearch{}}
project := func(at int64) (*save.State, production.AdvanceSimulationResult) {
t.Helper()
copy, err := cloneState(suite.Bundle.Economy, runtime.company)
if err != nil {
t.Fatal(err)
}
counter := &relevanceCounter{limit: suite.Scenario.TransitionBudget}
advance, err := ranker.advance(copy, runtime.revision, nowMS+at, production.AblationMask{}, counter)
if err != nil || counter.value != 1 || save.VersionForState(copy) != row.Version {
t.Fatal("actual ranker reference failed or changed version", at, counter.value, err)
}
return copy, advance
}
for at := int64(0); at <= 1000; at++ {
copy, advance := project(at)
cash, ok := copy.Ledger.Balance("company.cash")
if !ok {
t.Fatal("actual cash missing")
}
row.References = append(row.References, firstHourReferenceResearch{Cash: cash.String(), Lifetime: copy.LifetimeValue.String()})
if at == 0 || at == 1 || at == 500 || at == 1000 {
row.Anchors = append(row.Anchors, firstHourAnchorResearch{At: at, State: encode(copy), Advance: advance})
}
}
ids := []string{"generator.beige_tower"}
for _, item := range ranker.Policy.Items {
if strings.HasPrefix(item.PurchasableID, "upgrade.") && !runtime.company.UpgradesOwned[item.PurchasableID] {
ids = append(ids, item.PurchasableID)
break
}
}
if len(ids) != 2 {
t.Fatal("declared unowned upgrade population absent", target.name)
}
for _, id := range ids {
resource, cost, err := ranker.candidateCost(runtime.company, id)
if err != nil || resource != "company.cash" {
t.Fatal("actual quote failed", id, resource, err)
}
bits := strconv.FormatUint(math.Float64bits(cost.Mantissa()), 16)
parsed, err := strconv.ParseUint(bits, 16, 64)
if err != nil || !decimal.New(math.Float64frombits(parsed), cost.Exponent()).Eq(cost) {
t.Fatal("quote capture changed internal cost", id, err)
}
counter := &relevanceCounter{limit: suite.Scenario.TransitionBudget}
at, affordable, err := ranker.earliestAffordable(runtime.company, runtime.revision, nowMS, nowMS+1000, resource, cost, production.AblationMask{}, counter)
if err != nil {
t.Fatal("actual private affordability query failed", id, err)
}
query := firstHourQuoteResearch{ID: id, Resource: resource, Cost: cost.String(), CostMantissaBits: bits, CostExponent: cost.Exponent(), At: -1, Affordable: affordable, Transitions: counter.value}
if affordable {
query.At = at - nowMS
copy, err := cloneState(suite.Bundle.Economy, runtime.company)
if err != nil {
t.Fatal(err)
}
advance := production.AdvanceSimulationResult{}
if at > nowMS {
copy, advance = project(at - nowMS)
}
query.Selected = &firstHourAnchorResearch{At: query.At, State: encode(copy), Advance: advance}
}
row.Quotes = append(row.Quotes, query)
}
if !bytes.Equal(origin, encode(runtime.company)) {
t.Fatal("diagnostic query consumed live test runtime")
}
snapshots = append(snapshots, row)
}
if runtime.milestones["milestone.first_elective_exit"] != nil {
break
}
}
observed := FirstHourRunResult{Key: suite.RunKey(spec, 0), PolicyHash: suite.PolicyHash, Outcome: "completed", InvariantFailures: []string{}, ReputationExits: []FirstHourReputationSample{}}
observed.Milestones = firstHourMilestoneReport(suite.Scenario.Milestones, runtime.milestones, &observed.InvariantFailures)
observed.Ending, observed.TransitionCount = runtime.ending, runtime.transitions
observed.ReputationExits = append(observed.ReputationExits, runtime.reputationExits...)
if runtime.milestones["milestone.first_elective_exit"] != nil && (len(observed.ReputationExits) == 0 || observed.ReputationExits[len(observed.ReputationExits)-1].ExitType != "collapse") {
observed.InvariantFailures = append(observed.InvariantFailures, "reputation_exit_unrecorded")
}
if len(observed.InvariantFailures) != 0 {
observed.Outcome = "failed"
}
if !reflect.DeepEqual(observed, baseline) || !reflect.DeepEqual(commands, baselineCommands) {
t.Fatal("manual runtime seam differs from complete public runner/script")
}
if len(snapshots) != 3 {
t.Fatal("incomplete declared snapshot population", len(snapshots))
}
packet := struct {
Schema int `json:"schema"`
Source string `json:"source"`
ConstantsHash string `json:"constants_hash"`
ScenarioHash string `json:"scenario_hash"`
PolicyHash string `json:"policy_hash"`
Artifacts map[string][]byte `json:"artifacts"`
Result FirstHourRunResult `json:"result"`
CommandCount int `json:"command_count"`
Experiment FirstHourExperiment `json:"experiment"`
Snapshots []firstHourSnapshotResearch `json:"snapshots"`
}{1, "first_hour_post_step_reference.greedy_seed0", suite.ConstantsHash, suite.ScenarioHash, suite.PolicyHash, suite.Bundle.Artifacts, observed, len(commands), experiment, snapshots}
data, err := json.Marshal(packet)
if err != nil {
t.Fatal(err)
}
if err := os.MkdirAll("../../.cache", 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile("../../.cache/wait-first-hour-inputs.json", data, 0600); err != nil {
t.Fatal(err)
}
digest := sha256.Sum256(data)
t.Logf("complete public/manual runner and script agree; snapshots%d quotes6 references3003 commands%d transitions%d packet_bytes%d sha256:%s", len(snapshots), len(commands), observed.TransitionCount, len(data), hex.EncodeToString(digest[:]))
for _, row := range snapshots {
t.Logf("%s source_version%d at%d lifetime%s queries%+v", row.Label, row.Version, row.NowMS, row.References[0].Lifetime, row.Quotes)
}
}