aboutsummaryrefslogtreecommitdiff
path: root/internal/game
diff options
context:
space:
mode:
Diffstat (limited to 'internal/game')
-rw-r--r--internal/game/cmd_get.go16
-rw-r--r--internal/game/credits_pickup_test.go44
-rw-r--r--internal/game/economy.go137
-rw-r--r--internal/game/economy_recovery_regression_test.go56
4 files changed, 198 insertions, 55 deletions
diff --git a/internal/game/cmd_get.go b/internal/game/cmd_get.go
index 515d2ab..7a5181f 100644
--- a/internal/game/cmd_get.go
+++ b/internal/game/cmd_get.go
@@ -270,8 +270,10 @@ func (g *Game) doGetAll(sess *net.Session) {
continue
}
if itemID == "credits" {
- taken, ok := g.World.RemoveReservedItem(p.RoomID, itemID, 999999, p.Name)
- if !ok {
+ // Same capped-removal rule as pickupCredits: the request is a
+ // sentinel above any possible stock, not an exact quantity.
+ taken := g.World.RemoveAvailableItem(p.RoomID, itemID, 999999, p.Name)
+ if taken <= 0 {
continue
}
p.Credits += taken
@@ -368,11 +370,11 @@ func (g *Game) doGetAll(sess *net.Session) {
}
func (g *Game) pickupCredits(sess *net.Session, p *player.Player, itemID string) {
- qty, ok := g.World.RemoveReservedItem(p.RoomID, itemID, 999999, p.Name)
- if !ok {
- sess.WriteLine("That's not yours!")
- return
- }
+ // Take whatever credits are accessible: a sentinel quantity far above
+ // any possible stock. RemoveReservedItem is all-or-nothing and would
+ // reject a request larger than the stack; RemoveAvailableItem caps the
+ // removal at what is actually on the ground.
+ qty := g.World.RemoveAvailableItem(p.RoomID, itemID, 999999, p.Name)
if qty <= 0 {
return
}
diff --git a/internal/game/credits_pickup_test.go b/internal/game/credits_pickup_test.go
new file mode 100644
index 0000000..61509e4
--- /dev/null
+++ b/internal/game/credits_pickup_test.go
@@ -0,0 +1,44 @@
+package game
+
+import (
+ "testing"
+
+ "thehouseoficarus/internal/net"
+)
+
+// TestPickupCreditsSentinelQuantity: credit pickups request a sentinel
+// quantity far above any possible ground stock. RemoveReservedItem is
+// all-or-nothing and rejects such a request; the pickup must use capped
+// removal so picking up 10 credits succeeds instead of answering
+// "That's not yours!".
+func TestPickupCreditsSentinelQuantity(t *testing.T) {
+ h := newHarness(t)
+ h.seedAccount("alice", "pw", false)
+ p := h.seedCharacter("alice", "alice")
+ h.g.RunOnOwner(func() {
+ p.Credits = 100
+ h.g.World.AddGroundItem(p.RoomID, "credits", 10)
+ sess := &net.Session{Player: p, Conn: newChanConn()}
+ h.g.pickupCredits(sess, p, "credits")
+ if p.Credits != 110 {
+ t.Errorf("credits after pickup = %d, want 110 (output: %s)", p.Credits, sess.Conn.(*chanConn).Bytes())
+ }
+ })
+}
+
+// TestGetAllPicksUpCreditsWithSentinelQuantity: the same sentinel rule for
+// the "get all" path.
+func TestGetAllPicksUpCreditsWithSentinelQuantity(t *testing.T) {
+ h := newHarness(t)
+ h.seedAccount("alice", "pw", false)
+ p := h.seedCharacter("alice", "alice")
+ h.g.RunOnOwner(func() {
+ p.Credits = 0
+ h.g.World.AddGroundItem(p.RoomID, "credits", 10)
+ sess := &net.Session{Player: p, Conn: newChanConn()}
+ h.g.doGetAll(sess)
+ if p.Credits != 10 {
+ t.Errorf("credits after get-all = %d, want 10 (output: %s)", p.Credits, sess.Conn.(*chanConn).Bytes())
+ }
+ })
+}
diff --git a/internal/game/economy.go b/internal/game/economy.go
index be3f5ef..3d48605 100644
--- a/internal/game/economy.go
+++ b/internal/game/economy.go
@@ -420,8 +420,12 @@ func addCreditsChecked(a, b int) (int, error) {
// 1. Open PAYOUT records are processed in append order against the evolving
// durable balance: file at the pre-payout balance → the payout is
// re-applied (the player is owed it); at the post-payout balance → it is
-// already durable and settles; anything else stays open and is surfaced
-// for operator inspection (a liability is never silently dropped).
+// already durable and settles — UNLESS an earlier recovery run (or the
+// original settlement) already settled a same-checkpoint sibling, in
+// which case the balance is explained by THAT record and this open
+// record is still owed and re-applied; anything else stays open and is
+// surfaced for operator inspection (a liability is never silently
+// dropped).
// 2. Open WAGER records are processed NEWEST FIRST (each refund restores
// the balance an earlier record's checkpoints refer to). A record at
// its pre-debit state (credits AND chips) never became durable → void;
@@ -541,6 +545,75 @@ func (g *Game) recoverEconomy() {
}
}
settled := make(map[string]bool)
+ // settledSiblings counts SETTLED payout records (from earlier recovery
+ // runs; visible in the folded journal) with the same signature as rec.
+ // Each one already explains one durable credit unit of the current
+ // balance: a record moved the balance from `before` to `after` and was
+ // settled, so any other open record with the SAME checkpoints is still
+ // owed — it must never be settled as "already durable" because the
+ // balance happens to sit at `after`.
+ settledSiblings := func(sig payoutSig, selfID string) int {
+ n := 0
+ for j := range folded {
+ other := &folded[j].rec
+ if other.ID == selfID || other.Kind != "payout" || other.Status != "settled" {
+ continue
+ }
+ if other.key() == sig.player && other.CreditsBefore == sig.before &&
+ other.CreditsAfter == sig.after && other.Credit == sig.credit {
+ n++
+ }
+ }
+ return n
+ }
+ // reapplyGroup re-applies every identical open sibling: they were all
+ // journaled against the same in-memory balance and are all owed. Only
+ // the siblings whose re-application actually became durable are
+ // settled; a save failure (e.g. the credit cap) leaves the unpaid
+ // remainder open for operator inspection — a liability is never erased.
+ reapplyGroup := func(group []*economyRecord, p *player.Player, credit int) {
+ paid := 0
+ capBlocked := false
+ for m := 0; m < len(group); m++ {
+ if _, err := addCreditsChecked(p.Credits, credit); err != nil {
+ capBlocked = true
+ break
+ }
+ if err := g.payCreditsDurable(p, credit); err != nil {
+ fmt.Fprintf(os.Stderr, "economy recovery: payout save %s: %v\n", p.Name, err)
+ break
+ }
+ paid++
+ compensated++
+ }
+ for idx, other := range group {
+ if idx < paid {
+ g.Economy.settle(other)
+ settled[other.ID] = true
+ continue
+ }
+ if capBlocked {
+ // The credit cap blocked re-application. Re-anchor the
+ // record's checkpoints to the current durable balance so
+ // a later recovery re-applies it against a balance it can
+ // actually be paid from — without this, the balance a PAID
+ // sibling moved reads as this record's own durability and
+ // the liability is silently settled instead of paid.
+ other.CreditsBefore = p.Credits
+ other.CreditsAfter = p.Credits + other.Credit
+ settled[other.ID] = true // handled for the rest of this run
+ _ = g.Economy.append(*other)
+ continue
+ }
+ // A TRANSIENT save failure blocked re-application and the
+ // balance still has room below the cap: keep the record open
+ // with its ORIGINAL checkpoints. Re-anchoring here would make
+ // the record unreadable against the unchanged durable balance
+ // (before-checkpoint mismatch) and permanently ambiguous; the
+ // original checkpoints let a later recovery retry cleanly.
+ settled[other.ID] = true // handled for the rest of this run
+ }
+ }
for i := range folded {
rec := &folded[i].rec
if rec.Kind != "payout" || rec.Status != "open" || settled[rec.ID] {
@@ -555,54 +628,22 @@ func (g *Game) recoverEconomy() {
switch {
case p.Credits == rec.CreditsBefore:
// The payout (and every identical sibling) was lost in the
- // crash: the player is owed them all. Only the siblings whose
- // re-application actually became durable are settled; a save
- // failure (e.g. the credit cap) leaves the unpaid remainder open
- // for operator inspection — a liability is never erased.
- paid := 0
- capBlocked := false
- for m := 0; m < len(group); m++ {
- if _, err := addCreditsChecked(p.Credits, rec.Credit); err != nil {
- capBlocked = true
- break
- }
- if err := g.payCreditsDurable(p, rec.Credit); err != nil {
- fmt.Fprintf(os.Stderr, "economy recovery: payout save %s: %v\n", p.Name, err)
- break
- }
- paid++
- compensated++
- }
- for idx, other := range group {
- if idx < paid {
- g.Economy.settle(other)
- settled[other.ID] = true
- continue
- }
- if capBlocked {
- // The credit cap blocked re-application. Re-anchor the
- // record's checkpoints to the current durable balance so
- // a later recovery re-applies it against a balance it can
- // actually be paid from — without this, the balance a PAID
- // sibling moved reads as this record's own durability and
- // the liability is silently settled instead of paid.
- other.CreditsBefore = p.Credits
- other.CreditsAfter = p.Credits + other.Credit
- settled[other.ID] = true // handled for the rest of this run
- _ = g.Economy.append(*other)
- continue
- }
- // A TRANSIENT save failure blocked re-application and the
- // balance still has room below the cap: keep the record open
- // with its ORIGINAL checkpoints. Re-anchoring here would make
- // the record unreadable against the unchanged durable balance
- // (before-checkpoint mismatch) and permanently ambiguous; the
- // original checkpoints let a later recovery retry cleanly.
- settled[other.ID] = true // handled for the rest of this run
- }
- case p.Credits == rec.CreditsAfter && len(group) == 1:
+ // crash: the player is owed them all.
+ reapplyGroup(group, p, rec.Credit)
+ case p.Credits == rec.CreditsAfter && len(group) == 1 && settledSiblings(sig, rec.ID) == 0:
+ // The only record with these checkpoints sits at its
+ // post-payout balance: it is already durable, settle it.
g.Economy.settle(rec)
settled[rec.ID] = true
+ case p.Credits == rec.CreditsAfter && settledSiblings(sig, rec.ID) > 0:
+ // A SETTLED sibling with identical checkpoints explains the
+ // balance: an earlier recovery run already re-applied (and
+ // settled) it, or its original settlement moved the balance
+ // here. This open record is still OWED — settling it as
+ // "already durable" because the balance reads `after` would
+ // silently drop the liability (see the
+ // partially-paid-identical-siblings regression).
+ reapplyGroup(group, p, rec.Credit)
default:
fmt.Fprintf(os.Stderr, "economy recovery: ambiguous payout %s for %s (credits %d, want before %d or after %d) — kept open for operator inspection\n",
rec.ID, rec.Player, p.Credits, rec.CreditsBefore, rec.CreditsAfter)
diff --git a/internal/game/economy_recovery_regression_test.go b/internal/game/economy_recovery_regression_test.go
index 1bb3293..241b235 100644
--- a/internal/game/economy_recovery_regression_test.go
+++ b/internal/game/economy_recovery_regression_test.go
@@ -479,3 +479,59 @@ func TestCapBlockedPayoutIsJournaled(t *testing.T) {
t.Fatalf("recovery mutated a capped balance: %d", loaded.Credits)
}
}
+
+// TestRecoveryReappliesPartiallyPaidIdenticalPayouts: two identical payout
+// records were open and an earlier recovery run re-applied (and settled)
+// only the FIRST before crashing again — the second save failed transiently
+// (see TestRecoverySaveFailureRetriesOnNextStartup for the single-record
+// case). The next recovery must NOT settle the remaining record as
+// "already durable" merely because the balance now sits at its
+// post-payout checkpoint: the settled sibling explains that balance, and
+// the open record is still owed.
+func TestRecoveryReappliesPartiallyPaidIdenticalPayouts(t *testing.T) {
+ h := newHarness(t)
+ h.seedAccount("alice", "pw", false)
+ p := h.seedCharacter("alice", "alice")
+ h.g.RunOnOwner(func() {
+ p.Credits = 90
+ if err := h.g.AccountStore.SaveCharacter(p); err != nil {
+ t.Error(err)
+ return
+ }
+ // Two identical owed payouts were journaled against balance 90.
+ if _, err := h.g.Economy.start("payout", p, 0, 20, 90, 110, 0, 0); err != nil {
+ t.Error(err)
+ return
+ }
+ second, err := h.g.Economy.start("payout", p, 0, 20, 90, 110, 0, 0)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ // Simulate the prior recovery run: the first record was re-applied
+ // and settled durably; the second's save failed transiently.
+ if err := h.g.payCreditsDurable(p, 20); err != nil {
+ t.Error(err)
+ return
+ }
+ first := h.g.Economy.loadOpen()[0]
+ if first.ID == second.ID {
+ t.Fatal("setup: expected two distinct records")
+ }
+ h.g.Economy.settle(first)
+ // Recovery over this state: the remaining owed payout must be
+ // re-applied, never settled as "already durable".
+ h.g.recoverEconomy()
+ loaded, err := h.g.AccountStore.LoadCharacter("alice")
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ if loaded.Credits != 130 {
+ t.Errorf("recovered balance = %d, want 130 (remaining owed payout re-applied)", loaded.Credits)
+ }
+ if open := h.g.Economy.loadOpen(); len(open) != 0 {
+ t.Errorf("records left open after recovery: %+v", open)
+ }
+ })
+}