P-LensOpen the app

P-Lens Engineering Notes

Modeling pachinko machines nobody has invented yet

Based on the Japanese article “未来のパチンコ台が分からないから、機種データをコンポーネントに分けた”, restructured for readers outside Japan.

Most data models are written for a domain whose list of cases is, at least for a while, closed. An invoice has lines. A user has roles. A new case turns up now and then, and a migration takes care of it.

P-Lens works with a domain where the list of cases is never closed. It is a bookkeeping app for pachinko and pachislot players, and besides keeping a player’s results it works out theoretical figures for a machine from that machine’s specification: how often it hits, what a hit pays, what happens next. To do that, it has to hold machine specifications as data. And the set of things a machine specification can contain grows every year, because machine makers keep inventing new mechanics, and nobody, the app included, knows what next year’s machines will do.

This article is about how P-Lens models that. Each machine is written as a small world in the shape of an ECS (Entity Component System, the pattern from game development): a list of entities, one table per component keyed by entity, and a few shared resources. What a part of the machine is follows from which tables it appears in, not from a type name. A component the engine does not know is refused by its name. The version number covers the shape, so adding a component does not change it.

None of this depends on pachinko. The same problem turns up wherever the variants of tomorrow cannot be listed today: insurance riders, tax rules that change every year, devices that report different capabilities, card games with new cards each season. A section near the end maps the mechanisms onto those. But pachinko gives the problem in a very pure form, so the article starts there, from zero, for readers who have never seen a pachinko parlor.

All code is quoted from p-lens at v0.10.98 (GPL-3.0-or-later). The pachinko engine is Rust, compiled to WebAssembly for the browser; the screens are TypeScript.

Pachinko, from the start

Pachinko and pachislot are machine games played in pachinko parlors across Japan. A player rents balls (pachinko) or tokens called medals (pachislot) with cash, plays them, and at the end takes what is left to the counter, where they are exchanged for prizes. How that exchange works, and why a parlor never pays out cash, is a story of its own, told in Law shapes the ledger. This article is about the machines.

The machine

A pachinko machine is an upright cabinet with a glass front. Behind the glass is a board studded with brass pins, and in the middle of the board, these days, a large LCD screen. The player turns a handle, and the machine shoots small steel balls, one after another, to the top of the board. They fall back down through the pins. Most of them drop out at the bottom and are gone.

Some of them fall into the start pocket, a small opening below the screen that players call the ヘソ (heh-so, “belly button”). A ball that enters the start pocket does two things. It pays back a few balls. And it starts a lottery: at the moment the ball enters, the machine’s controller draws a random number, and that draw decides whether this is a hit. The animation that follows on the screen, reels spinning, characters shouting, is a presentation of a result that was already decided when the ball went in. Players call one draw a spin (回転, kai-ten).

While one spin is being shown, more balls may enter the start pocket. The machine keeps their draws in a queue (保留, ho-ryoo), usually up to four, and shows them one after another.

The jackpot

The hit is called a 大当り (oh-ah-ta-ri), a jackpot. Its probability is fixed by the machine’s design and printed on its spec sheet as one in so many: 1 in 319.7 has been a common figure for a long time, and lighter machines are 1 in 199 or 1 in 99. Each draw is independent. Nothing builds up, and a machine that has not hit for 600 spins is no more likely to hit on the next one, unless the machine has a feature that says otherwise (there is one, below).

When a jackpot comes, a large pocket at the bottom of the board, the attacker (アタッカー), opens. The player shoots into it, and every ball that goes in pays a fixed number of balls back. The attacker stays open for a fixed number of balls, the count, and then closes; that is one round. A jackpot is a fixed number of rounds. On the test machine used later in this article, each ball into the attacker pays 15 balls and the attacker closes after 10, so one round pays 150 balls for the 10 that went in, a gain of 140, and a 10-round jackpot gains 1,400 balls.

What comes after a jackpot

This is where machines differ, and where the data modeling gets interesting.

A jackpot does not only pay. It also decides what state the machine goes into next. The spec sheet gives this as an allotment (振分, fu-ri-wa-ke): say, half of jackpots are 10 rounds and back to normal play, and half are 10 rounds and into a better state. Normal play is called the regular game (通常時, tsoo-joh-ji). The better states have names of their own, and the main ones are these.

A state reached after a jackpot is, in P-Lens’s words, a mode. On the floor, and on the machine’s own screen, modes are often called RUSH. “RUSH” is a name, not a mechanism: a RUSH may be an ST, a 時短, a 確変 loop, or a combination, and the spec sheet may describe it only by a continuation rate (継続率, kei-zoku-ritsu): “RUSH, 80% continuation”, meaning the chance of each RUSH jackpot being followed by another before the RUSH ends. Players count a run of jackpots as a combo (連チャン, ren-chan).

Features that did not exist ten years ago

Here is a list of mechanics a current machine may have, none of which the plain picture above needs:

Each line is a component waiting to happen. The point for a data model is that they combine. One machine has an ST followed by a 時短. Another has a 時短 with a lucky trigger inside it and a 遊タイム in its regular game. A third splits one RUSH into its first spin and the rest, so that the combo keeps counting across the two.

Pachislot, briefly

Pachislot machines are the other half of the floor. They have three reels and three stop buttons. Each game takes three medals; the player pulls a lever, the reels spin, and the player stops them. A draw at the lever pull decides whether the game has a small win, a bonus (BIG, REG), or nothing, and the reels only show it. Many current machines have AT (assist time): a stretch of games in which the machine shows which order to press the buttons in, so that small wins the player would otherwise miss are lined up and medals grow. A ceiling (天井, ten-joh) guarantees the AT after a set number of games without one. And a pachislot machine has settings (設定, set-tei), usually 1 to 6, chosen by the parlor and not shown to the player, which change the probabilities: the same model plays differently at setting 1 and setting 6.

P-Lens models pachislot machines in the same shape as pachinko machines. This article stays with pachinko, which is the smaller of the two, and comes back to pachislot when it counts tables.

Why the list never closes

The technical rules that pachinko and pachislot machines must meet are set by national regulation in Japan, and every model is tested against them before a parlor may install it. The rules are revised from time to time. Each revision closes some designs and opens others, and makers then invent new mechanics inside the new limits. That is where 遊タイム and c時短 came from: they are answers to a rule, not to a player’s request. New models arrive every month.

For whoever designs the data, a machine specification is a requirements document whose last line reads “and anything invented later”. The features above are the ones known today. The model has to accept the ones that are not.

Types per kind of machine do not survive

The first design that comes to mind is one type per kind of machine. The following is a sketch, written for this article, of a first design one might think of; it is not code from P-Lens:

type Machine =
  | { type: "st-machine"; chance: number; stSpins: number; ... }
  | { type: "rush-machine"; chance: number; continuationRate: number; ... }
  | { type: "st-with-relief"; chance: number; stSpins: number; reliefAt: number; ... }
  | ...

This works for the first three machines. The fourth has an ST followed by a 時短, a lucky trigger inside the 時短, and a 遊タイム in the regular game, and there is no case for it. Add the case, and the fifth machine is the same with a c時短. The number of cases grows with the number of combinations of features, not with the number of features.

Inheritance does not help either. Make an ST machine the parent, and an ST machine with a 遊タイム its child. Then a machine with an ST, a 時短 after it, and a 遊タイム: whose child is it? An inheritance tree can only branch, and features multiply.

The other way out is to branch on the machine’s name: if this is that model, do this special arithmetic. Once that starts, the calculation engine becomes a list of machines. P-Lens has none of it: no code in the engine, or in the TypeScript that prepares figures for the screens, changes a calculation by looking at a machine’s name. A feature the engine lacks comes in as a new component.

A machine as a world

Here is a whole machine specification in P-Lens: the made-up machine the tests use, made-up/spec.json.

{
  "v": 1,
  "entities": ["regular", "RUSH"],
  "components": {
    "regularGame": {
      "regular": { "chance": { "type": "ratio", "numerator": 1, "denominatorHundredths": 10000 } }
    },
    "label": { "RUSH": "RUSH" },
    "allotment": {
      "regular": [
        { "shareBasisPoints": 5000, "rounds": 10, "next": { "type": "regular" } },
        { "shareBasisPoints": 5000, "rounds": 10, "next": { "type": "mode", "mode": "RUSH" } }
      ],
      "RUSH": [{ "shareBasisPoints": 10000, "rounds": 10, "next": { "type": "mode", "mode": "RUSH" } }]
    },
    "rushing": { "RUSH": { "continuationRate": { "type": "percent", "basisPoints": 8000 } } },
    "onMiss": { "RUSH": { "type": "regular" } }
  },
  "resources": { "payout": { "prizeBalls": 15, "count": 10 } }
}

In pachinko terms: a machine that hits 1 in 100.00 in the regular game. Half its jackpots are 10 rounds and back to the regular game, half are 10 rounds and into a RUSH. In the RUSH every jackpot is 10 rounds and stays in the RUSH, which continues at 80%, and when it ends without a jackpot play goes back to the regular game. Each ball into the attacker pays 15, ten balls to a round. Numbers are integers throughout: shares in basis points (5000 is 50%), the probability’s denominator in hundredths.

It has three parts.

The way to read it is across, not down. To find out what RUSH is, collect its row from every table:

entity regularGame label allotment rushing onMiss
regular 1 in 100.00 50% 10R → regular, 50% 10R → RUSH
RUSH “RUSH” 100% 10R → RUSH 80% → regular

RUSH has a label, an allotment, a continuation rate, and somewhere to go on a miss. That is this machine’s RUSH. There is no Rush type anywhere; there is an entity that has rushing. Likewise, regular is the regular game because it has regularGame, not because of its name.

The Rust definition says so in its doc comment (spec.rs):

/// A machine as an ECS world, in the words pachinko uses: its entities — the
/// regular game and the modes a jackpot can lead to — each made of whichever
/// components it has, and the resources the whole machine shares.
///
/// A feature is a component: a mode is a 時短 because it has `rapid`, a
/// 遊タイム is a `relief_drive` on the regular game. A machine the model grows
/// to cover gains a component, not a new shape. Nothing here is a state
/// machine; the engine queries the components and derives one.
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Spec {
    /// Every entity, in the order it was made: the order its states take.
    pub entities: Vec<ModeId>,
    pub components: Components,
    pub resources: Resources,
}

“A machine the model grows to cover gains a component, not a new shape” is the design in one line. The other half of the comment, “Nothing here is a state machine”, comes back below.

The entity’s name is deliberately meaningless to the engine (spec.rs):

/// An entity of a machine: the regular game, or a mode, named as the person
/// writing the spec chose — `regular`, `RUSH`, `LT`, `時短`. Never empty. The
/// engine compares these and never reads them.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ModeId(String);

“Compares these and never reads them”: a name is a key for joining tables, never a source of meaning. A mode called 時短 that has special_time is an ST.

Eighteen tables

At v0.10.98 a pachinko machine can have eighteen components (spec.rs):

/// One table per component, each keyed by the entity that has it.
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Components {
    /// The regular game: how often it hits. Exactly one entity has it.
    pub regular_game: BTreeMap<ModeId, RegularGame>,
    pub label: BTreeMap<ModeId, String>,
    /// How a jackpot won there is allotted.
    pub allotment: BTreeMap<ModeId, Vec<Allotment>>,
    /// An ST: so many spins at a raised chance.
    pub special_time: BTreeMap<ModeId, SpecialTime>,
    /// A 時短: so many spins at the regular game's chance, played fast and
    /// with tulip support.
    pub rapid: BTreeMap<ModeId, Rapid>,
    /// 残保留: the draws still queued when a mode's spins run out, made at
    /// the regular game's chance.
    pub leftover_queue: BTreeMap<ModeId, LeftoverQueue>,
    /// A RUSH as many spec sheets summarise it: a continuation rate given directly.
    pub rushing: BTreeMap<ModeId, Rushing>,
    /// Until the next jackpot, which is certain: a 確変 loop.
    pub until_hit: BTreeSet<ModeId>,
    /// The chance a 確変 loop hits at on each spin, where it is said: what
    /// tells the spins it plays on the 電サポ. Only an `until_hit` entity
    /// has it.
    pub until_hit_chance: BTreeMap<ModeId, ProbabilitySource>,
    /// Where play goes when a mode ends without a jackpot.
    pub on_miss: BTreeMap<ModeId, Next>,
    pub lucky_trigger: BTreeMap<ModeId, LuckyTrigger>,
    /// The regular game's 遊タイム.
    pub relief_drive: BTreeMap<ModeId, ReliefDrive>,
    /// Modes played without the 電サポ — a 潜確 at the heso — whose spins
    /// the support drift does not touch. A leftover queue is played without
    /// it whether it says so or not.
    pub without_support: BTreeSet<ModeId>,
    /// A 時短 that each spin may end early without a jackpot — a c時短 — and
    /// where play goes then. On the regular game, the same: a spin of it
    /// that is no jackpot may lead off to a 時短.
    pub early_end: BTreeMap<ModeId, EarlyEnd>,
    /// The setting level the regular game's figures were read at, on a
    /// machine with setting levels this world does not otherwise tell apart.
    /// It says what the figures are; nothing is worked out from it.
    pub assumed_setting_level: BTreeMap<ModeId, NonZeroU32>,
    /// Whether a mode's spins fill the relief gauge, where the machine counts
    /// them otherwise than its kind does: an ST's spins, which count for none
    /// by kind, on a machine counting every spin; a 時短's, which count by
    /// kind, on one counting only the spins off the 電サポ. Only a mode whose
    /// spins run out has it.
    pub relief_counted: BTreeMap<ModeId, bool>,
    /// Modes whose spins are queued already — drawn off the 電サポ at no cost,
    /// as a leftover queue's are — whatever their kind: a 時短 of a
    /// 一種二種混合機's leftover queue, drawn at the 電チュー's chance. Only a
    /// mode whose spins run out has it, and never with `without_support`,
    /// whose spins are shot and paid for.
    pub queued: BTreeSet<ModeId>,
    /// The mode a mode's combo is counted as part of: a jackpot or a miss
    /// that keeps play among the modes of one such count carries the combo
    /// on, and the lucky trigger of the mode they are part of works from any
    /// of them — a RUSH split into its first spin at the heso and the rest,
    /// or one a chance zone leaves and comes back to with the combo kept.
    pub combo_of: BTreeMap<ModeId, ModeId>,
}

The code’s names are English words chosen for the mechanics, and the comments keep the trade’s Japanese words beside them, so the list reads as a glossary of the section above. rapid is a 時短. relief_drive is a 遊タイム, and its “relief gauge” is the count of dry spins. early_end is a c時短. without_support is a 潜確. queued covers modes whose draws are already in the queue, so they cost nothing to play, as a leftover queue’s do.

A few things are worth pointing out.

Every table is a map from entity to value, and a component with no value is a set: until_hit, without_support and queued carry nothing but “this entity has it”. In JSON, a table no entity has is left out entirely, which is why the made-up machine above shows only five of the eighteen.

Some components describe rather than compute. assumed_setting_level records which setting a machine’s figures were read at, and its comment says “It says what the figures are; nothing is worked out from it.” A component table is a place for facts about the machine, not a promise that the engine does arithmetic with each.

The tables have grown without the shape changing. Several of the eighteen arrived in recent releases. until_hit_chance came with a change to how electric support is costed per spin; relief_counted, queued and combo_of came together in one release. Every specification written before them is still valid as it is, because an entity that has none of a new component simply does not appear in its table.

Now take the machine that broke the union type: an ST followed by a 時短, with a lucky trigger in the 時短 and a 遊タイム in the regular game. In this shape it is not a new type. It is one row in special_time, one in rapid, an on_miss row pointing from the first to the second, a row in lucky_trigger, and a row in relief_drive on the regular game. If the 時短 is a c時短, one more row in early_end. Existing tables gain rows.

Capability is the shape of the data

Tables on their own do nothing. Something has to read them and assemble a regular game and a set of modes. In ECS terms that is a system; in P-Lens it is a set of queries, query.rs:

//! The systems' view of a machine: queries over its components that assemble
//! the regular game and each mode, refusing an entity whose components do not
//! make one — a component missing, two that conflict, or one astray.

The central question about a mode is how it ends: when its spins run out, at the next jackpot, or by a continuation rate. Five components answer it, and the query first collects which of them an entity has, by name (query.rs):

/// The kinds of mode an entity has, by name.
fn kinds_of(spec: &Spec, entity: &ModeId) -> Vec<Component> {
    let components = &spec.components;
    [
        components
            .special_time
            .contains_key(entity)
            .then_some(Component::SpecialTime),
        components
            .rapid
            .contains_key(entity)
            .then_some(Component::Rapid),
        components
            .leftover_queue
            .contains_key(entity)
            .then_some(Component::LeftoverQueue),
        components
            .rushing
            .contains_key(entity)
            .then_some(Component::Rushing),
        components
            .until_hit
            .contains(entity)
            .then_some(Component::UntilHit),
    ]
    .into_iter()
    .flatten()
    .collect()
}

Then it matches on the result as a slice (query.rs):

/// How the mode on `entity` ends, from its one kind component. A 時短 plays
/// at `regular`, the regular game's chance, or its own where it says one, and
/// a leftover queue at `regular`; both fill the relief gauge. An ST plays at
/// its own and does not — unless the mode says otherwise by `relief_counted`.
fn kind_of(
    spec: &Spec,
    entity: &ModeId,
    regular: ProbabilitySource,
) -> Result<ModeKind, SpecError> {
    let counted = spec.components.relief_counted.get(entity).copied();
    let components = &spec.components;
    let missing = || SpecError::MissingKind {
        entity: entity.clone(),
    };
    match kinds_of(spec, entity).as_slice() {
        [] => Err(missing()),
        [first, second, ..] => Err(SpecError::ConflictingComponents {
            entity: entity.clone(),
            first: *first,
            second: *second,
        }),
        [Component::SpecialTime] => components
            .special_time
            .get(entity)
            .map(|special| ModeKind::Runout {
                spins: special.spins,
                chance: special.chance,
                fills_gauge: counted.unwrap_or(false),
            })
            .ok_or_else(missing),
        [Component::Rapid] => components
            .rapid
            .get(entity)
            .map(|rapid| ModeKind::Runout {
                spins: rapid.spins,
                chance: rapid.chance.unwrap_or(regular),
                fills_gauge: counted.unwrap_or(true),
            })
            .ok_or_else(missing),
        [Component::LeftoverQueue] => components
            .leftover_queue
            .get(entity)
            .map(|queue| ModeKind::Runout {
                spins: queue.draws,
                chance: regular,
                fills_gauge: counted.unwrap_or(true),
            })
            .ok_or_else(missing),
        [Component::Rushing] => components
            .rushing
            .get(entity)
            .map(|rushing| ModeKind::Continuation {
                rate: rushing.continuation_rate,
                spins: rushing.spins,
            })
            .ok_or_else(missing),
        [_] => Ok(ModeKind::UntilHit {
            chance: components.until_hit_chance.get(entity).copied(),
        }),
    }
}

No kind is an error, two kinds are an error, and exactly one kind decides what the mode is. An ST, a 時短 and a leftover queue all come out as the same thing, Runout: a mode that ends when its spins run out. What differs between them is only the chance the spins are drawn at, and whether the spins count toward the 遊タイム (fills_gauge).

That last flag is a good example of why the kind comes from the component rather than from the numbers. The 遊タイム counts dry spins. A 時短’s spins count, and an ST’s do not. It would be tempting to infer this from the probability, since a 時短 plays at the regular game’s chance and an ST at a raised one. But an ST can happen to have the same chance as the regular game, and a 時短 on a 一種二種混合機 has a chance of its own. The Rapid component’s comment says it plainly: “Either way its spins fill the relief gauge, as a 時短’s do.” Inference from values guesses; the component says.

When the default turned out to be wrong

For a long time, the kind alone settled fills_gauge: 時短 counts, ST does not. Then machines arrived that count differently: some count every spin toward the 遊タイム, an ST’s included, and some count only the spins played without electric support, so a 時短’s do not count. The kind’s answer was now a default, not a rule.

This is exactly the situation the design was built for, and the change that handled it, in P-Lens 0.10.97, opens its release note with a sentence that could be this article’s thesis: “A pachinko mode’s properties combine apart from its kind”. The new component is relief_counted, a map from entity to bool, present only on machines that count otherwise. In the query it is the counted in counted.unwrap_or(false) and counted.unwrap_or(true) above. Machines that do not say keep the kind’s default, so no existing specification changed.

The tests for that release check each combination against something the engine already solved before (combined_properties.rs):

#[test]
fn an_st_counted_fills_the_gauge_as_a_rapid_mode_at_its_chance() {
    let st = normalize(&counted(with(special_time(100, one_in(50))), true));
    assert_eq!(st, normalize(&with(rapid_at(100, 50))));
    assert_ne!(st, normalize(&with(special_time(100, one_in(50)))));
}

#[test]
fn a_rapid_mode_not_counted_fills_none_as_an_st_at_the_regular_chance() {
    assert_eq!(
        normalize(&counted(with(rapid(100)), false)),
        normalize(&with(special_time(100, one_in(300))))
    );
}

An ST of 100 spins at 1 in 50 that is said to count toward the 遊タイム normalizes to exactly what a 時短 of 100 spins at its own 1 in 50 normalizes to. A 時短 at the regular game’s 1 in 300 that is said not to count is the same as an ST at 1 in 300. Once the property is a component of its own, the “kinds” turn out to be bundles of defaults, and the engine can be checked by showing that two spellings of the same machine come out the same.

The price: refusals instead of types

A model that lets components combine freely also lets them combine wrongly. An entity that is an ST and a RUSH at once. A mode with no way to end. A lucky trigger on the regular game. A c時短 on a mode whose spins never run out.

A union type would make most of these unwritable. The component model gives that guarantee up. A value of type Spec is not, by being one, a machine. The queries decide whether it is, and the errors they can return are part of the design (error.rs):

    /// No entity has the regular game.
    NoRegularGame,
    /// More than one entity has the regular game; a machine has one.
    SeveralRegularGames,
    /// An entity lacks a component it needs: a mode its allotment or where
    /// a miss goes, the regular game its allotment.
    MissingComponent {
        entity: ModeId,
        component: Component,
    },
    /// A mode with none of the kinds — special time, rapid, leftover queue,
    /// rushing, until hit.
    MissingKind {
        entity: ModeId,
    },
    /// An entity with two components that cannot go together: two kinds of mode.
    ConflictingComponents {
        entity: ModeId,
        first: Component,
        second: Component,
    },
    /// A component on an entity the world does not have, or on one it does not
    /// belong to: a 遊タイム on a mode, a kind on the regular game.
    StrayComponent {
        entity: ModeId,
        component: Component,
    },

The enum as a whole is documented as “What can stop a spec being normalised. Each case says where and what, so a form can point at the field rather than print a sentence.” An error is a value naming the entity and the component, so the input screen can highlight the field to fix. And because the errors are phrased in terms of entities and components rather than in terms of features, the list has not grown as components were added. A c時短 on the wrong mode is not a new error; it is a StrayComponent naming EarlyEnd.

Where a component may go is written as plain conditions in the query that assembles a mode (query.rs, the first part):

fn mode_of(spec: &Spec, entity: &ModeId, regular: ProbabilitySource) -> Result<Mode, SpecError> {
    let components = &spec.components;
    let missing = |component: Component| SpecError::MissingComponent {
        entity: entity.clone(),
        component,
    };
    if components.relief_drive.contains_key(entity) {
        return Err(stray(entity, Component::ReliefDrive));
    }
    let runs_out = components.special_time.contains_key(entity)
        || components.rapid.contains_key(entity)
        || components.leftover_queue.contains_key(entity);
    if components.early_end.contains_key(entity) && !runs_out {
        return Err(stray(entity, Component::EarlyEnd));
    }
    if components.queued.contains(entity) && !runs_out {
        return Err(stray(entity, Component::Queued));
    }
    if components.queued.contains(entity) && components.without_support.contains(entity) {
        return Err(SpecError::ConflictingComponents {
            entity: entity.clone(),
            first: Component::WithoutSupport,
            second: Component::Queued,
        });
    }
    if components.assumed_setting_level.contains_key(entity) {
        return Err(stray(entity, Component::AssumedSettingLevel));
    }
    if components.relief_counted.contains_key(entity) && !runs_out {
        return Err(stray(entity, Component::ReliefCounted));
    }
    if components.combo_of.contains_key(entity) && components.lucky_trigger.contains_key(entity) {
        return Err(SpecError::ConflictingComponents {
            entity: entity.clone(),
            first: Component::LuckyTrigger,
            second: Component::ComboOf,
        });
    }
    if components.until_hit_chance.contains_key(entity) && !components.until_hit.contains(entity) {
        return Err(stray(entity, Component::UntilHitChance));
    }

Read as rules: a 遊タイム belongs to the regular game, never a mode. A c時短, a queued mark or a relief_counted flag only make sense on a mode whose spins run out (runs_out is itself computed from which tables the entity is in). A mode cannot be both played at the start pocket and already queued. A mode whose combo counts as part of another’s cannot also carry its own lucky trigger. Dependencies between components are ifs over table membership, not types. ConflictingComponents has grown past its doc comment (“two kinds of mode”) to cover these pairs too, without a new variant.

There is one more check that a relational database would do with foreign keys. Table keys are plain strings, so a spec can name an entity in a table that is not in entities. A function called check_entities walks all eighteen tables, chained one by one, and refuses such a component as a StrayComponent (query.rs).

Since the compiler no longer stops a malformed machine, tests do (validation.rs); made_up() is the same machine as the JSON above:

#[test]
fn a_mode_is_refused_when_its_components_do_not_make_one() {
    let mut kindless = made_up();
    kindless.components.rushing.clear();
    assert_eq!(
        normalize(&kindless),
        Err(SpecError::MissingKind { entity: id("RUSH") })
    );
    let mut twice = made_up();
    twice.components.until_hit.insert(id("RUSH"));
    assert_eq!(
        normalize(&twice),
        Err(SpecError::ConflictingComponents {
            entity: id("RUSH"),
            first: Component::Rushing,
            second: Component::UntilHit,
        })
    );
    let mut aimless = made_up();
    aimless.components.on_miss.clear();
    assert_eq!(
        normalize(&aimless),
        Err(SpecError::MissingComponent {
            entity: id("RUSH"),
            component: Component::OnMiss,
        })
    );
}

Empty the rushing table and the RUSH has no kind. Add it to until_hit as well and it has two. Empty on_miss and it has nowhere to go. All three are well-typed Spec values.

The guarantee is not thrown away so much as moved. What the queries return is strict again: a mode’s ending is an enum, and a Runout cannot carry a continuation rate (spec.rs):

/// How a mode ends, as the engine derives it from its entity's kind component.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ModeKind {
    /// When its spins run out without a jackpot: an ST, a 時短, a leftover
    /// queue. `fills_gauge` when they count toward the 遊タイム: a 時短's
    /// and a leftover queue's, or as the mode's `relief_counted` says.
    Runout {
        spins: SpinCount,
        chance: ProbabilitySource,
        fills_gauge: bool,
    },
    /// At the next jackpot, which is certain: a 確変 loop, at `chance` a
    /// spin where it is said.
    UntilHit { chance: Option<ProbabilitySource> },
    /// At each jackpot, by a continuation rate: a RUSH as its spec sheet
    /// summarises it, lasting `spins` where they are said.
    Continuation {
        rate: ProbabilitySource,
        spins: Option<SpinCount>,
    },
}

So there are two shapes. The loose one, Spec, is what people write, store and send. The strict one, RegularPlay, Mode and ModeKind, is what the arithmetic uses. The loose shape cannot reach the arithmetic without passing the queries, because the engine’s entry point begins with them (normalize.rs):

pub fn normalize(spec: &Spec) -> Result<NormalizedSpec, SpecError> {
    let regular = regular_play(spec)?;
    let modes = modes(spec)?;

Open where the future comes in, closed where the arithmetic happens.

State machines are derived, not written

The specification is not a state machine. “The second jackpot of the RUSH” or “300 spins to go until the 遊タイム” are states, and they appear nowhere in the data.

Take the lucky trigger. What the spec says is this (spec.rs):

/// ラッキートリガー: the jackpot that makes combo `at_combo` in this mode,
/// counting the one that entered it, moves play to `to` rather than keeping
/// it here. Entering a RUSH on a first jackpot and moving to LT at the third
/// in a row is `at_combo: 3` — "3連で LT". A combo of one is the entering
/// jackpot itself, so `at_combo` is at least two.
#[derive(Clone, Debug, PartialEq)]
pub struct LuckyTrigger {
    pub at_combo: NonZeroU32,
    pub to: ModeId,
}

“3連で LT” is how a spec sheet says it: LT at the third in a row. The data says at_combo: 3, the same thing in the same words.

To calculate with it, though, the engine has to remember which jackpot in a row it is at, and a memoryless model of the machine cannot. So the engine expands the mode. The project’s ARCHITECTURE.md puts it in one sentence:

Normalising turns the assembled modes into states; history dependence is lifted into the states (a mode with a lucky trigger becomes one state per combo short of it), never into the solver.

The RUSH becomes “RUSH, first in a row” and “RUSH, second in a row” as separate states, and the jackpot that would make the third goes to LT. Whoever writes the spec never sees those states.

This is the reason the data sits where it does. A spec sheet’s vocabulary and a Markov chain’s states have different grain. Design the data to the sheet’s words and the solver suffers; design it to the solver’s states and every spec becomes a hand-expanded chain that nobody can check against the sheet. The component tables sit between the two, close to the sheet, with the queries and normalization doing the translation.

Versions: the shape, and only the shape

The "v": 1 at the top of the JSON is the version of the shape itself (version.rs):

/// The shape a spec is written in: its entities, a table per component and
/// its resources. A spec says which in `v`, and an engine reads the one
/// shape it knows: a spec in any other version, later or earlier, is
/// refused by that number rather than misread. A component added is no new
/// version — a table an engine does not know is refused by its name — only
/// a change to the shape itself is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SpecVersion(u32);

impl SpecVersion {
    pub const CURRENT: Self = Self(1);

    pub fn get(self) -> u32 {
        self.0
    }
}

“A component added is no new version.” The shape is entities, a table per component, and resources, and adding a table does not change that. So the specification format has been at version 1 while the pachinko tables grew to eighteen. The pachislot side, written in the same shape, has fifty-five component tables at v0.10.98, and its SpecVersion is also 1 (pachislot-domain/src/spec.rs opens with “A machine as an ECS world, in the words pachislot uses”, and adds that “an entity is a bonus because it has bonus, a replay because it has replay”).

The check is an equality, at the boundary where JSON becomes Rust types (convert.rs):

/// A spec is read only in the shape this engine knows: one of another
/// version is refused by its number, whatever else it holds.
fn spec_version(dto: &SpecDto) -> Result<(), ErrorDto> {
    let known = SpecVersion::CURRENT.get();
    if dto.v == known {
        Ok(())
    } else {
        Err(ErrorDto::UnsupportedSpecVersion {
            version: dto.v,
            known,
        })
    }
}

Earlier versions are refused as firmly as later ones. And v has no default: the JSON type documents it as “The version of this shape (SpecVersion): asked for, never assumed.”

There is a second version in the same file, and it moves much more. SchemaVersion is the shape of a normalized spec, the derived state machine that P-Lens stores beside a figure so that a later engine reads it as it was meant. At v0.10.98 it is 5, and each step is documented by what an older reader would miss (version.rs):

/// The shape of a normalised spec. A stored spec says which shape it is in,
/// so a later engine reads it as it was meant rather than as it now would be.
/// 3: a state may say the spins it plays at the heso, and a miss the spins
///    it fills the relief gauge by — a 時短 ended early — which an engine
///    reading 2 would pass over.
/// 4: the regular game may have a c時短, leading off it with no jackpot, which
///    an engine reading 3 would pass over.
/// 5: a state on the 電サポ may say the spins it plays there, which an engine
///    reading 4 would pass over.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SchemaVersion(u32);

impl SchemaVersion {
    pub const CURRENT: Self = Self(5);

The split is the useful part. What people write keeps one stable shape, so a spec typed in a year ago is still valid. What the engine derives may change shape as the arithmetic learns new things, and it carries its own number for that.

Unknown components, refused by name

If adding a component does not change the version, an old engine will one day receive a spec with a table it does not know. The worst thing it could do is ignore the table and calculate anyway: the new feature would silently not exist, and the figure would be wrong with nothing to say so.

So the JSON type keeps unknown tables instead of dropping them (dto.rs and L196–L200; the line // … is mine, standing for the sixteen tables between):

/// One table per component, keyed by entity; a table no entity has is left
/// out. A table this engine does not know is kept in `unsupported` and
/// refused by its name, never misread.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct ComponentsDto {
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub regular_game: BTreeMap<String, RegularGameDto>,
    // …
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub combo_of: BTreeMap<String, String>,
    #[serde(flatten, skip_serializing_if = "BTreeMap::is_empty")]
    pub unsupported: BTreeMap<String, serde_json::Value>,
}

A map marked #[serde(flatten)] collects every key that matched no other field. Anything under components that is not one of the eighteen known tables lands in unsupported, uninterpreted, and conversion begins by checking that it is empty (convert.rs):

fn components(dto: &ComponentsDto) -> Result<Components, ErrorDto> {
    const AT: &str = "spec.components";
    if let Some(name) = dto.unsupported.keys().next() {
        return Err(ErrorDto::UnsupportedComponent {
            field: format!("{AT}.{name}"),
        });
    }

The boundary test uses an invented component, chargeZone (boundary.rs):

#[test]
fn a_component_this_engine_does_not_know_is_refused_by_its_table() {
    let mut spec = value(SPEC);
    spec["components"]["chargeZone"] = json!({ "RUSH": { "spins": 4 } });
    let reply = value(&normalize(&json!({ "spec": spec }).to_string()));
    assert_eq!(
        reply["error"],
        json!({ "type": "unsupported-component", "field": "spec.components.chargeZone" })
    );
}

The refusal names the table, spec.components.chargeZone, so the person reading it knows what the engine is missing.

Where the refusal stops

The rule covers unknown tables. It does not cover unknown fields inside a known table. No struct in the crates is marked deny_unknown_fields, and serde’s default is to skip fields a struct does not have. The Rushing component is an example of a table that grew a field: a RUSH may now give its electric-support spins beside its continuation rate (dto.rs):

#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RushingDto {
    pub continuation_rate: ProbabilityDto,
    /// Its 電サポ回数, left out where the sheet says none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spins: Option<u32>,
}

Reading the code, an engine from before that field would read a RUSH that has spins, skip the field, and carry on, since neither the version nor the table’s name changed. The “refuse rather than misread” policy holds at the level of tables. Below that, it depends on whether a new field is a new fact the old engine can safely not know. That is worth knowing before borrowing the design: either put new meaning in new tables, or decide field by field.

What a new feature costs

The motive was “future machines are unknown”. So what does it cost when one arrives?

The data does not change. The code does, in a fair number of places. The release that added relief_counted, queued and combo_of, P-Lens 0.10.97, touched 26 files with 895 lines added (the count includes the rebuilt WebAssembly binary and version numbers). Following one component through it: a field in the Rust Components, a variant in the Component enum, a link in check_entities, a rule in the query, handling in normalization, a field in the JSON type and its conversion, the TypeScript type, the screens’ reading of the spec, the formula editor, the wording, the grounds the app shows for a figure, and tests, including a new test file for the combinations. Neither SpecVersion nor SchemaVersion changed in that release, and the made-up machine’s JSON has not changed by a character since it was written.

So what the design protects is not “no code changes”. It is two other things:

There is no way to support a machine nobody has invented yet without knowing anything about it. What there can be is a state in which, once it is known, it is clear where it goes.

What was borrowed from ECS, and what was not

The code calls a machine “an ECS world”, so the differences are worth stating for readers who know ECS from games.

ECS in a game P-Lens machine data
Purpose Process many entities every frame Express combinations of features without a type per combination
Number of entities Many A handful per machine (the example has two)
Entities created and destroyed At run time Fixed when the spec is written
Components attached and removed At run time Never; a spec is immutable
Systems Run repeatedly and write components Queries take &Spec and return values of other types; nothing is written back
Frames, schedulers Yes No
Memory layout Packed for iteration BTreeMap

Two ideas were borrowed: define a thing by the components it has, not by its kind, and keep one table per component, keyed by entity. Nothing else was. There is no system loop, no frame and no scheduler, and with a handful of entities per machine there is nothing for a cache-friendly layout to speed up. Strictly, this is not an ECS but an immutable data definition in the shape of one. The world in the comment is a world where nothing moves; it is only queried.

Where else this fits

Nothing above is specific to pachinko. The design pays off wherever three things are true at once: the variants cannot be listed in advance, the features of a variant combine rather than nest, and stored data has to outlive the code that reads it. Some places where that holds, mapped onto the same mechanisms:

Insurance and financial product terms. A policy is a base contract with riders: a waiting period, a deductible, a no-claims discount, an inflation index, a cap per year. Insurers invent new riders as regulation and markets change. Entities: the base cover and each benefit. Components: waiting_period, deductible, annual_cap, indexation. A benefit is “capped” because it has a row in annual_cap, not because it is a CappedBenefit. A pricing engine that meets a rider it does not know refuses the policy by the rider’s name, which is far better than quoting a premium that ignores it.

Tax and tariff rules that change every year. A tax year has bands, allowances, credits and surcharges, and next year’s budget will add one nobody has heard of. Entities: the year’s income categories. Components: band, allowance, credit, phase_out. SpecVersion covers the file format; each year’s rules are data in it. An old calculator given next year’s file with a new phase_out table stops and says so instead of producing a figure that is wrong by the new surcharge.

Device capabilities in IoT. A thermostat, a plug and a sensor hub report what they can do, and next year’s firmware adds something. Entities: a device’s endpoints. Components: on_off, level, color_temperature, battery. A screen shows a dimmer because the endpoint has level, which is capability detected by shape. A controller that meets an unknown capability can show the device with that capability marked unsupported, by its name, rather than guessing.

Card and board game rules. Each new expansion brings cards with abilities that did not exist before, and old cards must keep working. Entities: cards. Components: cost, attack, flying, on_enter, once_per_turn. A card is a creature because it has attack. “Conflicting components” and “stray components” are the rules engine’s validation: a land with attack, a once-per-turn ability on a card with no turn structure. Expanding a stateful ability into states, like the lucky trigger above, is how such an engine keeps its solver simple.

Product catalogs with varying attributes. A shoe has sizes, a laptop has RAM, a bundle has components of its own. Entities: products and variants. Components: size_range, memory, battery_capacity, bundle_of. A product is filterable by memory because it has memory. New categories add tables, not migrations of a giant product table, and an importer refuses a feed with an attribute table it does not know rather than dropping the attribute silently.

Model and pipeline configuration. A training config has an optimizer, a schedule, optional mixed precision, optional checkpointing, and next quarter a new regularizer. Entities: stages of the pipeline. Components: optimizer, warmup, ema, gradient_clipping. A loader that refuses spec.stages.train.new_regularizer by name prevents the most expensive kind of silent misreading: a long run that quietly trained without the setting someone asked for.

In each case the mapping is the same:

Mechanism In P-Lens In general
Entities the regular game and the modes the parts a variant is made of
One table per component rapid, relief_drive, … keyed by ModeId one map per feature, keyed by part
Capability by shape a mode is a 時短 because it has rapid a part can do X because it has X’s component
Kinds as defaults, properties as components relief_counted overrides the kind’s default split a property out the day it varies independently
Refusals as values MissingKind, ConflictingComponents, StrayComponent errors naming part and component, so a form can point at a field
Unknown component refused by name unsupported-component, spec.components.chargeZone never compute with a feature you cannot read
Version the shape, not the content SpecVersion 1 across 18 and 55 tables bump only when the container changes
Derived state stored with its own version SchemaVersion 5 store derived artifacts with the shape they were made in

And the cases where it does not fit: a domain whose variants really are few and stable, where a union type gives a compiler-checked guarantee for free; or a domain where the combinations are so constrained that most of the code would become validation. The component model trades a compile-time guarantee for runtime checks. That trade is worth it only when the list of variants is open.

Loose ends

A few things in the current code are worth knowing about, because they are the costs of runtime checks in particular.

There are two queries. The screens have their own reading of a spec in TypeScript, world.ts, whose comments say that whether the world is well made “is the engine’s to say; this only reads what is there”:

const kindOf = (components: ComponentsDto, entity: string): ModeKind | undefined => {
  const special = components.specialTime?.[entity]
  if (special !== undefined) return { type: "special-time", spins: special.spins, chance: special.chance }
  const rapid = components.rapid?.[entity]
  if (rapid !== undefined) return { type: "rapid", spins: rapid.spins, chance: rapid.chance }
  const queue = components.leftoverQueue?.[entity]
  if (queue !== undefined) return { type: "leftover-queue", draws: queue.draws }
  const rushing = components.rushing?.[entity]
  if (rushing !== undefined) return { type: "rushing", continuationRate: rushing.continuationRate, spins: rushing.spins }
  return components.untilHit?.includes(entity) === true ? { type: "until-hit", chance: components.untilHitChance?.[entity] } : undefined
}

Where Rust refuses an entity with two kinds, this takes the first it finds. The mapping from components to kinds is written twice, and adding a kind means changing both; changing one still compiles.

The list of components is written out in several places. The Components fields, the Component enum, the chain in check_entities, and the five kinds in kinds_of. Nothing ties them together in the type system. Forget the check_entities link for a new table and a component on a nonexistent entity passes. The tables added so far are all linked; what made sure of that was care, not the compiler.

The last arm of kind_of is a catch-all. [_] => Ok(ModeKind::UntilHit { … }) is correct while there are five kinds, because the fifth is the only one left. Add a sixth to kinds_of and forget its arm, and modes of the new kind would be read as 確変 loops without an error.

Replacing type guarantees with runtime checks means watching the checks themselves for omissions.

Summary

Next year’s machines are still unknown. What is known is that they will bring new components.

All articles