Role-Oriented Service Architecture¶
© 2026 S++ project contributors. All rights reserved. Book copyright.
S++ (SPP): Modeling, Language Mechanisms and Engineering Practice
English edition · October 15, 2026
Monetary examples use US dollars (USD), with English participant names. Amounts are illustrative; no exchange-rate conversion is implied. The banking case retains its original currency-specific eligibility rules.
Contents¶
- Part I — The Basic Model of Roles and Services
- Chapter 1 — From Objects to Business Activities
- Chapter 2 — Service Equals Participants Multiplied by Behavior
- Chapter 3 — Roles and Business Identity
- Chapter 4 — Service Categories and Scenario Organization
- Chapter 5 — Quantum Behavior and Quantum Services
- Chapter 6 — Superposition, Commutativity and Entanglement
- Chapter 7 — Queries, Calculations, Validations and Ordinary Updates
- Chapter 8 — Reusing Services and Scenarios Through Role Polymorphism
- Part II — Service Cooperation and Execution
- Chapter 9 — Service Cooperation and Execution Order
- Chapter 10 — Parallel Execution and Service Call Costs
- Chapter 11 — Minimum Service Granularity and Deployment Principles
- Part III — Expressing Roles and Services in S++
- Chapter 12 — Responsibilities of SPP, APP and PHY
- Chapter 13 — Entity, Reference, Role and Contract
- Chapter 14 — Role Composition and take Relationships
- Chapter 15 — Four Categories of Atomic Service
- Chapter 16 — Calculation Rules and Collection Participants
- Chapter 17 — Serial and Parallel Scenarios and Contract Formation
- Part IV — Consistency and Execution Guarantees
- Chapter 18 — Business Facts, Participant Identity and Storage Ownership
- Chapter 19 — Transaction Boundaries, Execution Plans and Deployment Capabilities
- Chapter 20 — Quantum Properties, Call Bounds and Conserved Settlement
- Chapter 21 — Rollback, Inverse Transactions, Reversals and Compensation
- Chapter 22 — Generation, Physical Resources and Runtime Configuration
- Part V — Separating Business and Technology
- Chapter 23 — Benefits of Separating Business and Technology
- Chapter 24 — Performance Through Caching and On-Demand Data
- Chapter 25 — Encryption, Fingerprints and Security Services
- Chapter 26 — Idempotency, Duplicate Guards and Reliable Execution
- Chapter 27 — Runtime Governance and Technical Evolution
- Part VI — Complete Petstore Practice
- Chapter 28 — Identifying Roles, Behavior and Services from Requirements
- Chapter 29 — Zero Opening, Funding and Inventory Receipt
- Chapter 30 — Quotation, Ordering, Payment and Shipping
- Chapter 31 — Cancellation, Returns, Reservations and Failure Handling
- Chapter 32 — Technical Configuration, Deployment and Integrated Verification
- Part VII — Advanced Cases and Architectural Methods
- Chapter 33 — Bank Deposits, Repayment Allocation and Reversal
- Chapter 34 — Migrating an Existing Object-Oriented System
- Chapter 35 — Architecture Review and Capability Boundaries
- Appendices
- Appendix A — The Service Model and Formal Derivations
- Appendix B — Conditions for Exchange, Reordering and Parallelism
- Appendix C — Performance Models and Experimental Methods
- Appendix D — Quantum Services and Conservation Mechanisms
- Appendix E — Language and Engineering Reference
- Appendix F — Sources and Verification Evidence
Part I — The Basic Model of Roles and Services¶
Part I establishes behavior-centered modeling, the participant–behavior service model, role identity, atomic service responsibilities, quantum conservation, and role-based reuse. Execution costs and deployment belong to Part II; language syntax and formal proof obligations are developed in later parts and appendices.
Chapter 1 — From Objects to Business Activities¶
Object-oriented modeling starts with entities and assigns operations to them. Role-oriented modeling starts with a business activity: its objective, participants, rules and completion conditions. Both can use objects; the difference is which concept organizes the model.
The Modeling Subject¶
For a purchase, an object-oriented design may begin with Customer, Product, Inventory and Order, then distribute purchasing across their methods. Each method can be correct while the purchase remains incomplete.
A role-oriented design instead asks:
- What business result constitutes a completed purchase?
- Which participating capacities are required?
- Which facts and changes establish that result?
- Which operations must succeed together?
The model identifies Buyer, Goods and Seller as participating roles; concrete entities provide their facts. Roles are defined in Chapter 3, while the reusable behavior is organized through services and scenarios.
Actions Are Not Complete Behavior¶
Setting an order status, reserving inventory or sending a payment request is an action. Purchasing is a behavior with an objective and a completion criterion. If inventory is reserved but the order agreement is not established, the complete behavior has not succeeded, regardless of the success of an individual operation.
Similarly, serialization and transport are useful operations, but are not business completion criteria. The business result determines which actions matter and which effects require joint settlement or recovery.
One Running Example¶
Alex purchases two units of goods from a store. The activity must establish eligibility, agreed quantity and price, an inventory commitment and an order record. A successful outcome satisfies those terms together. The model then assigns the necessary responsibilities to participants rather than declaring any single object's method to be the whole purchase.
This change of starting point does not eliminate entities or their data. It makes their capacity in an activity and the activity's result explicit. The next chapter gives that relationship a compact expression.
Chapter 2 — Service Equals Participants Multiplied by Behavior¶
A transfer behavior cannot identify a payment without a source, destination and agreed terms. Two accounts, conversely, do not move money merely by existing. A business result depends on both the participating capacities and the behavior applied to them.
The Service Model¶
The conceptual expression is:
B = p × b
B: business activity or result
p: participant (or structured combination of participants)
b: behavior applied in their business capacities
The word service in the familiar phrase “service = participants × behavior” denotes a complete business activity. In SPP's language model, an atomic service has one defined responsibility, while a scenario composes services and participants toward the complete objective. These are different levels of description.
The multiplication sign expresses joint contribution to a business result, not the numerical product of a database object and a function. Its important consequence is that a behavior cannot be interpreted independently of participant roles and their contracts. Payment, refund and wallet funding may share a transfer mechanism but have different sources, destinations, permissions and business meanings.
Contribution, Decomposition and Composition¶
A complex activity can be analyzed into smaller responsibilities:
Purchase = eligibility + quotation + inventory commitment + order formation
This is a decomposition of responsibilities, not an arithmetic equality of money or inventory. A scenario can compose the corresponding services, preserve dependencies and define the common completion result.
For a fixed participant context and a composition operator that preserves the behavior's meaning, one may express a distributive modeling rule:
p × (b1 ⊕ b2) ≡ (p × b1) ⊕ (p × b2)
Here ⊕ means a specified composition of compatible activities and ≡ means equivalence of the intended business result. This is conditional: the component behaviors must have well-defined roles, contracts, ordering and failure semantics; neither the algebraic notation nor S++ syntax alone proves arbitrary distribution or reordering. Appendix A develops the formal assumptions.
The Boundary Between Service and Scenario¶
For payment, querying payer facts, validating eligibility, calculating the amount and transferring funds are separate responsibilities. A scenario binds them to the order and payment agreement, establishes the transaction boundary and determines whether the entire payment completed.
This separation lets a service remain precise without pretending it alone represents the complete business. Chapters 4–7 define the atomic categories and their guarantees.
Chapter 3 — Roles and Business Identity¶
An entity is a concrete business subject; a role is the capacity in which it participates. Product may have a catalog name and specifications, while Goods adds selling status and price. These facts are related but need not have the same owner.
Facts, Qualification and Identity¶
A person can play Buyer and Merchant, but membership tier belongs to Buyer while store identity belongs to Merchant. Creating the person does not automatically establish authorization to trade. Eligibility and role-specific facts must be established for the participation in question.
Conversely, a person or a company may play Buyer when each satisfies the Buyer's contract. Role polymorphism is treated in Chapter 8; here the issue is how the participating identity is modeled.
Relationships Can Be Roles¶
A cart line depends on both a Buyer and Goods. Its quantity is a fact of their relationship, not a permanent property of either player alone. A composed role can express those participants together:
Role CartLine {
Buyer;
Goods;
int quantity;
}
A role can itself play another role. Goods used in an OrderLine may provide current product facts, while OrderLine separately retains agreed quantity, unit price and description. A later price or name change must not rewrite the historical agreement.
Composition Is Not Flattening¶
A participant member declares intrinsic role composition. When a take relationship supplies players, it joins them with those required members; distinct take alternatives are not replacements for the role's intrinsic structure. Intermediate role identities remain meaningful. Chapter 14 specifies these rules.
A service names each participant once by its role. If two cash drawers appear in a transfer, source and destination are distinct participating roles even if they have the same underlying entity type; Chapter 15 shows how rules refer to them.
Extensible roles also have stable storage identities. APP maps player associations without replacing a role's own primary key; inline versus separate-table storage is a technical choice, not a change in business uniqueness.
Roles therefore distinguish what an entity is, how it participates and which facts belong to that participation.
Chapter 4 — Service Categories and Scenario Organization¶
A business scenario should expose distinct responsibilities rather than disguise an entire workflow as one operation. SPP classifies business services by the effects they are allowed to have.
Business and Technical Responsibilities¶
Checking whether a buyer may pay is a business validation. Checking a message signature is technical security. The former belongs to business meaning; the latter supports trustworthy execution. Protocols, serialization and database connections should be provided through technical contracts without changing the underlying business rule.
Atomic Categories¶
| Category | Responsibility | Payment example |
|---|---|---|
| Query | Obtain and confirm participant facts | Load order and payer |
| Validation | Decide whether execution may continue | Check eligibility |
| Calculation | Derive results from prepared facts | Determine amount due |
| Update | Apply prepared business changes | Transfer funds or save a receipt |
The update category has two distinct forms:
- Ordinary update persists descriptive facts or status, such as an address or order state.
- Quantum service applies conserved deltas to quantifiable transaction properties, such as balances or available/reserved inventory.
Classification follows meaning, not data type: a numeric selling price may be descriptive, while inventory quantity is transactional. Quantum services receive their own definition in Chapter 5.
Scenarios Define Completion¶
A payment scenario identifies participants, confirms facts, validates conditions, prepares the amount, settles funds and records the agreed outcome. Not every scenario uses every category—for example, quotation can finish without settling a quantum change.
The atomic categories make effects visible. The scenario provides the composition, ordering, boundary and completion criterion. Detailed call restrictions appear in Chapter 7; the language syntax appears in Part III.
Chapter 5 — Quantum Behavior and Quantum Services¶
A descriptive update records information; a quantum service transfers a measurable business quantity. Money, stock and reserved inventory require source, destination, amount, bounds and a settlement result rather than merely a new stored value.
Definition and Minimum Unit¶
A quantum service is the conserved transfer between two quantum properties within one business dimension. Its minimum unit is a paired decrement and increment:
A.balance -= 100 USD
B.balance += 100 USD
sum of deltas = 0 USD
The two changes form one indivisible business transfer. Crediting B without debiting A, or committing only A, does not satisfy the service. Different dimensions such as USD and item counts are not added to claim conservation. Sources for wallet funding or inventory receipt must also be explicit, even when the counterparty is an internal account or supply role.
Deltas Instead of Stale Values¶
Suppose a wallet is queried at 500 USD, receives 20 USD and then makes a 100 USD payment. A stale assignment of 400 would lose the receipt. The transfer instead applies −100 to the settled state, yielding 420 USD if those are the only changes.
The service describes the change rather than fixing the eventual observed balance. The executor must check the permitted bounds against the authoritative state and decide the complete conserved transfer. Chapter 20 describes call bounds and settlement; this definition makes no promise that application-side reads protect them.
Settlement Guarantees¶
A correct quantum execution must provide:
- Atomicity and conservation: the paired change succeeds or fails as one result.
- Bound enforcement under contention: simultaneous debits cannot overspend a lower bound.
- Idempotent confirmation: retrying after a lost response must not repeat a settled transfer.
- Traceability and inverse recovery: original deltas and identity remain available for reversal without overwriting later changes.
These are required semantics, not automatic consequences of writing two arithmetic expressions. Execution protocols, failure recovery and deployment guarantees are developed in Part IV and Appendix D.
A scenario can combine quantum settlement with ordinary updates, such as recording the order receipt. Its completion rule must account for both. The next chapter examines the properties of delta-based execution.
Chapter 6 — Superposition, Commutativity and Entanglement¶
S++ borrows three words from quantum physics as architectural analogies, not claims of physical quantum computation. They describe how uncertain observations, additive deltas and conserved relationships affect transaction execution.
Superposition: The Observed Value Is Not Fixed by One Delta¶
A query sees 1,000 USD and a quantum service settles a debit of 100 USD. If an independent debit of 200 also settles, a later observation may show 700 USD rather than 900 USD. Confirmation establishes whether this service's delta settled; observation establishes the balance at a particular point. Neither result implies the other.
Thus “superposition” denotes uncertainty of the observed value relative to an earlier read and the service's own delta. It does not mean that settlement itself can remain ambiguous after a confirmed outcome.
Commutativity: A Conditional Result Property¶
For fixed deltas d1 and d2 on the same property, arithmetic addition commutes:
(x + d1) + d2 = (x + d2) + d1
If both changes are admitted and settle under equivalent constraints, their joint final value is order-independent. This does not prove that every proposed execution order is admissible. For example, with balance 100, lower bound 0 and deltas −150 and +80, a sequential debit-first plan fails at −50 while the combined net change yields 30. Per-command net-bound checks and atomic decision boundaries therefore matter; Chapter 20 specifies the applicable runtime semantics.
Commutativity also does not allow arbitrary reordering of reads, validations, ordinary saves or failure-sensitive business decisions. Appendix B sets out the required independence and conflict conditions.
Entanglement: Conservation Couples Effects¶
A transfer's debit and credit are coupled by a conservation requirement:
Δsource + Δdestination = 0
Both parts must share the settlement outcome. This is the borrowed meaning of “entanglement.” It is a business invariant, not a physical quantum state. In inventory reservation, available decreases while reserved increases by the same quantity of the same item; dollars and items are separate conserved dimensions.
Combining Quantum Commands¶
Two fixed transfers from A, one of 100 to B and one of 200 to C, may be represented by aggregate deltas:
A: −300, B: +100, C: +200
Aggregation can reduce requests and allow an executor to make a coordinated decision, provided identity, bounds, conservation, atomic groups and failure semantics are retained. A mathematical equality of final sums alone does not authorize merging transactions with different contracts or independently significant results. Appendix D develops the execution mechanisms.
Chapter 7 — Queries, Calculations, Validations and Ordinary Updates¶
Non-quantum atomic services retrieve, derive, judge and persist business facts. Their separation prevents hidden side effects and makes a scenario's dependencies inspectable.
Query: Confirm Existing Facts¶
A built-in query completes required participant facts through APP/PHY mappings. An absent participant is not the same as an unavailable source. Queries may overlap only when their inputs are ready and their in-memory completion ranges do not conflict; the scheduling rules appear in Part II and Appendix B.
Calculation: Derive Prepared Results¶
A calculation uses facts already present and writes derived results, such as quantity × agreedUnitPrice or an order subtotal. It does not access repositories, perform validation, save facts or start a scenario. The explicit exception to the atomic no-call rule is calculation-to-calculation reuse.
Calculation call graphs must be acyclic, including indirect calls. Loops over lines are permitted, but an iterative formula must still have a termination rule. A scenario obtains missing facts and validates business preconditions before invoking calculations that require them.
Validation: Control Execution¶
A validation judges eligibility or consistency without changing participant facts. A failed validation stops its enclosing execution scope: directly in a transaction block it causes rollback; inside a nested serial block it ends that block. breakTransaction explicitly rolls back from any depth. The caller's scenario structure therefore matters to the meaning of rejection.
Validations do not call other validations or scenarios. Calculations derive amounts; validations decide whether the prepared conditions permit continuation.
Ordinary Update: Save Complete Facts¶
Ordinary updates are built-in; application authors do not supply their implementations. They persist descriptive properties or status using facts prepared by earlier queries, calculations and quantum results. They do not conceal additional business queries or calculations.
Within a transaction boundary, the generated plan places quantum transactions before ordinary saves. When further preparation is needed after settlement, a serial phase completes it before the relevant save. Independent, fully prepared saves can then run concurrently. This intra-transaction freedom must not be confused with conflict protection between separate requests updating the same record.
Scenario: The Only General Composition Layer¶
Atomic services keep one responsibility; scenarios combine them and express dependencies, serial groups, transactional boundaries and completion. An order-payment scenario can query roles, validate terms, calculate the due amount, perform quantum settlement and then save the order and receipt. The ordinary save cannot start before its inputs exist.
These constraints let readers locate business decisions and side effects. Language-level forms are specified in Chapters 15–17; dependency analysis, concurrency and deployment are developed in Part II.
Chapter 8 — Reusing Services and Scenarios Through Role Polymorphism¶
Role polymorphism allows different entities to participate in an existing business behavior through the same role contract. It reuses responsibilities without treating different natural entity types as identical.
Substitution Through a Business Contract¶
An individual and a company can both play Buyer if they provide the required identity, facts and qualifications. A purchasing scenario then consumes Buyer, not a branch for each underlying entity type. Role bindings and query mappings supply the relevant data.
Substitution is valid only when the role's semantics are satisfied. Mapping a company name into a buyer-name field is not sufficient if credit terms, eligibility, address or ownership rules differ. The role contract, not mere structural resemblance, establishes compatibility.
Reuse at Three Levels¶
- Calculation:
priceLinemultiplies an OrderLine's agreed unit price by quantity regardless of whether its Goods player is food or toys. - Validation: a quantity or payment-eligibility check evaluates role facts, not the runtime class of the buyer.
- Scenario: quotation and purchasing organize existing role-based services and can accept new players without duplicating the workflow.
The reuse boundary is the business contract. A company using the same purchasing rules mainly needs a correct Buyer relationship and fact mapping. A company requiring approval limits, credit settlement or a different discount policy changes behavior, so the relevant roles, calculations, validations or scenario steps must change explicitly.
What Polymorphism Does Not Guarantee¶
Role substitution does not automatically make two storage schemas, transaction protocols or deployment configurations equivalent. APP and PHY must still provide required facts and runtime guarantees. Nor does it eliminate domain-specific rules: adding a new kind of buyer is simpler when the contract remains stable, but a new purchasing policy is a real change in the model.
The principle is therefore precise: entities may vary while services and scenarios remain reusable to the extent that their required role contracts and behavior stay unchanged. Part II next examines how those fine-grained responsibilities can execute efficiently.
Part II — Service Cooperation and Execution¶
Explain each wait in ordering before deciding which queries and calculations can overlap. These three chapters discuss cooperation, call costs and deployment boundaries. Formal proofs and performance derivations appear in Appendices B and C.
Chapter 9 — Service Cooperation and Execution Order¶
Ordering requires buyer facts and goods prices before quotation. It does not require the buyer query to finish before the goods query starts. The execution order should follow the dependencies of the business, not the order in which its source happens to be written.
Three Sources of Waiting¶
| Source | Example | Consequence |
|---|---|---|
| Business agreement | Verify returned goods before refunding | Preserve the policy |
| Data dependency | Calculate subtotal before a discount that uses it | Preserve the producer–consumer relationship |
| Code arrangement | Query buyer and goods successively despite independent inputs | Remove unnecessary waiting |
The first two impose genuine constraints. The third is an execution choice, provided the operations do not interfere.
Dependencies and Join Points¶
A scenario can be understood as a dependency graph. Each operation consumes prepared inputs and produces facts, decisions or effects. An edge represents a required precedence, not necessarily a remote call.
┌─ Query buyer ─┐
Prepare inputs ───┤ ├─ Eligibility ─ Quote ─ Prepare inventory ─ Settle
└─ Query goods ─┘
At the join, both queries must have completed with usable results. An absent participant or technical failure prevents normal quotation. A parallel plan must also define what happens to outstanding branches and effects when execution fails.
Independence requires more than distinct service names. Queries fill in-memory facts and may conflict if they write the same property. Line calculations may run independently, but their subtotal must await the required results; concurrent writes to one accumulator require a safe reduction.
Settlement and Shared Writes¶
Two requests each reading a wallet of 100 and attempting to debit 80 may prepare concurrently. With a zero lower bound and no other changes, at most one debit can settle. Scheduling alone cannot enforce that invariant. Likewise, debit and credit must share a settlement outcome.
Under the quantum-first plan in Chapter 7, independent ordinary saves may overlap once settlement results and all required facts are ready. Conflicting writes still require protection, and completion must honor the transaction boundary.
The method is to identify inputs and outputs, preserve business and data dependencies, check interference, and specify join and failure semantics. Appendix B develops the formal conditions and counterexamples.
Chapter 10 — Parallel Execution and Service Call Costs¶
Fine-grained business services improve the precision of modeling, but treating each service as a remote endpoint can multiply communication, encoding, queueing and coordination costs. SPP separates the business decomposition from the execution plan so that independent waits can overlap and unnecessary calls can be avoided.
Latency and the Critical Path¶
Suppose buyer and goods queries take 40 and 70 milliseconds respectively, followed by a 10-millisecond quotation. With independent queries and sufficient execution resources:
Serial: 40 + 70 + 10 = 120 ms
Concurrent: max(40, 70) + 10 + overhead = 80 ms + overhead
These are illustrative durations, not benchmark results. The ideal saving is 40 milliseconds before scheduling and join overhead. The total work is not reduced merely by overlapping it.
More generally, for a dependency graph with operation durations tᵢ, serial execution takes their sum; the longest dependency path gives a lower bound on parallel completion time. Actual latency also depends on resource contention, communication and coordination. Parallel execution is beneficial only when the avoided waiting exceeds its added costs.
Three Complementary Mechanisms¶
| Mechanism | Effect |
|---|---|
| Concurrent independent services | Overlap database or network waits |
| Merged quantum requests | Reduce repeated transport and protocol overhead while retaining settlement semantics |
| Local calculations and validations | Avoid remote calls for prepared-data rules |
Independent ordinary saves can also overlap after the quantum phase and required preparation. The dependencies and admission conditions of Chapters 6, 7 and 9 remain binding; neither merging nor concurrency permits arbitrary reordering.
Performance Is Not Availability¶
Traditional microservices may justify separate deployment through isolation, independent scaling or ownership. However, more required remote dependencies can increase the opportunities for a scenario to fail. Overlapping calls reduces waiting, not the number of required successful dependencies.
A saturated database, limited connection pool or shared executor can eliminate parallel gains or increase tail latency. Evaluate equivalent business rules and commit guarantees using response-time distributions, throughput and resource consumption. Appendix C develops the performance models and experimental conditions. Chapter 11 addresses the deployment choices that determine these costs.
Chapter 11 — Minimum Service Granularity and Deployment Principles¶
The minimum business service is a modeling boundary, not a process boundary. SPP defines that minimum before choosing where services execute.
Minimum Business Granularity¶
| Service | Minimum responsibility |
|---|---|
| Quantum | A conserved change between a pair of quantum properties |
| Query, calculation, validation, ordinary update | A defined operation on a role |
A debit alone is not a complete quantum transfer; its counterpart is indispensable (Chapter 5). A role operation, such as querying Buyer or calculating an OrderLine amount, may use only some properties. A field accessor, multiplication or comparison is an expression inside that operation, not a smaller independent business service.
Calculation reuse and scenarios compose these units. Merging quantum requests does not change their underlying minimum responsibilities.
Role Granularity Does Not Determine Data Volume¶
A role query need not retrieve every property in its role-playing chain. Property usage in scenarios, calculations and validations can be collected at compilation to identify required facts. Quotation may need membership tier, eligibility may need status, and delivery may need address; unused customer data need not be loaded.
Request-level caches can avoid repeated reads within a scenario, and shared caches can reuse sufficiently stable facts across requests. APP/PHY mappings and freshness policies determine when such reuse is valid. Cached observations do not replace authoritative money or inventory settlement.
On-demand loading reduces data per read; caching reduces the number of reads. Neither requires splitting roles into property-level services. Appendix C13 and Part V develop these optimizations.
Deployment Granularity Is an Independent Choice¶
A process can host many independently defined services. Calculations and validations over prepared facts generally suit local execution. Queries may execute locally or remotely according to fact ownership, and independent queries can overlap. Quantum requests may be combined when their contracts permit it; independent ordinary saves follow the required settlement and preparation phases.
Separate deployment can be justified by scaling, resource isolation or team ownership. Co-location reduces communication and may simplify coordination without changing the logical service responsibilities.
Deployment Must Honor Transaction Boundaries¶
Petstore's develop environment hosts four domains in one process using LOCAL; testing separates customer, product and shop applications. The business model remains the same, but execution costs and commit capabilities differ.
Co-located services sharing a suitable transactional resource can coordinate quantum and ordinary changes in a local transaction. Separate resources or processes require supported coordination or explicitly modeled phased settlement and recovery. Co-location alone does not guarantee atomicity, and distribution alone does not provide a joint commit protocol.
Model at the defined minimum; deploy according to dependencies, capacity, communication cost and transaction guarantees. Fine-grained business expression need not entail fine-grained remote deployment.
Part III — Expressing Roles and Services in S++¶
SPP, APP and PHY separate business from technology and logic from physical implementation, clarifying the work of requirements specialists, technical developers, operators and AI. We then express the model in source. Goods, carts and funding examples introduce role playing, atomic services and scenarios as checkable declarations.
Chapter 12 — Responsibilities of SPP, APP and PHY¶
S++ separates business from technology, and technical logic from physical implementation. SPP defines the business; APP declares the technical contracts needed to execute it; PHY supplies environment-specific resources.
Business and Technical Responsibilities¶
SPP defines participants, roles, contracts, calculations, validations, scenarios and required transaction boundaries. A membership discount belongs in SPP; SQL, transport and external-system integration do not. Requirements specialists familiar with the language can express compilable business models, while technical developers connect their roles and contracts to actual systems.
APP organizes repository mappings, bindings, interfaces, duplicate protection, numbering, logical resources and environment deployment. PHY selects databases, protocols, numeric representations, endpoints and runtime resources. Developers implement or adapt capabilities; operators configure them. A new protocol or representation may first require an adapter before PHY can select it.
How Three Layers Complete Payment¶
| Layer | Content | Primary Responsibility |
|---|---|---|
| SPP | Buyer, merchant, agreement, qualifications, amount and transaction boundary | Business developers or requirements specialists familiar with the language |
| APP | Storage mappings, bindings, interfaces and technical contracts | Technical developers and integrators |
| PHY | Databases, endpoints, resources and physical representations | Operators, with adapters supplied by technical developers |
SPP expresses buyer −100 and merchant +100 and the order-receipt result. APP organizes storage and integration, selecting execution that honors the boundary. PHY supplies actual resources.
Order numbers with direct business use can belong to SPP. Internal storage keys are supplied by compiler and system, without an extra business ID. Rounding is business; machine representation and storage capacity are physical. These distinctions preserve meaning while separating maintenance.
Deterministic Generation and Review¶
Compilers, generators and runtimes derive repeated model, mapping, query/save integration, interface and storage code from declarations. Given the same source, configuration and tool version, deterministic transformations reduce the amount of implementation code that humans or AI must independently maintain.
Business specialists can review the roles, formulas, conditions and settlement results against requirements. Technical developers review mappings and adapter guarantees; operators review resources and configuration. AI can focus changes on the relevant layer rather than regenerate mixed business and infrastructure logic.
Generation does not prove business correctness or adapter guarantees. Requirements, exceptions, expected results and actual execution still require validation; toolchain changes need their own targeted review.
Locate a Change in Its Layer¶
Membership discounts change SPP calculations; new customer systems change APP adaptation; production endpoints and connections change PHY.
The following chapters introduce source expressions. Part V, Chapters 23–27, extends the benefits and technical services for performance, security, reliability and governance.
Chapter 13 — Entity, Reference, Role and Contract¶
Types answer different questions. Entity is a natural entity owned by the current domain; Reference points to an external-domain concept; Role is participating identity; Contract records an agreement formed by a scenario. Together they explain meaning and lifecycle ownership.
Natural Entities and External References¶
The customer domain owns Person and the product domain Product. The shop uses their facts, but the original domains own their lifecycles. Reference makes origin explicit; APP and PHY determine integration.
References can target provider entities, roles or contracts. They identify fact sources without taking lifecycle maintenance away from providers.
Roles and Scenario Contracts¶
Buyer expresses shopping identity and Goods sales identity. ShopOrder records ordering terms; PaymentAgreement payment terms. Later payment, shipping and return scenarios can reference an order without repeating ordering.
A short Petstore contract is:
Contract WalletFundingAgreement {
Buyer buyer;
SettlementAccount source;
BigDecimal(19, 2) amount;
}
Participants and amount describe one funding activity. The contract records terms; services implement changes.
Constituent Facts and Independent Participants¶
Order lines retain goods, quantity and agreed unit price. Total is a constituent fact of the agreement, not necessarily a separate amount role. Independent roles require real participation and lifecycle meaning.
Aggregating lines in a contract does not mean the contract plays each line. Composition and role playing are separate relationships.
Internal Keys and Business IDs¶
S++ provides a business-invisible internal entity key for technical identity. Database uniqueness alone does not justify declaring a business id.
Habitual fields such as id or customerId can imply nonexistent business credentials. The compiler checks suspicious habitual IDs and warns developers to confirm real meaning.
Where an ID truly serves business, business explains its purpose and removes the warning. A receipt identifier used by customers to query results is one example:
Entity Receipt {
business("Business receipt number used by customers to look up and verify the outcome") String receiptId;
}
Review asks who uses the number, in which activity and how it supports processing or verification. The business annotation explains that purpose rather than merely asserting uniqueness.
Models are organized by membership, goods, cart, orders and other functions. See the Petstore source guide.
Chapter 14 — Role Composition and take Relationships¶
A role is both a business identity and the structure consumed by services. It does not depend on a particular player, but its members must be explicit. Participant members declare intrinsic composition; ordinary properties describe facts belonging to that composition.
Intrinsic composition needs no repeated take¶
Role CartLine {
Buyer;
Goods;
int quantity;
}
Buyer and Goods are already intrinsic participants. Repeating take Buyer, Goods as CartLine and assigning the same players to the same members adds no information. Services read cartLine.buyer, cartLine.goods and cartLine.quantity. Generated Java/JSON keeps ordinary bean property names.
Declaring only quantity and silently adding members through an empty take would leave the service contract incomplete. Explicit member names remain valid. Two Buyer members must be distinguished by name; a type alone cannot select between them.
take adds players rather than replacing intrinsic roles¶
take ReservationSource as CartLine;
Assuming ReservationSource is declared, this branch jointly combines Buyer, Goods and ReservationSource. Quantity remains a role fact. Commas within one take mean joint participation; separate take clauses are alternatives. Intrinsic participants join every alternative.
Role R;
take A as R;
take B as R;
take C, D as R;
With A, B, C and D declared, the valid combinations are {A}, {B} or {C, D}. Each R row selects one complete combination. Separate A and B clauses do not make them joint; C and D must both be present.
Role R { R1; R2; }
take A as R;
take B as R;
take A, B as R;
With the referenced types declared, the valid combinations are {R1, R2, A}, {R1, R2, B} or {R1, R2, A, B}. R1 and R2 are mandatory. Intrinsic composition alone is the default only when no explicit take exists. Persistence requires one complete declared combination.
At run time, takes whose participants a request supplies together are joint; supplying only one take's participants selects that take. A role never found or filled remains blank and unidentified: shared performers do not materialize it, and a sibling lookup retains its own key. Inactive player identities are null in inline storage or absent in separate association storage.
If Person plays Buyer and Product plays Goods, the composition can be traced to those sources. Buyer and Goods remain distinct intermediate business identities.
An identity-only role is also valid:
Role Goods;
take Product, Package as Goods;
The players are explicitly composed, but their entire property sets are not automatically flattened into Goods. Declare the facts needed by services and map their sources. A role with no properties can still express an identity.
Participant binding and scalar mapping¶
A unique match between an existing member and its player produces an automatic whole-participant mapping. Explicit mappings remain available, but must target declared members and must not silently add fields.
Role OrderLine {
Goods;
String name;
BigDecimal(19, 2) unitPrice;
int quantity;
}
take Goods as OrderLine {
String name = name;
BigDecimal unitPrice = price;
}
The Goods relationship is intrinsic. The scalar mappings select goods name and price as the sources of order-line facts. Explicitly resolve competing sources.
mapsame; enables compatible same-name mappings; it is not implied by an empty take block. Retrieving Product.name does not by itself select it as Goods.name. The existing takeall; keyword is a compatible explicit property-import form; new models should prefer complete Role declarations so service dependencies remain visible.
Participant collections retain their element identities. They are not converted into one scalar player. Explicit member names remain necessary when several members share a type.
Binding a player in APP¶
An SPP take joins roles in the business model. APP can also bind a role to a player from another domain with play. The Petstore application binds its buyer to the customer domain's person:
play Buyer by customer.Person {
customerNumber = customerNumber;
name = name;
email = email;
address = address;
}
The mapping lists the role facts that the player supplies. A role carries all facts of its player: the APP play when there is one, otherwise the first take in declaration order. Further takes of the same role only map their own sources onto those facts and add none. Two roles played by one entity, such as a giving and a receiving position, therefore address the same stored facts under different business names. A role passed where its player is expected books the player's quantum position, so a transfer between two roles of one player moves one conserved attribute between two positions.
Stable independent identity and APP storage¶
Extending composition must not change an existing role identity. A role table without an explicit key receives an APP-only String roleId. A named independent key can be declared as follows:
tables roles {
table SHOP_CART_LINES(CartLine) {
primarykey notnull String cartLineId;
identity independent;
performers in SHOP_CART_LINE_PLAYERS;
}
}
Insertion generates the technical identity; later CRUD uses it. SPP neither declares nor modifies cartLineId. Player keys are relationship facts, not the default role primary key. Explicit historical business/composite keys remain supported. Business uniqueness and physical identity are separate concerns.
performers inline; stores player identity records in the role table. performers in TABLE; uses a separate association table joined through the stable role identity. The current JDBC realization uses technical per-player identity columns for the inline layout, and role_type, role_id, performer_type and performer_key for the separate layout. These contain identities, not copies of all source-domain facts.
Role and association writes use the same local transaction resource and roll back together. Nested participants carry technical identity through private persistence metadata rather than business properties. The current/snapshot policy for ordinary facts is independent of this layout; agreed order prices still belong to the role's snapshot storage.
New relationships do not backfill historical business facts. Business rules determine whether they are required. Adding inline columns requires a schema migration; separate tables can receive new association rows, but cannot invent real relationships. APP selects layout; PHY selects the database and deployment. Neither changes business cardinality or obligations.
See the composition and storage specification.
Chapter 15 — Four Categories of Atomic Service¶
Ordinary business atomic services are query, check, calculate and update. They retrieve facts, judge conditions, form candidate results and apply changes. Scenarios combine them into complete activities.
Queries Complete Facts¶
Ordinary query is built-in. Scenarios call findBuyer and similar services directly; APP/PHY retrieve facts and complete input participants without redeclaring standard queries. There is no business return value such as buyer = findBuyer(). Identity confirmation is execution state, not inferred from nonempty fields. Completion need not load the whole role chain; property analysis and caching can optimize it as described in Part II, Chapter 11.
A service signature lists participant types only, as in (Buyer, Goods, StockLine[]). Its body refers to each participant by a short name: the type name in lower camel case, so buyer, goods and, for an array, stockLines. A type can declare its own, for example Entity ExternalLoss short loss, losses; the second name is the array form. Writing an explicit parameter name is a compile error, as is a short name used twice in one signature. A type appears once per shape, so a selector and its result collection can share a type, but two scalar records of one entity need two roles. Omitted call arguments still require unique matching by complete type and collection dimension; ambiguity requires explicit selection.
When other participants supply the lookup values, the read lists them with by. The target's key fields are taken from the listed participants through their take mappings, or from a field set to a constant:
Role Book { String code; int edition; }
Role Selection { String requestedCode; }
take Selection as Book { String code = requestedCode; }
readonly Scenario serial readSelectedBook(Book, Selection) {
findBook by selection, book.edition = 3;
}
With APP declaring Book.code and Book.edition as the primary key, the code comes from selection.requestedCode and the edition from the constant. Each key field needs exactly one source, and the compiler checks the take relation and the field types.
Validation Checks Eligibility¶
check reads facts and uses require for requirements without changing participants. A failing check ends its enclosing bare block, at any depth of if/else nesting. A bare block is an explicit serial { } or parallel { }, a transaction { } or a failure handler; the bodies of if/else and of a guarded check are transparent. When that block is the transaction itself, the failure rolls the whole transaction back. To leave only part of the logic, wrap it in an extra serial { }: a failing check there exits only that block and the transaction continues. Outside a transaction a failing check only ends its block. checkXXX,breakTransaction rolls back the whole transaction from any depth.
Visible checks clarify admission. Actual quantum bounds must be enforced at settlement, not substituted by earlier balance reads.
Calculations Prepare Results¶
calculate changes candidate facts through formulas. It may call pure calculations, not query, check, update or scenarios to hide side effects.
atomic calculate priceLine(OrderLine) {
orderLine.amount = roundHalfUp(
orderLine.unitPrice * orderLine.quantity, 2);
}
This definition is from pricing source, with line wrapping for presentation.
Updates Apply Changes¶
Ordinary update is also built-in. After preparing complete facts, scenarios call standard insert, update or delete services suffixed by participant type. Current participants are passed; the framework retains technical baselines without a business before snapshot. Business calculations and checks stay outside the built-in update. Quantum updates describe special-property deltas and settlement requirements.
Preparation and checks may precede settlement where dependencies permit; earlier checks do not replace protected execution.
Chapter 16 — Calculation Rules and Collection Participants¶
Calculations derive candidate facts using formulas, conditions and loops. SPP expresses business arithmetic; PHY supplies physical representation.
Make Rounding a Business Rule¶
Line amount uses unit price times quantity, rounded to two decimals as agreed. roundHalfUp states the rule. Without a business rounding requirement, storage capacity or default precision must not silently change values.
BigDecimal is one physical option. Some operations still require explicit rounding or another representation; exact decimal does not finitely represent all mathematical results.
A result can also declare its precision, scale and rounding mode, such as BigDecimal(15,0,DOWN) qualifiedUnits;, and the calculation then uses ordinary division: the repeating quotient of 0.29 by 0.03 is computed at high precision and the assignment rounds it toward zero to 9. A calculation local can declare the mode the same way, for example BigDecimal(18,6,HALF_UP) rate. If a calculation may lose fractional digits at a target that has a scale but no rounding mode, the compiler warns and uses DOWN. Choosing the mode in SPP keeps the business rule the same across PHY representations.
Rules Execute in Defined Order¶
Petstore calculates lines and subtotal, then membership discount, shipping and total. These depend on facts at the current execution point.
if, switch, while and for provide deterministic flow, not a repeatedly firing rule agenda or arbitrary Java calls. Formulas remain within supported expressions and call contracts.
Collections and Internal Lines¶
Participants can be one-dimensional collections such as Goods[]. Queries complete them, calculations traverse goods and cart lines and form new internal order lines. Scalar input instances cannot be replaced; collection inputs retain their container while contents change.
Syntax accepts Goods[][], but current query, update and calculation implementations do not support multidimensional participant collections. Examples use one dimension; implementation will expand if practical demand emerges.
A schematic subtotal service, omitting domain and other definitions:
atomic calculate sumOrderLines(ShopOrder) {
shopOrder.subtotal = 0;
for (OrderLine line : ShopOrder.lines) {
shopOrder.subtotal += line.amount;
}
}
The loop is sequential. Parallel line processing requires explicit branch results, aggregation and execution support.
Candidate and Settled Facts¶
A calculation may mark an in-memory candidate paid, but only protected updates make it an actual result. Technical failure cannot publish a candidate as settled.
Separation allows independent formula verification and shorter transactions. Version or settlement guarantees must still prevent competition after preparation from causing stale overwrite.
Chapter 17 — Serial and Parallel Scenarios and Contract Formation¶
A Scenario expresses one defined business activity through explicit participants, qualifications, dependencies and commit boundaries.
Reading a Funding Scenario¶
From wallet funding source:
Scenario serial fundShopWallet(
Buyer, SettlementAccount, WalletFundingAgreement) {
checkBuyerCredential; checkFundingAmount; prepareWalletFunding;
parallel { findBuyer; findSettlementAccount; }
identify(buyer); identify(settlementAccount);
transaction {
transferWalletFunds bounds {
settlementAccount.balance: [null, null];
buyer.wallet: [0, null];
};
}
}
Inputs identify buyer, source account and agreement; the body names them buyer, settlementAccount and walletFundingAgreement. Credentials and amount are checked, relationships prepared, then both sides queried concurrently. After identity confirmation, the explicit transaction executes fund transfer with the bounds declared at the call: the wallet's lower bound, and an explicit [null, null] for the settlement account, because every position a call can debit needs a bound and an unlimited one says so. A scenario that only reads is declared readonly Scenario, and the compiler rejects any update in it.
Contracts in Scenarios¶
WalletFundingAgreement expresses parties and amount; ShopOrder ordering; ReturnRequestAgreement a return request. A contract corresponds to a defined activity, not an arbitrary wrapper for a list or return object.
Later activities reference existing contracts. Payment uses an order; returns use the original order and reason. This preserves relationships without invoking the original scenario again.
Explicit Orchestration and Automatic Binding¶
Argument-free calls reduce repeated names without removing participants. The compiler finds unique type bindings; multiple instances need explicit arguments. Readability cannot depend on guessing ambiguity.
Serial groups express order and parallel groups overlap execution. Inputs and effects must be established first; plans also check deployment support and recovery capabilities.
A Reviewable Business Entry¶
A scenario should correspond to a named activity. Packing many actions into a generic command string hides eligibility and participant scope inside branches. Separate payment, shipping and return entries state their facts more clearly.
Scenarios turn combinations into readable business narratives. The next part explains identity, storage, transactions and resources that honor them.
Part IV — Consistency and Execution Guarantees¶
Correct payment formulas are insufficient: participants must be located correctly, competing updates protected, and failures explained. Fact ownership, transactions, quantum settlement, recovery and generation show how those requirements receive real guarantees.
Chapter 18 — Business Facts, Participant Identity and Storage Ownership¶
Participant identity, fact ownership and storage location are distinct. A Buyer can contain facts maintained by several owners.
Borrowed and Owned Facts¶
Customer name is borrowed through role playing and maintained by the customer domain. Tier belongs to Buyer; wallet settlement belongs to quantum storage. Ordinary role insert, update and delete write only their own table, without cascading to players.
This prevents goods updates altering products and cart saves implicitly modifying buyers. Entity maintenance is explicit through the original domain's services.
Contracts Retain Settlement Facts¶
An order for “Kitten Food 1kg” must retain that name after the merchant renames it “Kitten Formula Food 1kg.” Current product pages show the new name; the old order describes what was purchased.
Current names and agreed contract names have different duties. Order queries must not overwrite historical names from today's products. APP storage and mapping configuration implements this requirement; ordinary role relationships alone do not imply it.
For example, a bank's failure-disposition record must preserve the deposit or reversal contract at the time of failure, including the system-provided cause, service, phase and recovery status. Saving only an association and later querying current facts can change the record's meaning as balances or contracts change.
APP snapshot now preserves explicitly declared associated participants and collections as historical snapshots. Queries do not continue filling those snapshot subtrees through role or association chains, and current quantum balances do not overwrite historical balances inside them. Ordinary live associations still follow their normal completion rules. APP configuration distinguishes these uses; see the bank snapshot verification.
Identity and Query Baselines¶
APP locates participants through keys, business credentials or combinations. The compiler supplies business-invisible entity keys; actual order and membership numbers remain business facts (Chapter 13).
Built-in queries retain internal baselines for subsequent saves. Version comparison uses the originally queried revision, not a fresh revision read just before writing. A missing baseline, changed identity or competing modification requires explicit conflict handling. Chapter 19 describes the execution policy.
Master-Detail¶
An order is Master; each line is Detail, recording quantity and agreed unit price. Cart and cart lines use the same structure.
The example preserves detail identities and completes members and related participants via query metadata. Saving Master does not replace explicit insertion, modification or deletion of Details.
Ordering explicitly deletes old cart lines, inserts agreed order lines and saves order and cart. Visible operations identify ownership rather than treating the whole aggregate snapshot as freely overwritable.
The Lifecycle of Zero Facts¶
Establishing zero quantum facts differs from crediting nonzero funds. Account opening prepares storage for future transfers; funding requires conserved quantum settlement.
With role and quantum facts in one database, a common local transaction establishes them. With split storage, the built-in runtime commits role records and a durable technical recovery task locally, then creates remote zero records after confirmation. Local rollback removes both. Remote unavailability or lost responses retain the task for retry. Retry creates only missing zero records, never overwrites settled values, and produces no quantum transaction journal entry.
Scenarios still call role insertion without manually splitting opening or writing business compensation. Opening is not fully successful before remote zero records exist. The current mechanism covers built-in JDBC ordinary and quantum repositories; see split zero-record recovery.
Every fact should have an owner, locator and maintenance entry. See the transaction and storage specification.
Chapter 19 — Transaction Boundaries, Execution Plans and Deployment Capabilities¶
“These changes must hold together” is a business requirement; resources and protocols are implementation. SPP expresses boundaries with transaction, APP selects strategy, PHY supplies real resources, and generated plans connect them.
Ordinary Updates Default to Optimistic Locking¶
The system retains query baselines. After scenario calculation and validation, built-in updates conditionally write against those baselines. If another request changed ordinary facts, the update reports conflict rather than overwriting them. APP defines retry or recovery.
Two requests read one profile. The first changes address; the second changes phone using stale facts. Its save must detect the changed baseline instead of restoring the old address with the whole old profile. Optimistic locking avoids holding a record lock throughout query and calculation while checking competition at write time.
Finds that load the participants of an updating service are plain snapshot reads, inside or outside a transaction. They take no row locks. Locking happens afterwards, once per transaction, so two scenarios that find the same positions in opposite order cannot deadlock in the database before they reach the quantum step.
| Queried Facts | What Protects Them |
|---|---|
| Ordinary participant | The write locks the row and compares the revision token read at the find. A fact changed by another transaction since then is rejected with PERSISTENCE_VERSION_CONFLICT; the caller re-reads and retries the scenario |
| Quantum facts | No ordinary read lock. The transaction locks every position it moves in one sorted order, by attribute and then position key, and checks bounds at settlement |
| Participant with ordinary and quantum facts | Ordinary facts are protected by the revision compare at the write; quantum facts by the sorted settlement lock |
Query the APP declares locked |
Keeps its row lock, because the application asked for it; declare it only on one scalar key |
SPP does not write select for update. The runtime locks at the write and at settlement, not at the find. Locking an ordinary record does not mean locking wallet quantum facts. The transaction reads reference describes the earlier read-locking design; this chapter reflects the current rule.
Local Joint Commit¶
Petstore develop uses LOCAL. Domains share a JVM and the required database, schema and connection resources, so quantum and ordinary changes enter one local transaction. Recovery applies within that resource scope. A LOCAL transaction whose calls make no quantum transfer commits as a plain JDBC transaction on its one shared resource; a quantum transfer in LOCAL still requires that shared resource.
The same database name does not prove a common transaction connection. Separate processes do not gain LOCAL merely by accessing one database. Compilation and startup validate actual identities.
Phased Execution¶
Outside LOCAL, a concentrated quantum group may settle first, followed by ordinary groups according to mode. Saga restores committed phases. A later ordinary rollback cannot undo an already committed quantum change.
Plans require explicit recovery capabilities. Unsupported combinations should be rejected rather than inventing compensation. Joint success across phases differs from single-resource atomic commit.
Nested Boundaries¶
REQUIRED joins the current boundary; ending it does not commit separately. Payment uses it for a logical scope, not independently committing payment before order.
REQUIRES_NEW is independent and does not automatically enter the outer recovery chain. Independent account opening may remain completed after outer failure and needs its own handling. Appendix E describes example-backend propagation support.
Automatic Quantum-First Planning¶
Ordinary updates are built-in and contain no business query, calculation or validation. Scenarios supply complete facts through preparation and quantum results.
Ordinary saves do not affect quantum inputs or outcomes; fixed quantum deltas can be aggregated or reordered only under the applicable command and settlement constraints. The compiler therefore schedules quantum transactions before ordinary updates within a boundary, allowing unordered or merged execution. Serial groups arrange post-settlement calculations and validations before ready saves run concurrently. Runtime supplies context, resources, joining and failure handling. “After quantum services” describes phases; LOCAL can still commit them together at the end.
Business Rejection and Technical Failure¶
SPP omits try/catch/throw: business conditions are explicit checks, while APP defines technical-failure policy and runtime/PHY execute it. A failing check exits its enclosing bare block; at transaction scope it rolls back the transaction. breakTransaction rolls back from any depth (Chapter 15).
A database failure is not evidence that an order is absent; a payment timeout is not evidence that settlement failed. APP must confirm uncertain outcomes before retry or business disposition. Generated Java and runtime may use exceptions internally. See participant execution.
Business Failure Compensation¶
SPP handles business failures: once conditions are known not to hold, what should happen to established results? Different businesses may choose different responses.
Insufficient inventory may lead to waiting for restocking or cancellation and refund. The framework confirms reservations and payment, but cannot choose for parties. transaction { ... } fail { ... } expresses post-failure business operations. Technical execution and recovery occur first; the adjacent fail receives failure facts. Its saves use a new explicit transaction.
| Failure | Decision Required from Business Developers |
|---|---|
| Admission rejects before changes | Reject with reason; do not refund a debit that never happened |
| Inventory held but later business validation rejects | Whether to cancel, releasing the actual reservation if canceled |
| Payment settled but fulfillment impossible | Keep payment for later handling, or cancel, refund and release holds |
| Application independently accepted but approval rejected | Keep for retry or mark rejected/canceled, and decide fee treatment |
| Goods delivered but later business cannot finish | Return, refund or another remedy; state changes do not return physical goods |
These are decisions, not a universal instruction to reverse all steps. Uncommitted changes can roll back; quantum services automatically reverse original transactions without a separately written business inverse. Business still decides cancellation, release or continued fulfillment. Later partial refunds or fees are new activities, not erasing original payment history.
Compensation respects layering. Refund eligibility is SPP; timeout executing the refund is APP. SPP defines qualifications, amounts and result; APP confirms, retries and recovers. Timeout is not business rejection.
Example: Retain an Accepted Reservation and Record Rejection¶
Petstore saves acceptance before reserving inventory. With ten available and eleven requested, acceptance exists but reservation cannot settle. The scenario retains the original number and records rejection for insufficient stock. From the actual scenario, omitting initial checks:
transaction { insertPetReservationAgreement; }
prepareReservationInventory; findStockLine; identify(stockLines);
transaction {
reserveRequestedInventory bounds {
stockLines.available: [0, null]; stockLines.reserved: [0, null]; };
confirmPetReservation; updatePetReservationAgreement;
} fail {
if (ResultInfo.failure.recoveryStatus == "ROLLED_BACK" || ResultInfo.failure.recoveryStatus == "REVERSED") {
findStockLine; identify(stockLines);
rejectPetReservation;
transaction { updatePetReservationAgreement; }
}
}
The first transaction independently saves acceptance; failure of the later one does not delete it. Success marks RESERVED. Failure first rolls back uncommitted effects or automatically reverses the settled quantum phase, then enters fail.
ResultInfo is a built-in scenario participant, not an input declaration. The example acts only for ROLLED_BACK or REVERSED: confirmed rollback or recovery of committed phases. It re-queries stock, calculates rejection and saves state in a fresh transaction, outside the failed boundary.
Rejection calculation marks REJECTED and distinguishes INSUFFICIENT_STOCK from RESERVATION_NOT_COMPLETED using recovered stock and requested quantity. Ten available against eleven yields the same reservation number, insufficient-stock reason and unchanged 10 available/0 reserved. A later ordinary-save fault despite sufficient stock instead records reservation not completed.
fail does not manually add inventory back. System rollback or automatic reversal handles that; fail expresses the business choice to preserve acceptance and record final rejection.
Unknown outcomes give RECOVERY_REQUIRED, so this example does not declare safe rejection. fail may record pending verification facts, but technical failure continues to APP and is not considered recovered merely because fail ran. After successful handling, status remains FAILED with handled true, rather than converting the original transaction to success. Current support is outer transaction fail in serial scenarios; multiple input contracts use fail(targetContract). See failure and system results.
Technical Recovery Policy¶
APP defines original-request confirmation, permitted retries, durable recovery tasks and escalation. A timeout alone does not trigger cancellation or refund. The same policy applies to compensation execution: confirm actual effects and prevent duplicates before reporting completion.
Report Actual Results¶
Request failure may mean no commit, partially committed phases or an unknown outcome. Settlement and recovery evidence determine actual state; an HTTP error alone does not prove rollback everywhere.
Explicit transaction semantics and deployment capabilities turn boundaries into reliable promises. Appendices D and F state detailed support.
Chapter 20 — Quantum Properties, Call Bounds and Conserved Settlement¶
Balances and inventory frequently face concurrent changes. “Enough when queried” is insufficient; actual settlement requires bounds and consistency. Quantum properties and services make that need explicit.
Properties and Deltas¶
Petstore declares wallet quantum and defines bilateral funding:
quantum update transferWalletFunds(
Buyer, SettlementAccount, WalletFundingAgreement) {
settlementAccount.balance -> buyer.wallet : walletFundingAgreement.amount;
}
The arrow moves one amount from the first position to the second. The amount is evaluated once, a negative or null amount is rejected, and zero has no effect. The compiler rejects a direct assignment or increment of a quantum field, so a transfer is the only way to change one. Two roles of one entity can move the same attribute between different keys, and writing the same endpoint on both sides is an error. Several transfers in one service are several movements, each with its own amount. The service states the relationship; bounds specify this call's range. Limits generally belong to wallet-role properties, so scenarios query them before passing them. One transfer service can serve wallets with different limits.
Transfers over a Collection¶
A slip with several lines moves each line's units between two holders. The quantum update loops over participant collections and each iteration is one conserved transfer; the whole slip is all or none:
quantum update moveSlip(Slip, Giving[], Receiving[]) {
for (SlipLine line : slip.lines) {
for (Giving source : givings) {
for (Receiving target : receivings) {
if (source.kind == line.kind && target.kind == line.kind) {
source.pieces -> target.pieces : line.units;
}
}
}
}
}
The two collections can be roles of one player, or one collection of the player. Each element is a distinct position of the player's conserved attribute. A transfer endpoint must be a participant parameter or an element of a loop over a participant collection parameter, otherwise compilation fails with SPP_QUANTUM_LOOP_ENDPOINT. A position is one object: key it once in its collection however many lines move it, because a key that occurs twice is rejected with QUANTUM_COLLECTION_IDENTITY_REQUIRED_OR_DUPLICATED.
Instead of the nested loops and if, the transfer can name its two positions with pick:
quantum update moveSlip(Slip, Giving[], Receiving[]) {
for (SlipLine line : slip.lines) {
Giving source = pick givings by owner = slip.giver and kind = line.kind;
Receiving target = pick receivings by owner = slip.taker and kind = line.kind;
source.pieces -> target.pieces : line.units;
}
}
Each pick yields exactly one element of the collection parameter, and the local is that element, usable as a transfer endpoint. A line with no matching position is QUANTUM_MATCH_MISSING, and one matching two is QUANTUM_MATCH_AMBIGUOUS; either rolls back the whole slip, where the nested loops would silently do nothing or transfer twice. The key must cover the whole position identity, otherwise the compiler reports PICK_KEY_INCOMPLETE; fields that the find hydrating the collection already fixes may be left out. pick first and pick last state which of several matches to take. The same expression reads one element in a calculate or check.
The transaction locks positions in a consistent order, by attribute and then position key, to avoid cyclic lock acquisition. Bounds are checked once per command for each constrained position, against its authoritative starting value plus the net delta of all legs in that command. Intermediate leg balances are not separate admission conditions. If any bound fails, the entire command is rejected without applying any leg. Every position a call can debit, including the elements of a loop, needs an explicit entry in the call's bounds block, named by the scenario argument; an unlimited debit is written [null, null], and a missing entry is the compile error SPP_QUANTUM_BOUND_REQUIRED. The limit is a fact of the business transaction, usually read from the contract, so it is not declared on the account. Credit-only positions need no entry. An empty slip applies no transfer and is rejected. A boolean fact that nothing set is false in generated models.
Several domains can be composed in one application on one QService: the application binds every domain's quantum store to the same endpoint and namespace, and a consumer domain whose quantum roles are all played by other domains declares no store of its own. One transaction then reaches the service as one command covering every store it touches; stores bound to a different service are still reported as a distributed transfer that is not yet supported. Each domain contributes its own quantum definitions to the shared store; an attribute declared by several domains must be declared identically, or deployment fails with QUANTUM_DEFINITION_CONFLICT naming both domains. A play that moves no quantum needs no coordinator in any transaction mode, because the consumer only reads the provider's record. The service also enforces call bounds itself, inside the command, so no leg is applied when a bound is violated; the committed value of one quantum can also be read from the service without taking part in a transaction. The client reads the quantum facts of repository objects through that committed read, so a scenario sees its own settled commands, and a position is opened, idempotently, once the owner object has committed.
Query Wallet Limits First¶
A normal wallet may range from zero to 10,000 US dollars, while overdraft permits −500. Such facts belong to particular wallets rather than a hard-coded universal nonnegative transfer rule.
Payment queries the source lower bound; funding queries the destination upper bound; transfers obtain both sides' relevant limits. Adding 300 to 9,800 with a 10,000 maximum violates the range.
Limit queries retrieve settlement rules; balance queries support display or preliminary judgment. The scenario passes the limits, and execution checks them against actual settlement values. An earlier balance cannot guarantee success.
Bounds Apply at Settlement¶
Two requests see 100 and each pays 80. Both preliminary checks can pass, but at most one settles without overdraft. The quantum implementation processes current values and checks constraints before commit.
Limits are evaluated before the call; null disables that direction's check. It does not mean unknown amount or replace a legitimate funding source. Eligibility remains explicit validation.
For each constrained position q, let x(q) be its authoritative value and Δ(q) the sum of incoming amounts minus outgoing amounts in the command. Admission requires L(q) ≤ x(q) + Δ(q) ≤ U(q), omitting an unbounded side. For example, a position at 100 with lower bound 0 can send 150 and receive 80 within one command: its net delta is −70 and its final value is 30. The intermediate −50 is not a rejection condition. Separate commands do not share this netting permission; concurrent commands still require correct admission and atomic settlement. Conservation and all other constraints remain mandatory.
Conserve Actual Relationships¶
Payment source decrease and destination increase match. Reservation moves available to reserved; shipping reserved to sold. Each goods identity conserves separately; another product's increase cannot hide this one's loss.
Money and inventory use different dimensions, not one numerical conservation equation. They can cooperate under a scenario with separate conservation groups and an overall transaction or recovery plan.
Settlement Results and Participant Completion¶
The framework fills participants with settlement results. These describe the transaction's facts, not a global simultaneous snapshot across sources. Later transactions can continue changing values.
Ordinary prepared inputs remain stable as agreed; dynamic quantum facts belong to quantum execution. Business must not bypass it to save nonzero balance changes.
Automatic Inverse Transactions¶
Recovery applies opposite deltas to the original settlement participants, preserving later changes rather than restoring old balances. The system owns identity, deduplication and technical recovery. Chapter 21 distinguishes this automatic inverse from business reversal and compensation.
Chapter 21 — Rollback, Inverse Transactions, Reversals and Compensation¶
“Undo” hides distinct duties: uncommitted rollback, settled-fund reversal, new business reversal and external compensation. Distinguishing them explains failure outcomes and recovery scope.
Rollback Undoes an Unfinished Transaction¶
Technical rollback removes the current transaction's effects, retaining evidence and other independent committed results. Resources and protocols determine scope.
Committed Saga nodes are outside their original local transactions. The failed node can roll back its uncommitted effects; prior successful nodes need separate recovery.
Ordinary Updates Can Also Be Automatically Reversed¶
Built-in ordinary updates contain no calculation or query for completion. They save already prepared facts. Systems can retain before facts and resulting versions to undo writes without a reverse service recalculating old values.
An address changes from A at v8 to B at v9. Recovery can restore A only if current version still equals this write's v9, and must produce a new version. Reverting the marker to v8 could wrongly accept formerly stale requests.
If another request produced C at v10, recovery cannot overwrite it. Even if values happen to return to B, the new version still matters. Version check and restore must be one atomic conditional operation, not a check followed by unconditional write.
Quantum reversal negates a delta while retaining later deltas; ordinary recovery restores facts only while the version qualifies, without later writes. Conflict requires APP confirmation and handling, not overwriting subsequent results.
Recovering Mixed Cross-Domain Transactions¶
One SPP boundary may update different domains, processes and databases. It expresses joint business requirements, not a shared local database transaction. APP plans and PHY capabilities determine restoration.
Consider four updates:
| Update | Effect | Domain |
|---|---|---|
| Q1 | Buyer wallet −100, merchant funds +100 | Payment roles' domains |
| Q2 | Available stock −1, order hold +1 | Inventory |
| U1 | Save order and agreed lines | Order |
| U2 | Save processing receipt | Receipt owner |
Q1 and Q2 conserve different dimensions. Roles can belong to separate domains while configured unified quantum execution handles deltas. Ordinary repositories may be called remotely. Current non-LOCAL plans complete the quantum group, execute ordinary phases and retain commit records. Multiple quantum requests can settle together; ordinary updates follow configured coordination.
If the quantum group does not settle, ordinary execution stops. A balance or stock bound can reject the whole group. Its resource removes uncommitted effects and U1/U2 do not proceed. A purchase cannot debit without stock or save a success receipt for no settlement. Unknown quantum commit requires confirmation, not definite rejection.
If quantum settlement succeeds but ordinary commit fails, restore both appropriately. Suppose Q1/Q2 settle, U1 executes and U2 reports a definite conflict. If U1/U2 belong to a supported XA or Seata AT ordinary scope, that coordinator first restores its writes, then the mixed plan automatically reverses the quantum group. Executing U1 is not proof it committed independently; status follows its phase.
Q1 + Q2 settled
→ Execute U1 and U2
→ U2 definitely fails
→ Undo unfinished ordinary transaction
→ Automatically reverse settled quantum group
→ Confirm every recovery result
Independently committed ordinary phases need their own recovery. Under Saga, U1 may commit before U2 fails. Roll back U2's unfinished transaction, restore U1 in reverse committed-phase order, then reverse quantum changes. U2's rollback cannot remove U1. Version-protected restoration uses U1 before facts and written version; if no later version exists it can restore without business recalculation. Otherwise retain a recovery conflict under APP policy.
Unknown phase outcomes require confirmation first. A remote U2 timeout may mean the receipt committed or never ran. Current mixed plans retain pending recovery instead of immediately reversing earlier commits. APP queries the original request, then completes or restores according to actual records. Otherwise funds and stock could be undone despite successfully saved order and receipt.
Recovery failure means recovery remains incomplete. Failed U1 restoration or lost quantum-reversal response retains original and recovery evidence. Current implementation records a failed recovery phase and still attempts others, potentially producing partial recovery. Every result must be checked; “recovery started” is not “fully undone.” APP defines later confirmation, retry and handling. Quantum inverse deduplication prevents duplicate refunds, and permitted business during recovery follows explicit policy.
Rollback concerns the uncommitted phase; quantum inverse restores committed deltas; ordinary reversal restores qualifying versions. A later bank reversal is new business, not this automatic failure recovery.
These capabilities need before facts, versions, records and backend protocols. Shared databases do not imply shared connections, and naming XA, Seata AT or Saga does not prove deployment guarantees. See environments and storage contracts.
Local Rollback and Split-Storage Recovery in the Bank Case¶
The bank case in Part VII, Chapter 33 provides a concrete comparison: cash reversal has already applied reverse fund movements when saving reversal postings fails.
| Deployment and Failure Point | Actual Funds and Ordinary Facts | System Outcome |
|---|---|---|
| Shared local transaction resource; reversal postings fail to save | Funds, the original-transaction flag and reversal contract roll back together; the original remains unreversed | ROLLED_BACK |
| Separate quantum and ordinary storage; posting save fails after some ordinary stages commit | Quantum inverse transactions restore funds; ordinary flags or reversal contracts may remain | RECOVERY_REQUIRED, handled=false |
| Saving the failure-disposition record also fails | Preserve the original failure, actual recovery state and secondary disposition failure | Entering fail does not establish successful disposition |
The case's split-storage repository has not yet implemented automatic recovery for committed ordinary stages. This does not change the principle of version-guarded automatic reversal, but shows that the backend protocol must actually be implemented and verified. Recording reconciliation facts is failure disposition; restoring funds and ordinary records is transaction recovery.
Tests also change an original contract's version after it has been queried, verifying that reversal cannot overwrite a later change. Even when split-storage funds have been restored, earlier ordinary stages may remain. The system preserves the pending-recovery result rather than allowing a direct retry to hide it. The case verification record documents the persisted outcomes.
Automatic Inverse Transactions Retain Later Results¶
Starting at 100, +50 then +20 gives 170. Reversing the first subtracts 50, leaving 120. Restoring a snapshot of 100 would erase the second activity.
The system inverses original settlement components and maintains participant identity, duplicate protection and confirmation. APP handles technical confirmation and recovery. Failure of the inverse request does not prove the inverse did not settle.
Business Reversal Is a New Activity¶
A bank reverses a completed transaction for business reasons by querying the original, checking eligibility and forming a new result. Original principal and interest components must be restored, not recalculated under today's policy.
It has its own transaction and failure handling. Cross-day rules, later dependencies, disbursed funds and external effects may constrain eligibility. This differs from technical rollback before original commit.
Compensation Requires Business Decisions¶
Consumed goods or irreversible external effects may require another remedy. Content, triggers and completion criteria must be agreed; systems execute, record and retry the defined rules.
Automatic quantum inverses and version-qualified ordinary restoration do not decide physical returns or substitute fulfillment. Database restoration cannot erase external effects, and later ordinary versions prohibit forced old-value restoration.
APP Converts Definite Technical Failures into Business Failures¶
Conversion requires a known outcome and agreed business meaning. A definitely rejected unique-key write may become “number already taken”; optimistic conflict may become “information changed; reconfirm.” SPP handles the result without database error types. APP defines these mappings explicitly, rather than classifying every error as one rejection.
Timeout, disconnection or lost commit confirmation can occur after commit. They indicate absence of a definite response, not business failure. APP confirms before returning success or rejection; until then, retain uncertainty and technical recovery, without triggering business compensation.
Separation therefore permits cross-layer failure information: definite, meaningful failures become business failures; uncertain ones require confirmation first.
Evidence and Coverage¶
Stable request identity and result lookup are essential when confirmation is lost. Appendix F distinguishes implemented recovery paths from unresolved coordination and compensation coverage.
Chapter 22 — Generation, Physical Resources and Runtime Configuration¶
Declarative models must become executable code, interfaces, repositories and resource access. Generation performs this conversion and checks model-implementation contracts. Reading output reveals declarations' effects.
From Models to Runtime Artifacts¶
The compiler combines models, calls, role relationships and transaction boundaries with APP/PHY to generate Java models, services, mappings, OpenAPI, DDL and runtime catalogs. Chapter 12 explains the review benefits of deterministic generation.
Maintain rules in source directories and configuration, not generated Java in target: direct edits may be overwritten by the next build.
Generation and Startup Checks¶
Generation detects undefined facts, ambiguous binding, illegal calls, unsupported propagation and contradictory resources. Startup checks actual override parameters, environments, identities, provider contracts and readiness.
Resolution does not depend on file names. All domains are validated before any is generated, and APP files are compiled in two passes (tables first), so a provider may sort before or after its consumers, two domains may play each other's roles, and one domain's tables and scope may be split over several APP files. A table or service declared twice is reported with both declaring files.
Static checks do not prove current remote settlement capability, and startup does not replace concurrency or fault tests. Each supplies different evidence.
Build and Local Demonstration¶
Run at repository root with the documented JDK 25, Maven and dependencies:
mvn -pl :petstore-demo -am package -DskipTests -Dspp.environment=develop
SPP_PETSTORE_JDBC_URL='jdbc:h2:file:/tmp/spp-book-petstore' \
./demos/petstore/run-demo.sh web
The web demo defaults to 8086. This uses an independent experimental database; reusing the path retains old data. Appendix E provides variables and multiprocess commands.
Interface Declarations in APP and PHY¶
Interface technology never appears in SPP. A scenario is business behavior; its HTTP method, path, query parameters, wire names and the HTTP status of a business rejection are deployment choices declared in APP:
@parameter(path="{id}/Deposit/Initiate", method="POST")
@payload(request = "order.facilityId=path.id, order.amount=body.Deposit.Amount",
response = "Reference=deposit.depositId, Deposit.Amount=deposit.amount")
{ initiateDeposit; }
@rejectionStatus(FACILITY_NOT_FOUND="404", FACILITY_NOT_ACTIVE="409", fallback="400") { }
@parameter selects the method (GET, POST, PUT, PATCH or DELETE; PUT without it), @payload maps path, query and body names to participant fields and back, and @rejectionStatus maps the rejection codes of a domain to statuses, with technical failures always 500. Names are checked at compile time. The generated OpenAPI carries the declared methods, query parameters and statuses, and a runtime dispatcher serves them. For the other direction, a PHY remote declaration with adapter openApiClient calls another REST service while the remote atomic stays unchanged in SPP and APP; business outcomes such as an absent party are mapped from status codes. Money travels as a plain decimal with its scale preserved (120.00 stays 120.00) in requests, responses and path or query values.
Numbers and Resources¶
PHY selects representation and capacity; APP organizes technical mappings. SPP specifies rounding; inexact unsupported conversion must fail rather than silently alter meaning.
develop and testing can use different deployments and plans for one scenario. Compare selected environment, generated catalog and startup arguments rather than using artifacts from one to prove another.
Verify That Declarations Are Honored¶
A successful build establishes source-generation checks, not actual business completion. Execute scenarios and verify results. The later Petstore practice follows requirements through fund and stock movement to show the architecture as a complete system.
Part V — Separating Business and Technology¶
Business scenarios describe participants, calculations, settlement and failure handling. We now examine the technical capabilities surrounding them: performance, security, reliability, observability, governance and evolution.
Using different needs of one order, this part introduces caches, on-demand data, protection, idempotency, duplicate guards and governance. APP selects strategies and interception scope; PHY binds Java technical services, resources and protocols. New technical implementations can extend capabilities without technical calls in SPP. Chapter 23 introduces binding and Chapter 27 a custom implementation; each capability must fit its actual interface.
Chapter 23 — Benefits of Separating Business and Technology¶
Payment requires eligible parties to transfer an agreed amount and form a verifiable result. Encryption, caches, duplicate detection and database access support execution. S++ puts business in SPP, technical strategies in APP and resources and protocols in PHY, giving each a clear maintenance location.
Let Business Specialists Review Business Directly¶
Changing a member discount from ten to fifteen percent requires checking eligibility, percentage and quotation. Mixed database, conversion and retry code makes specialists understand technology before assessing completeness.
SPP expresses discounts as calculations, conditions as validations and invocation as scenarios. Requirements specialists can review and model with AI. Tools supply queries, saves and integration, so review concerns business facts and rules. Part III, Chapter 12, explains how this reduces freely generated AI code.
Technical work also concentrates. Poor cache hit rates concern access policies; duplicates concern request identification and execution, not payment formulas.
Adapt One Business to Different Environments¶
Customer facts can come from local storage or a remote domain. Protocols and protection can change while scenarios still use Buyer with the same meaning.
Moving the customer domain to a separate application changes APP bindings and PHY endpoints and resources, requiring transaction and recovery checks. If providers honor the same contract, payment gains no HTTP conversion or connection-management code.
Replacement must preserve meaning, effects and failures, not just types. A new interface cannot treat timeout as the old “not found.” Separation makes adaptation and verification explicit.
Reuse Technical Capabilities Centrally¶
Orders, reservations and funding all need request identification. Separate lock, registration, result and recovery implementations can drift. A shared technical protocol with scenario-specific configuration reduces duplication and centralizes improvements.
Encryption, compression, tracing and throttling have similar value. Technical developers maintain facilities while business describes facts and results. Updated capability can serve many scenarios through configuration.
Bind Java Technical Services Through APP Interception¶
Capabilities need not all be built into the compiler. Technical developers can implement Java services and bind them around scenario or atomic calls. SPP remains business; APP chooses targets and stages; PHY chooses classes and parameters.
To record all shop-service durations without modifying each payment, order or query, Petstore's technical APP declares:
technical services { invocationTrace; }
intercept services {
before: invocationTrace;
after: invocationTrace;
failure: invocationTrace;
}
invocationTrace names a capability. intercept services matches all generated services in this domain, including scenarios, ordinary CRUD and quantum services. intercept scenarios limits it to scenarios; intercept findBuyer, reserveShopPet selects named services. This is a technical binding, not a business call to a logging atomic service.
Its PHY specifies:
phy {
technical service invocationTrace {
implementation: "com.servpp.service.technical.InvocationTraceService";
config logger = "spp.petstore.invocations";
}
}
New implementations implement TechnicalService and enter the runtime classpath. APP declares name and scope; PHY binds class and configuration. Chapter 27 builds a slow-call observer.
| Stage | When | Typical Use |
|---|---|---|
| before | Before business invocation | Technical access control and start recording |
| after | After normal return | Duration, validation result and completion recording |
| failure | When technical error propagates | Diagnostics and alerts |
after means normal method return, not validation acceptance or outer transaction commit. A reservation rejected and handled by fail can return normally and trigger after. Recording after alone cannot certify successful payment.
The interface exposes read-only service identity, kind, trusted headers, duration, validation result and technical error, not mutable participants. It directly supports observation and identity-based control. Data rewriting, query replacement or response changes need suitable adapters. Java capability can evolve while business ownership stays explicit. See the interception protocol.
Optimization Must Honor Business Agreements¶
Display names may tolerate caching; payment cannot overwrite balances based on caches. Lists may return summaries, while returns need eligibility facts.
Business defines fact purposes and results; technology chooses strategies. It cannot omit checks or relax quantum bounds for speed or success rate. Freshness, recovery and outputs must honor agreements.
The next chapters discuss performance, security, reliable execution and governance. Facilities may reside in runtime, integration or adapters, without each becoming a remote microservice.
Chapter 24 — Performance Through Caching and On-Demand Data¶
Performance means reducing repeated access and unnecessary data as well as concurrency. SPP retains role organization; APP selects query, transfer and output strategies; PHY supplies resources.
Observe Performance Before Choosing an Optimization¶
APP after/failure can collect query and scenario names, durations and faults, identifying whether product access or saving dominates. No timing code enters SPP. A Java collector can integrate metrics through PHY.
Current interceptors only expose invocation metadata. They cannot modify participants or return a cached answer while skipping a query. Observation fits directly; caches, field selection and response projection belong in query, repository or output adapters.
Caches Reduce Repeated Access¶
Ten cart lines may reuse product information. Request caches reuse facts within a call; process caches share across requests; shared caches reduce source-domain reads across application instances.
Remote product names and categories can be cached locally. Business still calls role queries; technical cache hits complete facts without explicit “cache first, database next” in scenarios.
Keys must distinguish participant identity, loaded fields and version. Having a name does not imply having price and status. Freshness follows purpose: name display may tolerate age, while settlement needs authoritative mechanisms. Cached balances can support display or preparation, not settlement.
On-Demand Queries Reduce Read Sets¶
A role chain may expose many properties while quotation needs only tier, price and quantity. Compile-time use analysis can form a required set, with queries retrieving its sources.
Buyer may include name, avatar, address and tier. Discount only needs tier; ordering adds address. Role granularity remains Buyer while loaded volume decreases.
Retain identity, internal baselines and loaded-property markers. An unloaded address must not become an empty saved address. Partial loading and saving need a protocol, not merely shorter SQL.
On-Demand Responses Reduce Output Sets¶
Calculation input and display needs differ. Quotation may use addresses and complete pricing facts while showing only names, quantity, unit price and total.
APP can define output sets per entry: order summaries, detailed lines, or payment receipt and system result. Roles and contracts retain meaning; output adapters select allowed needed fields.
Queries determine retrieval; response selection determines disclosure. Internal sensitive facts need not reach the page. Selection must cooperate with permissions, masking and replay.
Current generated web interfaces mainly return completed input objects and result information. General projection, role-use query pruning and multilevel caches need further implementation and scope verification. These are optimization methods, not universally completed capabilities. Appendix C13 specifies conditions.
Batching and Execution Paths¶
Independent goods can use batch or parallel queries. Quantum services can merge requests. Ready ordinary updates can save concurrently.
Calculations and validations normally run in the scenario process, avoiding network calls for small work. Compressing large payloads saves bandwidth but adds encoding cost and should follow measurement.
Measure full latency, read/output volume, cache hits and source calls. Faster lists that cause many later detail reads may need adjusted data sets. Appendix C gives experiments.
Chapter 25 — Encryption, Fingerprints and Security Services¶
Correct rules also require trusted requests, protected data and traceable operations. APP organizes authentication, encryption, integrity and output control; PHY supplies protocols, keys and resources. Scenarios operate on trusted business facts.
Protect Transfer and Storage¶
Customer addresses may travel across domains and be stored. Integration can protect transport and select field encryption without business handling ciphertext, key choice or decryption calls.
Transport and at-rest encryption have distinct scopes and do not replace each other. Specialized facilities manage keys; PHY supplies endpoints and configuration. Rotation and upgrades affect adaptation while meaning stays stable.
Authentication and decryption may precede business; output encryption follows. Technical ordering has its own dependencies and is not arbitrarily exchangeable because business atomics can be concurrent.
Fingerprints Identify Content; Integrity Protection Verifies It¶
A content fingerprint is a normalized digest for detecting change. A request number first transferring 100 and later 200 is not a retry; comparing facts or fingerprints detects the conflict.
Cover relevant content, including parties, not just amount. Consistent normalization avoids treating reordered fields as changed business. Identity identifies the call; fingerprint checks its content against the original.
A plain digest does not authenticate a sender or stop an attacker replacing both content and digest. Use authenticated message checks or signatures when protection requires origin and integrity. SPP receives verified facts; integration establishes trust.
Biometric fingerprints also belong to authentication. If business explicitly requires verified identity, that qualification and result enter business rules. Means and eligibility have separate places.
Authentication, Permissions and Business Eligibility¶
Authentication establishes who calls, access control what entries and data they may access, and business validation whether this activity is eligible.
A logged-in buyer may query only authorized orders. Refunds additionally check ownership, delivery and deadlines. APP supplies trusted identity and protection; SPP expresses relationships and qualifications.
A submitted Buyer object is not proof of its identity, and a browser duplicate marker is not authentication. Integration verifies origin and binds trusted identity to participants before business processing.
Technical Access Control with before¶
An internal entry may accept only specified verified callers. A Java technical service reads trusted headers in before and rejects unauthorized calls before business starts. APP selects entries, PHY selects implementation, and SPP needs no technical identity code.
before failure prevents invocation and enters failure with the original technical error. Trusted headers must already be established by authentication; arbitrary user values cannot become credentials. Ownership and payment eligibility remain SPP checks.
Current metadata excludes addresses, amounts and message contents. Field encryption, content fingerprinting and masking need data or communication adapters. Interception can audit calls, but committed-transaction evidence must also use transaction/storage records.
Output Control and Audit¶
Order details may show a telephone number while lists show a masked one. APP can combine permissions, selected fields and masking, including logs and replay rather than only normal responses.
Technical audit records callers, entries, verification and traces. Business contracts record parties, amounts and processing results. Correlated identities support distinct safety and business inquiries without exposing keys or unnecessary sensitive facts.
Facilities can serve many scenarios, but algorithms, key management, authentication and permissions require implementations and scope verification. This chapter does not assume all security infrastructure is built in.
Chapter 26 — Idempotency, Duplicate Guards and Reliable Execution¶
Repeated clicks, communication retries and lost confirmation can deliver payment requests more than once. Reliability identifies their relationship to original business so duplicate transport does not duplicate debit. APP defines strategy; SPP retains qualifications, amount and outcome.
Idempotency Identifies the Same Request¶
A 100-dollar payment may settle without its response reaching the page. Retrying the same identity and content should restore the result, not debit again.
Current remote-update protocols identify caller, caller serial and target service. Identical content replays original participant facts and result; changed amount or payee under the same serial conflicts. Registration tracks running, completed and recovery-needed requests, not just a seen flag.
An order number and technical request serial differ. One order has many processing activities; a retry must retain the original call identity. New serials on every retry prevent recognizing the same payment.
Duplicate Guards Identify Repeated Operations¶
Transport idempotency concerns one request; UI guards also catch similar clicks with different serials. Repeated “add to cart” may be one accidental action.
APP declares identity keys, facts and a window, such as buyer, goods and quantity. After expiration, another addition can be legitimate; rejection must not be permanent.
Whether an order can be paid again is SPP business eligibility. Expired technical windows do not make it payable or imply no previous settlement. Both protections cooperate.
Current remote idempotency and UI guards are separate. Local calls do not repeat transport registration; quantum deduplication belongs to its backend. Queries do not replay through the update protocol; query caches are distinct. See call idempotency.
Optimistic Locking Protects Competition Between Different Requests¶
Two legitimate profile edits may share stale facts without being duplicates. Conditional updates compare query baselines and reject overwrites after new versions. Quantum services apply deltas and actual bounds.
Deduplication, versions and quantum settlement protect repeated calls, competing replacement and quantitative change respectively. One duplicate key cannot replace all three.
Confirm Outcomes Before Retrying¶
Timeout may mean uncommitted work or lost confirmation of committed work. APP queries original execution or retains recovery status. Repeating an entire uncertain scenario can duplicate debit or acceptance.
Confirmed full restoration with no independent stage committed may permit retry. Partial or unknown completion needs continued original recovery. Quantum inverses are automatic; ordinary restoration follows version contracts; business handling follows rules. Part IV, Chapter 21, distinguishes them.
Retries need deadlines, limits and backoff. Exhaustion does not create a compensation policy; preserve evidence and enter defined technical handling.
Interceptors Observe; Execution Protocols Confirm¶
Java services can correlate request identity, target and failures. Scenario entry events may include idempotent replay; if replay does not execute atomics, it produces no repeated atomic execution events.
Two entry events do not prove two debits; atomic after does not prove outer commit. Registration, journals and receipts establish actual duplication.
Current after/failure are observation stages, and failures do not replace original results/errors. There is no arbitrary retry, result mutation or independent commit callback. failure must not simply rerun payment. Execution protocols retain confirmation and reversal responsibility; interception supplies diagnostics.
Durable Records Survive Restart¶
Memory-only registration can forget requests after restart. Required update recovery uses durable identities and results coordinated with actual settlement.
The framework supports memory and JDBC stores with different capabilities. Unknown or partially committed records cannot expire into brand-new requests. Split zero creation also uses durable technical tasks rather than new business compensation. Central strategies keep scenarios focused on results rather than rewritten retry protocols.
Chapter 27 — Runtime Governance and Technical Evolution¶
Correct models still need capability under variable load, dependency failure and migration. APP organizes tracing, throttling, isolation and recovery; PHY supplies deployment and monitoring. These facilities help detect, locate and handle problems.
Traces and Metrics Locate Problems¶
Slow ordering may reflect product queries, stock settlement waiting or ordinary-save conflicts. “Order failed” alone identifies none.
Trace scenarios, domain calls, phases and recovery. Measure duration, errors, cache hits, version conflicts and pending requests. Distinguish settled quantum work, failed ordinary work and unconfirmed inverses.
Contracts answer what was bought, paid and processed; traces answer paths, failures and recovery progress. Correlation avoids exposing connections or threads as page business state.
Add a Slow-Call Observer in Java¶
Suppose calls over 200 ms need a separate record. Add a technical service without changing scenarios. This example uses current TechnicalService (maintainer reference: ../../appframe/src/main/java/com/servpp/service/technical/TechnicalService.java) and TechnicalInvocation (maintainer reference: ../../appframe/src/main/java/com/servpp/service/technical/TechnicalInvocation.java):
package example.technical;
import java.util.Map;
import java.util.logging.Logger;
import com.servpp.service.technical.TechnicalInvocation;
import com.servpp.service.technical.TechnicalService;
public final class SlowCallObserver implements TechnicalService {
private long thresholdNanos;
private Logger logger;
public SlowCallObserver() {}
@Override
public void configure(Map<String, String> config) {
long millis = Long.parseLong(config.getOrDefault("thresholdMillis", "200"));
if (millis < 0) throw new IllegalArgumentException("Negative threshold");
thresholdNanos = Math.multiplyExact(millis, 1_000_000L);
logger = Logger.getLogger(config.getOrDefault("logger", "spp.slow"));
}
@Override
public void handle(TechnicalInvocation event) {
if (event.elapsedNanos() > thresholdNanos) {
logger.warning("service=" + event.serviceName()
+ " phase=" + event.phase()
+ " elapsedMicros=" + event.elapsedNanos() / 1_000);
}
}
}
A public no-argument constructor is required. Registration calls configure; execution calls handle. Instances can receive concurrent calls, so do not store a request's start time or identity in shared fields. This example initializes threshold and logger once, and uses each event's data.
Put the class on the runtime classpath, then observe scenarios in APP:
technical services { slowCall; }
intercept scenarios {
after: slowCall;
failure: slowCall;
}
Bind implementation and parameters in PHY:
phy {
technical service slowCall {
implementation: "example.technical.SlowCallObserver";
config thresholdMillis = "200";
config logger = "spp.slow";
}
}
The same structure integrates metrics, traces and alerts; identity-based controls or throttling can choose before. Thread-pool isolation, cancellation and message transformation still need runtime or communication adapters, not observation alone.
Interception Scope and Failure Meaning¶
All-service matching applies only to its declaring domain. A shop proxy and product provider are separate calls; observing provider internals requires product configuration. Declaration and phase-list order determines execution. Duplicate service-stage-technical-service matches fail compilation.
before may block invocation. after faults become diagnostics while later observers continue. failure faults attach to the original error while others continue, without replacing it. Logging failure cannot rewrite an already normally returned business result.
Method return also differs from commit. Quantum return may precede outer settlement; one scenario after cannot represent several sequential commits. Current interfaces have no independent commit callback. Execution records determine settlement and recovery.
Technical services are not registered as SPP atomics, avoiding recursion under all-service matching. Business completes activities; technical services surround calls with facilities.
Throttling and Isolation Protect Resources¶
A slow external catalog can occupy connections and threads until other business suffers. Limits, deadlines and isolated pools reduce propagation.
Throttling limits admission rate, isolation separates resources, and circuit breaking pauses access to persistently failing dependencies. These improve handling but cannot interpret unavailable dependencies as missing goods or guarantee whole-business success.
Timeout ending page waiting does not stop background updates. Confirmation and execution status must cooperate with response-time policy.
Degradation Must Preserve Meaning¶
Unavailable recommendations can be omitted and failed images replaced. Display adaptation can handle these.
Unavailable price sources cannot silently cause old-price settlement, nor payment faults mark orders paid. Agreements define optional output, acceptable cached facts and mandatory suspension. Technical methods honor business-approved outcomes.
Async notification is similar. Queues may carry notices, but an order-success promise cannot silently precede confirmed stock and funds. If business accepts now and processes later, SPP explicitly defines phases and contract states.
Conversion and Environment Adaptation¶
Adapters normalize external field names, formats and number representations into agreed facts. Dates, serialization and compression can be shared.
A protocol change still supplies goods-role facts. Localization can use constants and resources. Currency conversion and rounding alter business amounts and are not mere formatting.
PHY supplies environment endpoints, storage, caches and keys. Operators configure existing capabilities; naming an unimplemented option does not make it work.
Verify Evolution¶
Each change needs objectives and coverage. Caches require freshness/invalidation; durable guards concurrency/restart; transaction deployments commits/inverses/unknown results; security trusted identity and output protection.
Technical tests honor capability contracts while business tests retain calculations, qualifications and agreements. Separate reviews meet at shared requirements. Petstore next connects roles, services, scenarios and integration into complete practice.
Part VI — Complete Petstore Practice¶
The first five parts established models, cooperation, language, consistency and technical separation. We now apply them to one buyer's complete journey through Petstore models, scenarios, APP and PHY: zero facts, funding, inventory receipt, quotation, ordering, payment, shipping and subsequent handling or failure.
Illustrative amounts and quantities can be checked step by step; snippets link to real files. Existing implementations and evidence are distinguished from proposed caching, on-demand data and full security/governance extensions. Experiments and detailed arguments remain in the appendices.
A Code-Size Comparison with Java¶
The comparison below uses the recorded source baseline described in Appendix F7. Later expanded formatting and English/USD presentation change physical line counts; these historical figures are not counts of the current downloadable files.
The four-domain, 34-scenario example covers membership, goods, cart, orders, payment, fulfillment, returns and reservations. Its source generated the following Java:
| Content | Files | Code Lines |
|---|---|---|
| SPP business models, services and scenarios | 63 | 999 |
| Business enums | 2 | 18 |
| APP and PHY configuration | 8 | 331 |
| Maintained S++ source total | 73 | 1,348 |
| Tool-generated Java | 962 | 100,151 |
Counts exclude blank lines and comments but include brace-only lines. About one thousand business lines plus three hundred configuration lines expand into about one hundred thousand Java lines, including models, request/response types, interfaces, implementations and integration. Business specialists mainly maintain SPP; tools deterministically produce expanded models, calls and persistence.
A rough Spring Boot + MyBatis + Lombok estimate is:
| Java Scope | Maintained Code and Configuration |
|---|---|
| Conventional monolith for 34 scenarios using local transactions | About 6,000–10,000 lines |
| Including this example's domain calls, conserved transactions, durable idempotency and recovery responsibilities | About 10,000–20,000 lines |
Java, SQL/Mapper and necessary configuration are counted together, as with S++ source plus configuration. Dependencies, tests, pages and generated accessors are excluded. Existing frameworks and components are assumed to handle repetition; developers need not rewrite generated output line by line.
The rough comparison is thus about 1,350 maintained S++ lines versus ten to twenty thousand conventional Java-project lines. Java ranges are responsibility-based estimates, not independently measured implementations. One hundred thousand is actual generated volume, a different quantity. Appendix F7 gives methods and assumptions.
Connecting to the First Five Parts¶
| Practice | Principles Applied |
|---|---|
| Identify roles, contracts and responsibilities | Part I completeness and polymorphism; Part III models and services |
| Arrange queries, calculations, validations and saves | Part II dependencies and concurrency; Part III scenarios |
| Settle money/inventory and handle failure | Part I quantum services; Part IV transactions, conservation and recovery |
| Configure storage, requests, security, performance and deployment | Part III layers; Part IV guarantees; Part V technical capabilities |
Check objective completeness, ready inputs, consistent settlement and storage, and whether technical strategies honor them.
Chapter 28 — Identifying Roles, Behavior and Services from Requirements¶
The earlier parts now meet in one shop: a VIP buyer funds 500 US dollars, buys two goods at 60 each, pays and receives shipment, then examines cancellation, returns and failed reservations. These are illustrative inputs, not fixed demo seeds.
First establish objectives, then SPP expression, then APP/PHY integration and deployment. Meaning, source responsibilities and results can be checked together.
Describe Complete Activities First¶
“Buyer purchases goods” is too broad. Expand it:
| Activity | Participants | Completion Result |
|---|---|---|
| Funding | Buyer, settlement source, funding contract | Wallet increases; source decreases equally |
| Ordering | Buyer, cart, goods, stock, order | Terms saved, stock reserved, cart maintained |
| Payment | Buyer, merchant, order, payment contract | Funds transferred, order paid, receipt formed |
| Shipping | Buyer, order, inventory, shipment contract | Reserved becomes sold; shipping recorded |
| Return request | Buyer, order, request contract | Reason and processing state recorded |
| Return approval | Buyer, merchant, order, inventory, refund contract | Funds returned, stock replenished, result saved |
Payment deserves its own scenario because wallet debit is only one part. Payee, eligibility, amount, status and receipt determine completeness. Starting from Buyer methods can scatter cooperation; starting from payment exposes participant duties. This is the emphasis of Part I, Chapters 1–2.
Separate Entities, Roles and Contracts¶
Person belongs to customer and Product to product. Buyer, Merchant and Goods express shop identities; inventory owns StockLine and supply. The shop does not acquire ownership of all customer/product facts.
Person plays Buyer; Product plays Goods; buyer and goods jointly play CartLine, owning relationship quantity. Goods forms OrderLine with agreed name, quantity, price and amount. ShopOrder is an ordering contract; Receipt an evidence entity.
Current name differs from agreed name. “Pet Food A” later becoming “Pet Food A — New Packaging” must not change the old order. APP uses current(Goods.name) and snapshot(OrderLine.name, OrderLine.unitPrice), developed in Part VI, Chapter 32.
Membership and order numbers serve customers, not merely tables. business states that use; keys, versions and duplicate identifiers belong to technology. Part III, Chapters 13–14, now have concrete applications.
Classify Scenario Responsibilities¶
| Responsibility | Petstore Example | Work |
|---|---|---|
| Query | findBuyer, findMerchant, findShopOrder | Complete existing facts |
| Validation | checkOrderOwner, checkPaymentEligibility | Check ownership and qualification |
| Calculation | preparePayment, preparePaymentAgreementReceipt | Prepare amount, state and receipt |
| Quantum update | payOrderFunds | Transfer wallet funds to merchant |
| Ordinary update | updateShopOrder, insertReceipt | Save prepared facts |
Systems supply queries and ordinary saves; developers write calculations, validations and scenarios. Updates do not retrieve amounts or calculate discounts internally. Visible preparation concentrates rules in readable flows while persistence can be implemented separately.
What Polymorphism Reuses¶
Quotation reads Buyer tier, Goods price and CartLine quantity, without knowing the original database, supplier or external system. Another legal Goods player supplying those facts can reuse calculation and validation.
Meaning still matters: having a price field does not authorize arbitrary substitution for sales goods. Existing Petstore demonstrates concrete chains; new players need models, mappings and verification, not merely matching fields.
Follow Both Business and Technical Source¶
Read requirements, then the payment scenario and its named calculations/checks. Ask what each uses, produces and waits for.
Then read APP and PHY for storage, guards, transactions and resources. Functional directories organize source without changing domain identity or requiring a particular deployment machine.
Next establish participants and resource sources, then follow one set of amounts and quantities.
Chapter 29 — Zero Opening, Funding and Inventory Receipt¶
Purchasing needs buyer, store, goods, wallet and stock. Establishing participation is separate from moving money or goods: opening creates no gifted balance or stock. Every later nonzero change has a source.
Opening Prepares Identity and Zero Facts¶
New wallets, available/reserved/sold stock and sources begin at zero. Creation generates no nonzero transaction journal, and retries must not reset funded balances.
Business establishes identities; technology prepares records and quantum addresses. Durable split-storage tasks confirm and recover zero creation without per-scenario database retries. Part IV, Chapter 18, and Part V, Chapter 26, explain lifecycle and persistence.
After opening but before funding, the buyer exists with zero balance: an interpretable state.
Funding Shows a Conserved Pair¶
Funding 500 increases buyer.wallet by 500 and decreases settlementAccount.balance by 500. From zero, results are 500 and −500, still summing to zero.
The negative source is a counterpart within the demo boundary. Real integration must confirm funding source, payment and settlement eligibility; this does not permit unconditional gifts.
Funding source states:
quantum update transferWalletFunds(Buyer, SettlementAccount, WalletFundingAgreement) {
settlementAccount.balance -> buyer.wallet : walletFundingAgreement.amount;
}
The minimum responsibility is this pair's complete change. Splitting into unrelated remote updates loses the meaning of one funding activity.
Query Facts, Check Actual Bounds at Settlement¶
From the same source:
checkBuyerCredential; checkFundingAmount; prepareWalletFunding;
parallel { findBuyer; findSettlementAccount; }
identify(buyer); identify(settlementAccount);
transaction {
transferWalletFunds bounds {
settlementAccount.balance: [null, null];
buyer.wallet: [0, null];
};
}
Check inputs, prepare relationships, query buyer and source. Inputs are ready and independent, permitting concurrency. The transaction handles prepared transfer without looking up the amount inside the update.
Queried balances do not replace actual bounds: other funding or payment can intervene. This example uses a zero wallet lower bound and writes [null, null] for the settlement source, which is debited and so needs an explicit bound. Role-owned limits, if required, must be queried and passed to the quantum call.
Inventory Receipt Uses the Same Structure¶
Receiving ten decreases StockSupply.balance by ten and increases StockLine.available by ten. The properties differ from money but still need source, destination, quantity and settlement bounds.
The receipt scenario confirms goods, prepares stock/source, queries both concurrently and calls receiveInventory, whose facade binds to inventory quantum definitions. No database address or protocol enters business calls.
Similar structure does not require a generic action. Funding and stock receipt have different units and qualifications; distinct names preserve meaning.
Record a Checkable Baseline¶
| Fact | After Opening | After Funding and Receipt |
|---|---|---|
| Buyer wallet | 0 | 500 |
| Settlement source | 0 | −500 |
| Available / reserved / sold | 0 / 0 / 0 | 10 / 0 / 0 |
| Supply source | 0 | −10 |
Check negative-amount rejection, absent-identity nonsettlement and original-request replay without another credit. UI guards and transport idempotency do not replace positive-amount rules. Part VI, Chapter 32, gives configuration.
Chapter 30 — Quotation, Ordering, Payment and Shipping¶
Continue with wallet 500 and available stock ten. A VIP buys two at 60. Distinct quotation, ordering, payment and shipping activities organize different service categories.
Quotation Forms Candidate Terms¶
Subtotal 120, discount 12, discounted amount 108 qualifies for free shipping, so total is 108. See calculations.
Queried prices, quantities and tier produce a candidate, not persistent settlement. Lines retain names, quantities, unit prices and amounts; the order retains discount, shipping and total. Numerical price is descriptive quotation input, not automatically a quantum property.
Later price changes leave old agreed lines unchanged. Business requires historical terms; APP snapshots implement saving and querying them.
Ordering Connects Terms and Reservation¶
The order scenario has four dependency phases:
- Prepare selection and query buyer/catalog concurrently.
- Locate and query cart, validate it and calculate quotation.
- Prepare inventory identities, query and validate reservation, prepare order/cart changes.
- Save lines, order, cart and receipt with inventory reservation in the transaction.
Initial queries are independent. Stock query needs goods relationships prepared from the order, so cannot arbitrarily join the first parallel group.
Two units move from available to reserved: 8/2/0. Supply stays −10 and this goods total zero. Preliminary availability does not prevent competing orders, so actual bounds remain mandatory.
The compiler schedules quantum and ordinary work by preparation dependencies. preparePurchaseReceipt is inside the current transaction; not every statement can execute as a simultaneous save. Calculation precedes dependent receipt insertion. Built-in saves do no hidden completion.
Payment Makes Amount and Parties Explicit¶
Payment reads the formed order instead of cart or recalculating discounts. It verifies ownership and eligibility, prepares 108 and receipt, then transfers and saves.
From payment:
transaction {
transaction REQUIRED {
payOrderFunds bounds {
buyer.wallet: [0, null]; merchant.cash: [0, null];
};
}
updateShopOrder;
insertReceipt(paymentAgreement.receipt);
}
Wallet becomes 392 and merchant gains 108. Quantum services conserve funds; ordinary services save order and receipt. Their ready inputs permit parallel saving under supporting configuration.
Inner REQUIRED joins the outer logical boundary, not an independent settlement. APP/PHY determine joint physical commit or phases and recovery. SPP alone does not prove two databases share a transaction.
Shipping Uses Another Inventory Pair¶
Shipping queries buyer/order, prepares and queries inventory, checks status and reserved quantity, then prepares agreement and receipt.
Two move reserved to sold: available 8, reserved 0, sold 2. Ordinary saves retain state, tracking and receipt. Payment conserves money; shipping conserves quantities, with different completion conditions.
Check Each Stage¶
| Stage | Wallet | Merchant Delta | Available / Reserved / Sold | Ordinary Facts |
|---|---|---|---|---|
| Ordered | 500 | 0 | 8 / 2 / 0 | Lines, total 108, unpaid |
| Paid | 392 | +108 | 8 / 2 / 0 | Paid state, receipt |
| Shipped | 392 | +108 | 8 / 0 / 2 | Shipping state, tracking, receipt |
These expected illustrative results do not replace runtime evidence. Unknown payment cannot be shown as definitely failed or successful; APP confirms settlement and saves. Next distinguish recovery from subsequent business.
Chapter 31 — Cancellation, Returns, Reservations and Failure Handling¶
Completed order stages determine subsequent services. Cancellation and return are new activities; rollback and inverse execution restore the original failed activity. Both can reverse changes but have different meanings.
Follow Established Facts¶
These are alternative branches, not consecutive steps on one order:
| Starting Point | Activity | Money | Inventory |
|---|---|---|---|
| Ordered, unpaid | Cancel unpaid order | None | Two reserved become available |
| Paid, unshipped | Cancel paid order | Refund 108 | Two reserved become available |
| Delivered, return eligible | Request return | None | None; record request/reason |
| Request qualifies for approval | Approve return | Refund agreed amount | Corresponding sold units become available |
Return request needs buyer, original order and request. Approval adds funds and stock. Policies requiring physical receipt first need that fact and eligibility; demo rules are not universal.
Use confirmed amounts and quantities, not old wallet/stock snapshots that erase later business.
Business Refund Versus Automatic Inverse¶
Canceling a successful payment is new refund business with eligibility, contract and receipt. Undoing a payment that failed during execution restores its original effects; quantum inverses need no separate business service.
Ordinary restoration protects later versions under Part IV, Chapter 21. The current implementation still requires corresponding compensation capability; simple save logic is not proof all deployments already provide automatic conditional inverse updates.
If quantum funds settle but cross-resource order save fails, APP recovers committed phases. Full confirmed recovery permits declaring reversal; partial failure remains pending. SPP does not take over remote result queries and database retries.
Reservation Intentionally Retains Acceptance¶
The reservation scenario first saves acceptance and number, then reserves and confirms in a second transaction. Competition may cause the second to fail while acceptance survives.
With ten available and eleven requested, quantum bounds reject reservation. After confirmed rollback or inverse execution, the scenario records rejection while keeping the number for queries.
The second boundary is:
transaction {
reserveRequestedInventory bounds {
stockLines.available: [0, null];
stockLines.reserved: [0, null];
};
confirmPetReservation; updatePetReservationAgreement;
} fail {
if (ResultInfo.failure.recoveryStatus == "ROLLED_BACK" ||
ResultInfo.failure.recoveryStatus == "REVERSED") {
findStockLine; identify(stockLines);
rejectPetReservation;
transaction { updatePetReservationAgreement; }
}
}
The fresh stock query supports reason selection: insufficient current stock versus another incomplete reservation. Model and calculation define it. Business does not catch database exceptions; it handles accepted applications after recovery confirmation.
Three Different Failure Paths¶
| Situation | Facts | Handling |
|---|---|---|
| Invalid quantity | No settlement | Validation rejects before stock transaction |
| Reservation fails; recovery confirmed | Acceptance retained, reservation undone | fail saves business rejection and reason |
| Reservation/recovery unknown | Resource changes unconfirmed | APP confirms and recovers; no definite rejection |
Definite meaningful technical failures can reach business handling. Timeout is not automatically insufficient stock and must not make fail reserve again. The guard prevents that error.
If the rejection save fails, do not pretend it persisted. Preserve evidence and continue confirmation. ResultInfo describes this execution; stored status and reason describe the application.
Verify Completion with Faults¶
Check insufficient stock, ordinary-save failure after quantum changes, and unknown results. The first two require stock, application state and reason checks; unknown requires recovery records and no repeated reservation.
See failure evidence. LOCAL tests alone do not prove every real cross-domain recovery. Check resources and evidence together next.
Chapter 32 — Technical Configuration, Deployment and Integrated Verification¶
The preceding chapters expressed participants, quotation, settlement and failure. Now inspect existing configuration, extensions and deployment verification. Part V separation should become concrete files and results.
Put the Layers Together¶
| Layer | Payment Content | Files |
|---|---|---|
| SPP | Eligibility, amount, transfer, order and receipt | Scenario, models, calculations and validations |
| APP | Storage, request policy, bindings, transactions and environments | petshop.app |
| PHY | Database, quantum storage, routing, timeout and adapters | petshop.phy |
Business reviews parties, amount, eligibility and handling; developers review storage/calls; operators resources. AI helps each, but understanding payment does not require reviewing all generated Java and drivers. Runtime evidence still verifies guarantees.
Snippets come from APP and PHY.
Retain Agreed Facts Through Mapping¶
table SHOP_ORDER_LINES(OrderLine) {
primarykey(OrderLine.lineNumber);
auto OrderLine.lineNumber prefix "ORDER-LINE";
foreignkey(OrderLine.goods) references Goods;
snapshot(OrderLine.name, OrderLine.unitPrice);
}
Goods name uses current(Goods.name). Save an order, change product name and selling price, then query goods and old order. Current facts change, historical name/price remain. This tests Part III mapping and Part IV ownership together.
Protect Repeated Processing¶
Global and payment-entry declarations occur in requests and scope local:
requests { idempotency retention 3 days; duplicateWindow 5 seconds; }
duplicate key(Buyer.membershipNumber, ShopOrder.orderNumber)
facts(ShopOrder.orderNumber) payShopOrder;
PHY uses config requestIdempotencyAdapter = "jdbc";. UI guards handle quick repeated actions; remote idempotency handles repeated transmission. SPP still checks eligibility.
Verify no second payment for repeated clicks, original results for same-identity/content remote replay, and conflict for changed content. LOCAL calls do not register remote transport requests and cannot substitute for its tests. See protocol.
Check actual durable data sources and restart records. Three-day retention does not allow unknown requests to become new payments when time expires; unresolved recovery needs explicit treatment.
Compare Concentrated and Split Deployment¶
develop deploys four domains in one process:
transactions {
mode: LOCAL;
resource: shopRecordsResource;
ordinaryUpdates: PARALLEL;
}
PHY binds ordinary and quantum resources locally. Ready independent ordinary saves run concurrently; unprepared steps retain scenario dependencies.
testing separates customer and product processes while inventory and shop share a process. Ordinary and quantum databases are separate; PHY supplies routes/timeouts, APP chooses unified quantum storage and recovery for ordinary resources.
Domains stay the same while paths/resources change. LOCAL rollback is not cross-resource rollback. Quantum-first settlement followed by save failure requires phase confirmation and recovery, not relaxation of consistency.
Web, restart/conservation and failure evidence is in Appendix F. Recorded paths are neither all-fault proof nor a performance benchmark.
Apply Performance Methods to Queries¶
Goods browsing can cache names, descriptions and display facts. Property-use analysis can limit quotation to pricing/eligibility and listings to display, avoiding complete recursive loads.
Order lists need number, state and total; detail needs lines. Measure on-demand reads and responses separately, and never save partial objects as complete snapshots.
These proposals from Part V, Chapter 24, are not proven complete multilevel caches, compiler pruning or generic output projection in this example. Add keys, invalidation, permissions and unloaded-field save contracts, not just fewer scenario queries.
Display caches for wallets and availability do not replace actual payment/reservation bounds. “Two cached items” cannot guarantee buying two.
Extend the Existing Logging Example¶
Technical APP binds invocationTrace to shop services with intercept services, while PHY supplies generic Java logging. SPP has no added logging calls.
Business reviews payment, status and rejection reasons; technology reviews events. A fail-handled reservation normally returns AFTER even though reservation failed. Logs omit customer/order contents.
Part V, Chapter 27, shows custom Java metrics, alerts and controls through APP/PHY. Query caches and output masking need data adapters. See technical example.
Apply Security and Governance to Entries¶
testing has an interdomain token, not a complete authentication, authorization and data-protection system. Production work includes:
| Capability | Location | Verification |
|---|---|---|
| Authentication/access control | Page and domain entries | Trusted caller; no impersonating another buyer |
| Encryption/masking | Transfer, addresses, logs and output | No unauthorized sensitive disclosure |
| Content fingerprints | Request registration | Changed content under same identity detected |
| Tracing/metrics | Query, settlement, save and recovery | Locate delays and establish phase results |
| Throttling/isolation/breakers | Browse/update entries and remote resources | Contain faults while confirming accepted updates |
These are design tasks, not a claim all exist. Content fingerprints and ownership checks do not authenticate callers, as Part V, Chapter 25, explains.
Recommendations/images may degrade; payment cannot falsely report success or rejection after timeout. Correlate original requests, journals, ordinary saves and recovery, without SPP network catches.
Produce an Integrated Record¶
Check Chapters 29–30 numeric tables, then cancellation, return or reservation branches. Verify states, receipts, conservation, duplicates, versions, insufficient stock and unknown outcomes.
Keep performance comparison focused: serial versus parallel independent queries under identical business and resources, recording latency, overlap, throughput, errors and use. Add separate cache/projection comparisons if implemented. Appendix C holds detailed methodology.
Record source version, APP strategy, PHY resources and coverage. Business correctness, honored configuration and confirmable deployed results together complete the practice.
Part VII — Advanced Cases and Architectural Methods¶
Bank deposits and reversals illustrate complex rules, followed by system migration, design review and the expression of complex requirements. We distinguish role-oriented modeling, commercial service architecture and current language implementation, using a hash table to show how simple concepts form complex algorithms. The cases yield reusable methods for participating identities, behavior, ownership and execution evidence.
Chapter 33 — Bank Deposits, Repayment Allocation and Reversal¶
A bank's deposit business includes admission checks, authorization, repayment allocation, interest accrual, accounting and reversal. It provides a useful test of whether role-oriented service architecture can express complex rules while keeping business and technology separate.
This chapter uses the repository's bank deposit case study. Business logic is expressed in SPP, APP and PHY; tools generate the production Java code. Tests only prepare inputs, invoke generated services, assert outcomes and inject technical faults. Business rules and demonstration configuration have distinct sources; they do not represent every policy of the original bank system.
Distinct Participating Facts¶
Accounts, debts, product policies, business dates, authorization evidence, funding sources, processing plans and original transactions all participate. Account balance, interest-bearing amount, interest owed, principal owed and overdraft exposure have different meanings. Their common representation as amounts does not justify combining them into one field.
Front-office cash acceptance and core calculations may also have different amount conditions. Requiring a positive amount at the front office does not justify deleting a zero-amount repayment path in the core. Service contracts must preserve these differences between calling layers.
The current case separates accounts, eligibility, calculations, fees, accruals, postings, deposits and reversals into capability directories. Each scenario has its own file and directly organizes queries, checks, calculations and updates. A single umbrella scenario does not hide every step. The source navigation identifies these capabilities.
Repayment Allocation and Actual Fund Destinations¶
Normal debt and impaired debt can have different principal and interest repayment priorities. Business calculations first produce explicit components; the scenario then organizes account changes and postings. Eligibility and authorization checks remain visible in the scenario, while APP and PHY connect queries and storage.
Suppose a cash deposit of 100 US dollars repays 10 US dollars of interest and increases the customer's balance by 90 US dollars. The actual fund movements are:
Cash settlement account −100
Customer account +90
Bank interest-income account +10
Total fund movement 0
Interest owed separately falls by 10: this is a debt-settlement fact.
Treating a ten-dollar reduction in interest owed as the destination of funds is incomplete. Reducing debt explains how much less the customer owes; it does not explain where the money actually received by the bank is held. The case therefore explicitly introduces three internal accounts: interest income, collection-interest income and principal recovery. Calculations determine the components; quantum settlement updates actual recipients; the contract records the actual accounts and amounts; postings provide corresponding accounting evidence.
Debt and exposure continue to follow the case's quantum-property conventions, but must not be counted again in the fund-conservation group above. Fund conservation and changes in debt express different facts. APP specifies the current fund-conservation group; the runtime still records actual changes, bounds and inverse-transaction information for the other quantum properties.
Components need sufficient precision. Three-decimal interest can follow the agreed business mathematics; physical columns must not silently truncate it. Any required rounding must be explicit business policy. Demonstration parameters must also be distinguished from rules traced to original sources.
Prepare Through Queries and Calculations, Then Settle Within the Transaction¶
The cash-deposit scenario first queries the customer account, eligibility, funding counterparties and accrual facts in parallel. It then checks ownership, eligibility and authorization, and calculates fees, repayment components, postings and accruals. Updates that must hold together belong within an explicit transaction boundary.
Opening an account establishes only a zero balance; depositing cash creates actual fund movements. The bank's internal recipient accounts must also be opened first. A first interest repayment cannot create nonzero funds from nothing.
Within the transaction, quantum settlement comes first. Subsequent calculations of accrual and processing information prepare facts for ordinary saves, which persist account metadata, the deposit contract and postings. These calculations have dependencies preserved by the serial flow; parallel ordinary updates remain subject to their prerequisites. The scenario declares the complete business boundary, while APP and PHY implement it using actual resources.
Authorization Checks and Resuming After Authorization¶
Pending authorization is a business outcome, not a generic technical exception. The current case supports eligibility and authorization assessment. Persisting pending applications, choosing the authorization domain and resuming across processes still have boundaries to resolve.
A complete resumption flow should requery and recheck potentially changed eligibility after authorization arrives, then execute against current facts. Existing authorization checks do not constitute that complete workflow. The case's known issues records the distinction.
Reversal Driven by the Original Transaction¶
The cash-reversal scenario queries the original contract, actual postings and current account facts. It checks original ownership, recipient accounts, reversal eligibility and posting evidence, then derives reverse movements from the original settled components. Changed policies or loan status must not cause reallocation of the original amount.
If 100 US dollars is deposited and another five US dollars arrives later, reversing the first deposit must preserve the later five US dollars. Reversal must not restore the entire account to its old snapshot. Similarly, the original agreement records the fee and internal recipient accounts; current rates or account routing must not select them again.
The contract preserves a snapshot of settled postings. Before reversal, actual postings are compared against that evidence. Corrupted accounts, amounts or records must cause explicit rejection; balanced totals alone do not justify proceeding. Cross-day handling, Mode2, accruals and current eligibility also have their own checks and calculations.
A separate read-only reversal preview runs the same preparatory queries, checks and candidate calculations without settlement or persistence. Displaying eight candidate posting lines does not mean accounting facts have changed. Formal reversal must check current facts again.
Recovery from the Same Failure Under Different Deployments¶
In develop, related updates share a local transaction resource. If saving reversal postings fails, quantum and ordinary changes roll back together. The original transaction remains unreversed and can be retried after the outcome is confirmed.
In testing, quantum storage and ordinary records are separate. After quantum settlement, some ordinary Saga stages may already have committed. A later posting-save failure can trigger an inverse transaction for quantum funds, while already-committed ordinary facts may remain. The current case explicitly preserves RECOVERY_REQUIRED and handled=false. Restoring funds is not proof that the whole business activity has been undone.
This demonstrates the implementation boundary discussed in Part IV, Chapter 21. The architectural possibility of version-guarded automatic reversal for ordinary updates does not mean every repository and deployment already supports it. The case's fail block saves a failure-disposition record. It records that this transaction's fund movement was not completed only after the system confirms ROLLED_BACK or REVERSED; a reconciliation record cannot replace actual recovery.
The disposition record preserves the contract and system failure information as they stood at the time. Later queries must still show the original cause, phase and recovery status, without current balances or associations overwriting them. If saving that record also fails, the original transaction failure and actual recovery state must remain available.
Business Expression in Relation to Source Size¶
A source count on October 14, 2026 identified nine COBOL programs explicitly located by file or line references in the case documentation. They directly reference 135 COPYBOOKs; following nested references yields 161 distinct COPYBOOKs.
| Content | Files | Physical Lines, Including Blanks and Comments | Lines Excluding Blanks and Comments |
|---|---|---|---|
| COBOL programs directly located for analysis | 9 | 14,156 | 11,410 |
| Corresponding COPYBOOKs, including nested references | 161 | 23,488 | 11,179 |
| Original-source total | 170 | 37,644 | 22,589 |
| Current SPP business source and enums | 35 | 1,043 | 979 |
| Current APP and PHY configuration | 4 | 86 | 86 |
| Current S++ source total | 39 | 1,129 | 1,065 |
Expanding the scope to all related programs mentioned in the documentation gives 22 COBOL programs and 192 distinct COPYBOOKs: 45,587 physical lines, or 28,358 excluding blanks and comments. This broader scope includes dispatch, data access, accounting configuration and branches that have not been migrated.
These figures describe the maintenance scale of the business expression and original implementation, but their coverage differs. The original count includes entire source files; the case migrates selected business paths. Current S++ figures exclude tests, web pages, generated Java and shared frameworks. They therefore do not establish that more than thirty thousand lines of COBOL have been fully and equivalently replaced by roughly one thousand lines of S++, nor do they establish a productivity multiplier.
S++ concentrates selected rules in business models, calculations, checks and scenarios, leaving repetitive access and execution facilities to tools. Business expression becomes more focused, while tools and frameworks still implement the system. Appendix F9 provides detailed counts, source inventories and reproduction instructions.
From Web Operations to Verification Evidence¶
The Chinese-language deposit workbench supports account opening, cash deposits, reversal previews, formal reversals and accounting queries. The page submits participants and displays results; it does not calculate fees or repayment allocation. Communication loss is shown as an unconfirmed outcome, without automatically resubmitting an update or presenting input balances and candidate postings as settled facts.
Verification includes real JDBC storage, rule vectors, failures in two environments, concurrent contention, request idempotency, independent-process restarts and browser flows. See the latest verification record and Appendix F for configurations, batches and limits. Outstanding ordinary Saga recovery, complete authorization resumption and automatic resolution of unknown settlement outcomes remain separately documented in the completion audit.
Complex business becomes manageable by expressing rules, participating facts, processing plans, settlement and recovery separately, then connecting them through scenarios. Existing evidence supports defined paths. Original COBOL execution and bank-confirmed results remain distinct evidence levels; test counts alone cannot establish business equivalence.
Chapter 34 — Migrating an Existing Object-Oriented System¶
Start with one complete activity. Understand promised results, then identify participants, roles and behavior for explicit comparison with the old system.
Choose a Verifiable Business Line¶
Select clear inputs, durable results and failure rules, such as funding or payment. Preserve normal, rejection, duplicate and competition cases. Existing databases/interfaces can remain technical infrastructure.
The migration unit needs completion criteria. Moving a formula without actual settlement is calculation migration, not replacement of a transaction.
Identify Participating Identities from Classes¶
Read requirements and calls to separate User/Product duties by scenario. Identify buyer, payer, owner and fulfillment roles, players, borrowed and owned facts.
DTO fields are clues, not ready-made Roles. Reassess use, ownership and lifecycle; move technical keys and versions to application configuration.
Make Hidden Cooperation Visible¶
Identify access, qualification, calculation and persistence and establish atomic contracts. Place whole-activity order and boundaries in scenarios for review.
Pure calculation can migrate first with equal-input comparison, then facts, identity and settlement. Use independent expected results or historical evidence; copying a formula twice is not a correctness proof.
Control Deployment¶
Initially co-locate new services and existing adapters, limiting simultaneous changes to models, protocols and resources. Later split according to capacity and team ownership.
Data migration needs its own design for changed role, detail and snapshot structures. Decoding old records does not prove correct identity/ownership. Define authoritative writers during transition to avoid conflicting double writes.
Advance with Evidence¶
Retain versions, examples, durable outcomes and faults. Generation, local calculation, actual settlement and cross-process recovery represent different progress.
Completion returns to acceptance conditions: clear model, correct behavior, resources and operational recovery. Then new boundaries become maintainable system structure.
Chapter 35 — Architecture Review and Capability Boundaries¶
Review meaning, composition and guarantees. Declarations help discover errors, but designers still judge whether concepts are real, rules complete and implementation honors contracts.
Modeling Method and Architectural Approach Are Two Levels¶
“Role-oriented service architecture” contains two levels: role orientation is a modeling method; service architecture is an approach to organizing a system. For comparison, a service architecture based on object modeling may be called “object-oriented service architecture.” These names let us discuss modeling expressiveness separately from architectural scope. Object orientation can also support other architectures.
The service architecture in this book targets commercial business services. Purchasing, payment, reservations and shipping have explicit participating identities, processing rules and completion criteria, making them suitable for roles, services and scenarios. S++ delegates common queries, updates, conserved settlement and technical integration to tools, allowing business developers to express an activity with few declarations. This brevity comes from recurring domain structures and tool support; complex rules still need to be specified.
Fluid simulation, celestial mechanics and numerical solvers may instead focus on equations, discretization and error. Organizing those problems entirely as commercial services is usually inconvenient. A few business declarations cannot be expected to replace numerical algorithms. Task submission, resource allocation and result delivery in a scientific-computing system can use service architecture, while its solvers use expressions appropriate to their own domain.
When asking whether the architecture can meet requirements of arbitrary complexity, first distinguish a modeling method, a domain architecture and the capabilities already supported by the current language and tools. These are three separate questions.
Simple Concepts Can Also Build Complex Role Models¶
Object orientation starts with entities: many stateful objects receive actions, and their interactions describe a complete process. Role orientation starts with behavior: many activities identify their participating roles, and compositions of behavior describe a complete process. A scenario can be understood here as behavior in the broad sense, organizing several behaviors toward a larger objective.
Both approaches express state, change and composition; their starting points differ. Role orientation does not remove entities or data structures. It understands them through the behaviors in which they participate. A complex process can be decomposed into subbehaviors, and participants into simpler structures. Modeling can continue as long as each level has explicit state, rules and composition relationships.
A chess game, for example, can begin with board and piece objects that provide move methods. Alternatively, it can begin with moving behavior and identify the player, selected piece and board as participating roles, then organize alternating moves, position evaluation and game termination. The board still holds the position and pieces still have locations; behavior becomes the organizing thread.
Role-oriented modeling is therefore not inherently limited to commercial activities. For processes describable by state and computable rules, both approaches can extend through composition. Expressing a process, expressing it concisely and executing it efficiently are different questions. Appendix A8–A9 gives a constructive argument and its conditions.
Comparing the Starting Points with a Hash Table¶
A hash table shows why simple foundational concepts can compose into complex structures and algorithms.
Object orientation typically begins with a hash-table object. It holds a sparse storage table and offers put(key, value) and get(key) methods. The methods calculate positions, handle collisions, save records and find them. We first see what a hash table is and what it can do.
Role orientation can begin with “hash storage” behavior and identify three participating roles: a key used for lookup, a value to store and a sparse table providing storage. A particular string or identifier can play the key, a record the value, and a concrete structure the sparse table. The behavior explains their cooperation:
Hash storage (key, value, sparse table)
1. Calculate a candidate position from the key and table capacity.
2. Check whether that position already contains the same key.
3. If so, replace its associated value.
4. If another key occupies it, continue under the collision policy.
5. At an available position, save the key and value.
This is a modeling illustration, not executable current SPP syntax. Collision handling could use open addressing. Resizing can introduce behaviors for allocating a new table, migrating records and switching storage. Complexity remains, carried by explicit cooperating behaviors.
“Hash lookup” takes a key and sparse table, follows the same hashing and collision rules, and returns the found value or a not-found result. Storage and lookup must share these rules, or a successfully stored value might never be found.
For example, with capacity eight, let an integer key's initial position be its remainder on division by eight. Key 10 first checks position 2; key 18 also checks position 2. If key 10 occupies that position, a policy that searches forward for a free slot stores key 18 at position 3. Looking up 18 must likewise start at 2, compare the key and continue to 3. Object methods and role behaviors can both express this process.
Key and value are algorithmic participating roles here. They need not be declared as SPP business Roles, nor must every probe become a remote service. This example concerns role orientation as a foundational modeling method. Part III's business roles, atomic services and scenarios are its domain-specific constraints and applications in commercial service systems.
Reusing Object Implementations for Complex Algorithms¶
If needed, a general-purpose language could be built around role orientation, providing further expressions for data structures, algorithm composition and execution. Current S++ focuses on commercial business services. Demonstrating the modeling method does not require reimplementing every general computing facility.
Object orientation has already produced extensive data structures and algorithms. Role modeling can reuse these achievements: the business layer states required capabilities and results, APP declares bindings or adapters, and PHY supplies Java implementations and runtime resources. A complex Java object can internally use hash tables, graphs or numerical algorithms while exposing a clear capability contract.
For example, a delivery quotation may calculate distance from prepared locations and a route network. The business layer explains how distance affects pricing; a technical adapter can reuse Java route-search code. Another search algorithm can replace it without changing quotation rules if input, distance meaning and accuracy remain satisfied. Membership discounts, delivery eligibility and who bears the fee remain in SPP.
This integration needs the appropriate calculation or data-adapter interface. The before, after and failure interceptors in Part V receive invocation metadata only. They cannot replace route calculations or rewrite business participants. This discussion identifies the architectural location of complex implementation bindings in APP; actual binding forms depend on the interfaces provided by the implementation.
Complex requirements can thus be divided between explicit business models and reusable technical implementations. Their complexity does not require algorithms, data structures and deployment details all to enter the business language. Review whether responsibilities are clear, composition complete and each layer fulfills its contract.
Review Model Meaning¶
Each role explains player, behavior and own facts. Each contract identifies activity, parties and terms. Fields have owners and purposes; business credentials and technical identity have their places.
List-wrapper roles and generic-return contracts need reconsideration. Independently maintained duplicate properties need explicit ownership.
Review Composition¶
Services need clear duties; scenarios understandable dependencies and completion. Before parallel, check inputs, read/write conflicts and failure joins; before transaction, scope/resources; after phased execution, recovery owners.
A check failure ends its enclosing block and rolls back only when that block is the transaction; REQUIRED is not separate commit; co-location does not change domains; remote failure does not prove no transaction occurred. Explain these concrete effects.
Review Benefits and Costs¶
Roles and declarations reduce mixed logic but concentrate mapping, metadata and plans in tools/runtime. Teams must maintain them and understand output.
Simple business may not justify extra layers. Multiple-party cooperation, complex rules, conservation and environments benefit from explicit contracts. Decide according to real team/system needs.
Review Evidence Levels¶
Parsing proves accepted expression, compilation checked artifacts, running tests exercised paths, and faults/restarts specific recovery conditions. Performance also needs workload/resources.
Separating levels avoids claiming all reliability from one build. Maintain limits with versions so promises match capability.
Keep Architecture Explainable¶
Trace each activity through identity, behavior, contract, ownership and result. Locate unfinished phases on failure, responsibility on change and critical paths on optimization.
This book connects participants and behavior through roles/services into scenarios, then APP/PHY into running systems. That connection also guides continuous review and evolution.
Appendices¶
Appendices A–D develop definitions, assumptions, derivations and counterexamples for deeper reading. E provides language/runtime references; F sources and evidence. All equations use plain text.
Appendix A — The Service Model and Formal Derivations¶
“Service = participants × behavior” starts business analysis. We explain symbols with a transfer, then decomposition, composition and the precise meanings of equality. Equations use ordinary text readable in Markdown.
A1 Participants and Behavior Jointly Determine an Activity¶
A transfers 100 US dollars to B. Participant configuration p includes both and the agreement; behavior b defines debit, credit, bounds and results:
B = p × b
p = {source: A, destination: B, agreement: 100 US dollars}
b = complete the agreed transfer
B = the business activity of A transferring 100 US dollars to B
p is not an amount vector, and b not a number for arithmetic multiplication. The product expresses constitution. Replacing B with C changes the activity; replacing transfer with balance query changes objectives and results.
“If either is missing the result is zero” means no defined activity forms without necessary participants or behavior. Missing payee is not a successful zero-amount transfer. Rejection differs from numerical zero.
A2 Define What Is Compared¶
State x contains relevant participant facts. For identified A and B:
x = (A balance, B balance)
x₀ = (1000, 200)
Exec(B, x) = (resulting state, result classification, observable records)
Success gives (900, 300) and a record connected to this transaction. Rejection preserves (1000, 200) with its reason. Communication failure may temporarily prevent a definite answer and require actual-state lookup.
Business equivalence must specify records. Equal funds with different receipts is weaker than equal original associations and replay results. Service contracts choose observations; proofs cannot silently narrow them.
A3 Composition of a Complete Service¶
Here complete service uses the broad traditional meaning, such as order payment: queries, ownership, amount preparation, transfer and records. Addition denotes activity composition:
S = B₁ + B₂ + … + Bₙ = Σ Bᵢ
S is whole business and Σ composition. In SPP, services carry individual responsibilities and scenarios organize them. The equation does not require an ordinary service containing all calls. Dependencies, commit boundaries and failures remain part of composition; names alone do not specify execution.
“Transfer + order save” with joint commit differs from fund-first commit and later recovery. Success objectives may match, while failure contracts and guarantees differ.
Minimum Services and Composition Boundaries¶
Quantum minimum is conservation between two quantum properties; other minimums are role operations. Field reads, expressions and local assignments stay internal rather than becoming smaller business services.
Auxiliary inputs differ from operation targets. A line calculation can use prepared pricing rules but produces a line-role amount. A transfer contract supplies amount while conservation still concerns the balance pair. Collections, calculation reuse and request merging can cover many units without changing the minimum.
A4 Distribution over Behavior¶
If b₁ + b₂ means explicitly organized behaviors on the same participants:
p × (b₁ + b₂) = (p × b₁) + (p × b₂)
Left names the whole; right expands responsibilities. Equality requires the same bindings, inputs, sequence, boundaries and observations.
For pricing two lines (60, 2) and (20, 3):
Line 1 = 60 × 2 = 120
Line 2 = 20 × 3 = 60
Subtotal = 120 + 60 = 180
Expansion into two prices and aggregation preserves 180 because aggregation reads exactly their results. Moving aggregation earlier or changing per-line rounding requires rechecking.
Distribution explains expansion, not commutativity. Aggregation waiting for prices is a counterexample to arbitrary exchange.
A5 Distribution over Participants Describes Contributions¶
A contributes −100 and B +100:
δ_A = (−100, 0)
δ_B = (0, +100)
δ = δ_A + δ_B = (−100, +100)
Result = (1000, 200) + (−100, +100) = (900, 300)
(p_A + p_B) × b_transfer = p_A × b_transfer + p_B × b_transfer
Each right-hand term is this behavior's effect on its party, not an independent complete transfer. Otherwise the right side transfers twice.
Contributions can be analyzed separately while commit honors the whole. A-only completion (900, 200) violates conservation. Vector addition does not replace a joint-settlement protocol.
Joint eligibility also limits distribution: two jointly qualified applicants need not each qualify alone. Distinguish local contributions from whole-only rules before decomposition.
A6 Quantum Commutativity¶
For prepared identities and deltas δ_A and δ_B, when both settle:
A then B: (x + δ_A) + δ_B
B then A: (x + δ_B) + δ_A
Addition makes results equal. Both can affect one property: 1000 minus 100 and 200 gives 700 in either order. The basis is fixed-delta commutativity, not disjoint writes. Appendix B0 gives details.
General queries, checks and calculations still need dependency analysis; Appendix B treats them separately. Bound rejection and recovery require execution contracts.
A7 Testing Business/Technology Separation¶
Let F be the logical business transformation, G its implementation, and π the mapping from physical records to business facts. Successful semantics require:
π(G(physical input)) = F(π(physical input))
A cents column maps 10000 to 100 US dollars. A 10-dollar transfer must move 1000 cents, not ten. The mapping then preserves the formula.
Full contracts also preserve identity, bounds, failure and duplicate handling. Not changing the business objective does not make technical duration or responsibility zero.
A8 Constructing a Role-Behavior Model from Object Execution¶
This section concerns the expressiveness of a modeling method. It does not establish that the current SPP compiler supports every general-purpose program, or that either representation is shorter or faster. Complexity here means that structures, rules and execution steps can continue to compose; it does not mean executing an infinite process completely in finite time.
Consider an explicitly defined object model consisting of object states, operations and their composition. Let state x include object identities, relevant fields and execution position, and let a identify an operation and its inputs. One execution step is:
Object model: x --a--> x′
The state must include facts that affect later execution. A hash table includes not only key/value records but capacity and collision rules. If resizing affects later positions, the new capacity is part of the state. If the original model permits alternative next steps, as with concurrent scheduling, this notation denotes a transition relation rather than a single function.
Construct a role behavior for each object operation. Its target becomes a participating role; input values become necessary participants or behavior inputs; state changes follow the original rules. An operation involving several objects lets them play their corresponding roles. Method calls, conditional choices and repetition become behavior composition, branches and repetition.
Let E encode object-model states as role-model states and b_a be the constructed behavior. Each step must satisfy:
Original step: x --a--> x′
Corresponding step: E(x) --b_a--> E(x′)
Business or algorithm observations:
Obs_role(E(x)) = Obs_object(x)
Induction then covers every finite execution sequence:
- E encodes the initial state with equal relevant facts and observations.
- Suppose the representations correspond after step k. The behavior for operation k+1 was constructed from its original rules, so the resulting state and observations still correspond.
- After any finite number of steps, the role model therefore continues to express the process already described by the object model.
If an object-based hash insertion encounters a collision at slot 2, checks slot 3 and writes a record, the role model follows the same steps. If the object model resizes and rearranges records first, the role model must include that migration and switch. Encoding only the final key/value set would discard facts that affect subsequent behavior.
The construction assumes the ability to preserve required state, express original operation rules, and provide necessary choice, repetition and composition. These algorithmic facilities need not mean remote services, business transactions or commercial contracts. Imposing SPP's domain constraints on general modeling would change the subject of the argument.
A reverse construction is also possible: objects hold role-model participant state, methods implement behavior, and coordinating objects organize composition. The two modeling starting points can therefore carry the same computable process under these conditions. Clarity and implementation cost remain separate questions.
A9 Expressiveness, Domain Brevity and Implementation Capability¶
The preceding argument is conditional and constructive. Without explaining how state, rules and composition are expressed, merely observing that no counterexample has been found is not a universal proof. A counterexample must likewise identify a missing expressive capability, rather than show that one notation is inconvenient.
Simulation of the real world first needs an observation scope. A chess model records rules, positions and outcomes; it need not also record the material of each piece or every molecule's motion. Simulation here means preserving specified observations between models. Changing the modeling starting point does not make infinite-precision continuous facts or noncomputable rules fully manageable by finite computation.
Three questions can now be separated:
| Question | What Must Be Established | What Does Not Follow Automatically |
|---|---|---|
| Can the modeling method express a complex process? | Constructions for state, change and composition, with corresponding observations | The current compiler implements every required capability |
| Can the domain architecture express commercial services concisely? | How roles, services and scenarios reuse recurring domain structures | Every scientific algorithm fits a few business declarations |
| Can current tools execute a requirement? | Syntax, binding interfaces, representation, execution and resources | A valid model alone guarantees performance and reliability |
S++ obtains much of its brevity from common commercial-service capabilities. Once payment participants, amounts and processing relationships are declared, tools provide standard queries, updates, identity maintenance and technical integration. A new route-search algorithm still has its own complexity; existing Java code can implement it without expanding it into many business declarations.
For external calculation reuse, let C denote the business-required result, J the adapter and implementation, and encode/decode the input/output mappings. The contract requires:
decode(J(encode(business input))) = C(business input)
The agreement must also cover precision, missing input and failure semantics. A route-search implementation cannot return straight-line distance when road distance is required and still claim equivalence. Missing road data cannot silently produce a zero distance. Approximation needs a contractual error bound; comparison then asks whether the result satisfies that contract, rather than demanding exact numerical equality.
A pure calculation implementation must not hide data queries, persistence or transactional side effects, or the scenario's dependencies and boundaries become incomplete. Required external facts should first be prepared through queries and then passed to calculation. Persistence remains an update organized by the scenario. Reusing general algorithms must not conceal business responsibilities inside technical adapters.
A complex requirement can therefore use roles for business modeling, APP bindings and adapters for existing capabilities, and PHY for implementations and resources. Missing support in a particular binding interface is an implementation gap; it does not prove that the modeling method cannot express the requirement.
Sources: S++ concepts (maintainer reference: ../../../spp/docs/cn/concept.md), numeric semantics and participant execution. Cross-document issues are tracked outside the manuscript in known issues.
Appendix B — Conditions for Exchange, Reordering and Parallelism¶
We first prove fixed quantum-delta commutativity, including changes to the same property. We separately prove independent read/write conditions for general activities, then discuss implementation, bounds and failures.
B0 Quantum-Service Commutativity¶
Let x be a state vector within one business dimension. A and B express prepared δ_A and δ_B. Identities, amounts and units are fixed; intermediate balances do not redefine deltas. If both settle:
F_A(x) = x + δ_A
F_B(x) = x + δ_B
A then B: F_B(F_A(x)) = (x + δ_A) + δ_B
B then A: F_A(F_B(x)) = (x + δ_B) + δ_A
By associativity and commutativity of addition:
(x + δ_A) + δ_B = (x + δ_B) + δ_A
Both orders produce the same state even with overlapping coordinates. From 1000, −100 and −200 both give 700. Transfers from A to B and C can be written:
x = (1000, 0, 0)
δ_A = (−100, +100, 0)
δ_B = (−200, 0, +200)
Either final state = (700, 100, 200)
Each delta and their joint result conserve. Intermediate states can differ, but settled totals cannot. Using intermediate values to recalculate amounts changes the delta set being compared.
For n changes and any permutation π:
x_final = x + Σ δᵢ = x + δ_π(1) + … + δ_π(n)
Every permutation is a finite sequence of adjacent exchanges, each preserving results. This compares the same settled set. Which competing requests settle and how faults avoid lost/duplicate deltas are separate contracts, treated in B7–B9.
B1 Fact Granularity¶
View state as a map from fact locations to values:
(buyer A, tier) → VIP
(goods P, price) → 60
(order O, discount) → 12
Different objects of one type are different locations; properties of one object may also be distinct. Include actual mapper completion: copying a whole object writes more than one visibly used field.
R_A contains every location possibly read by A, W_A every changed location. Reads in conditions count. Resolve aliases before deciding whether names denote the same fact.
B2 Assumptions¶
The following proof assumes:
- A and B are deterministic, terminating and successful over the input range; rejection and faults are separate.
- R and W cover every effect, including conditions, mapping and hidden access.
- Activities use only their read facts and modify only declared writes, with no additional external effects.
- No third activity changes relevant inputs during comparison.
- Implementation correctly realizes independent logical writes, with final observation after both finish.
The last excludes corrupting adjacent fields, partial-object reads or undefined memory behavior as substitutes for the logical model.
B3 Sufficient Independence Conditions¶
W_A ∩ R_B = ∅ B does not read A's writes
W_B ∩ R_A = ∅ A does not read B's writes
W_A ∩ W_B = ∅ no shared writes
∩ denotes intersection and ∅ the empty set. Read sets may overlap; both reading one stable price does not overwrite it.
B4 Step-by-Step Proof for Successful States¶
Start with any qualifying x. Let a be the result of A alone and b of B alone.
First, A modifies only W_A, disjoint from R_B. B reads the same facts in a as in x.
Second, B is deterministic, so preceding A does not change B's calculated writes. Symmetrically, preceding B does not change A's writes.
Third, compare each final position:
| Location | A then B | B then A |
|---|---|---|
| In W_A | A's value, not overwritten | The same A value |
| In W_B | The same B value | B's value, not overwritten |
| Outside both | Original x | Original x |
Disjoint writes assign each location exactly one category. Final states are equal. Deterministic outputs from those facts are equal too, completing the proof within assumptions.
B5 Why Parallel Execution Can Be Considered¶
Neither activity changes the other's reads, and disjoint writes do not overwrite. Correctly protected interleavings can therefore produce the same final state.
Business must not observe unfinished whole results. Two fields may be updated at different moments, exposing a partial record. Require publication after joining, appropriate isolation or common commit if only complete results are visible.
The proof does not automatically supply thread safety or atomicity. It establishes logical permission; runtime supplies scheduling, writes and publication.
B6 Counterexample with a Dependency¶
A sets line amount to 120; B copies current line amount into subtotal. Both initially zero:
A then B: line = 120, subtotal = 120
B then A: line = 120, subtotal = 0
A's writes intersect B's reads. Concurrent B may likewise read zero. Independent line calculations can overlap, but summation waits.
B7 Commutative Mathematics, Lost Implementation Updates¶
A adds ten and B twenty to 100. Mathematics gives 130 in either order; read-then-write can lose a delta:
| Time | A | B | Balance |
|---|---|---|---|
| 1 | Read 100 | 100 | |
| 2 | Read 100 | 100 | |
| 3 | Write 110 | 110 | |
| 4 | Write 120 | 120 |
A's ten is overwritten. Atomic deltas, exclusion or appropriate isolation prevent this only when implemented. Shared writes do not satisfy B3; other safe concurrency needs another proof.
B8 Bounds Change Accepted Results¶
From 100 with no overdraft, A debits 80 and B 30:
A first: A succeeds, balance 20; B rejects; final 20.
B first: B succeeds, balance 70; A rejects; final 70.
The algebraic total is order-independent, but acceptance and final balance are not. A contract may permit settlement order to arbitrate competition, but cannot claim each request's result is independent of order.
B9 Failures and External Observations¶
A and B write disjoint parties. If A commits then B fails, A remains; if B fails first and stops the scenario, A never occurs. Successful-path exchange does not prove equivalent failure processes.
Joint success needs common commit or recovery. Permitted partial results need explicit states. A parallel fault requires knowing which other branches completed, not merely terminating a waiting thread.
Notifications are observations too. Announcing success after debit but before credit exposes an incomplete promise. Publish after confirmation, with duplication and delivery handling.
B10 Joining Parallel Validations¶
Two validations reading stable facts without mutation can return independently. If both must pass:
Continue = A passes AND B passes
AND is order-independent. Choosing the first completed rejection makes displayed reasons schedule-dependent. Fixed priority requires collecting and selecting results accordingly. Immediate-stop control must specify scope and effects on other branches.
This defines the contract needed, not a claim arbitrary bare checks already have it. Appendix E and editorial records state expression limits.
B11 Extending to Groups¶
Build read/write sets and dependency edges for production, conflicts, observation and commit. Apply sufficient independence to unrelated nodes; legal sequences satisfy all prerequisites.
Two legal sequences differing only in independent-node order can be transformed by adjacent independent exchanges. Each preserves successful results. Shared writes, dynamic aliases or external state prevent direct use of this corollary.
B12 Ordinary Updates with Complete Inputs Commute¶
Within one transaction's save phase, built-in updates contain no business queries, calculation or checks. Queries/calculations and quantum changes have prepared facts. Any post-settlement calculation/check completes first in serial groups. Let P be complete facts to save; Uᵢ persists its part Pᵢ.
Writes do not depend on another save's result. Different services save different locations; if they overlap, both save the same already fixed P value.
| Location k | Final Value in Either Order |
|---|---|
| Only A saves | P_A(k) |
| Only B saves | P_B(k) |
| Both save | P_A(k) = P_B(k) = P(k) |
| Neither saves | Original value |
Thus:
U_B(U_A(x; P); P) = U_A(U_B(x; P); P)
Adjacent exchange extends to any number, allowing concurrent saves after quantum work followed by a join. Physical implementation still must share transaction context, protect writes and honor common commit or recovery.
Prepared order status, amount and receipt can save independently. Receipt calculations based on settlement must complete first; this proof exchanges ready saves, not calculation with saving.
Built-in updates prevent hidden business access/calls. Serial groups enforce preparation. Complete input and consistent save relations support the proof. Same-identity insert/delete conflicts, foreign-key ordering and physical concurrency are editorial KI-011.
Different transactions can have different P and still require version/conflict protection. Intra-boundary exchange does not prove arbitrary cross-transaction overwrite commutativity.
B13 Why Quantum Work Can Move Earlier¶
For quantum Q and ordinary U within one boundary:
- The scenario prepares Q's identity, deltas and bounds; U does not complete or change them.
- U saves facts, does not produce Q's business calculations and does not modify quantum properties.
- Q's fixed deltas satisfy B0.
- Q completes settlement facts; required further calculations/checks run in serial groups before U under B12.
Q therefore has no business need to await U. Delaying saves does not affect Q's inputs. Saves may need Q results, so dependency points from quantum results to saving. The compiler can concentrate Q first.
Prepare scenario inputs
↓
Q: concentrated quantum execution, unordered or merged
↓
Complete settlement facts
↓
Serial group: further calculations/checks as needed
↓
U: concurrent ordinary saves
↓
Join and complete under the transaction contract
Commutativity explains Q's internal order, complete-input saving U's internal order, and one-way dependency cross-category scheduling. Quantum-first planning retains explicit settlement-calculation-validation-save dependencies.
Reordering stays within one boundary, without merging independent transactions or turning physical phases into atomic commit. LOCAL can commit common resources; phased backends retain protocols. Editorial KI-012 tracks implementation coverage.
Sources: participant execution, transactions/storage and scenario composition design (maintainer reference: ../../scenario/docs/Composit.docx).
Appendix C — Performance Models and Experimental Methods¶
Starting with one call, we derive serial, parallel and merged execution, then critical paths, capacity, completion probability and experiments. All numeric examples are hypothetical, not Petstore measurements.
C1 Cost of One Call¶
Along its actual path:
lᵢ = cᵢ + eᵢ + qᵢ + tᵢ + dᵢ
| Symbol | Meaning |
|---|---|
| cᵢ | Transfer and round-trip cost |
| eᵢ | Encoding, decoding and adaptation |
| qᵢ | Queueing for service, connections and resources |
| tᵢ | Net business work and resource access |
| dᵢ | Uncounted transaction setup, coordination and commit |
Do not double-count. If server duration includes commit, decompose it or use whole lᵢ without another dᵢ. Overlapping intervals require path analysis, not simple addition.
C2 Why Serial Calls Accumulate¶
If each call begins after the preceding complete return, intervals do not overlap:
T_serial = h + Σ lᵢ + u
h prepares common input; u is shared postprocessing/commit. Do not recount branch transactions already in dᵢ.
With equal c and d, omitting other costs:
T_fine_serial = Σ(c + d + tᵢ) = n(c + d) + Σ tᵢ
T_one_call = c + d + Σ tᵢ
Difference = (n − 1)(c + d)
The difference comes from repeated boundaries. It assumes comparable work/results and genuinely mergeable communication and commits. Independent business phases cannot be merged just to lower a formula.
C3 Independent Parallel Branches¶
With simultaneous starts, ready inputs, no mutual waits and no extra contention, completion is the last branch finish:
T_parallel = h + max(l₁, l₂, …, lₙ) + j + u
Savings = Σ lᵢ − max(lᵢ) − j
Net gain requires: j < Σ lᵢ − max(lᵢ)
j is additional scheduling/join overhead. Two 1-ms tasks with 3-ms overhead take 2 ms serially but 4 ms in parallel. Small work may not justify it.
C4 One Communication and One Commit¶
If one entry carries independent internal work, resources suffice and actual common commit exists:
T_combined_parallel = c + d + max(tᵢ) + j
This reduces boundaries and overlaps work. Remote branches still have their own communication, and phased quantum/ordinary commits retain phase costs. SPP syntax alone cannot remove them.
C5 A Complete Numeric Example¶
Let h = 5 ms, l₁ = 40, l₂ = 70, j = 3 and u = 10:
T_serial = 5 + 40 + 70 + 10 = 125 ms
T_parallel = 5 + max(40, 70) + 3 + 10 = 88 ms
Savings = 37 ms
Speedup = 125 / 88 ≈ 1.42
If contention increases l₂ to 110:
T_parallel_contended = 5 + 110 + 3 + 10 = 128 ms
It becomes slower than original serial execution. Measure actual branch times rather than retaining unchanged-duration assumptions.
C6 Dependency Graphs and Critical Paths¶
For an acyclic graph with duration t(v), unlimited resources and no scheduling overhead:
E(v) = t(v) if v has no predecessors
E(v) = t(v) + max{E(p)} for predecessors p
T_ideal = max{E(v)} over terminal nodes
A node waits for every predecessor; the latest determines its start. Computing E topologically gives the longest dependency path.
Queries of 40 and 70, quotation of ten and settlement of twenty yield:
E_buyer = 40
E_goods = 70
E_quote = max(40, 70) + 10 = 80
E_settlement = 80 + 20 = 100
Scheduling, queues and retries add or change durations. Improving the 40-ms branch cannot shorten the critical 70-ms branch.
C7 Lower Bounds with Finite Resources¶
For homogeneous resource work W and k equivalent slots:
T ≥ max(CP, W/k)
Critical-path activities cannot overlap, requiring CP. Over interval T, k slots perform at most k×T work, which must reach W.
Do not treat all network waits as CPU work or database connections as CPU slots. Model heterogeneous bottlenecks separately; thread count is not automatically k.
C8 Latency and Throughput¶
Parallelism can reduce one request's time while consuming several connections. If database work capacity is fixed and work unchanged, throughput may not rise.
Under stable load and a fixed boundary, average in-flight L, throughput λ and average residence T satisfy L = λ×T. Summing occupied time over a window and averaging by requests/time explains the relationship. It requires stability, not a continually growing queue, and averages rather than high percentiles.
Measure latency, throughput, concurrency and utilization together. One-request improvement does not establish capacity.
C9 Comparable Experiments¶
Keep inputs, scale, relationships, eligibility, commit guarantees, protocols and resources equal. Change only the studied factor. After warmup, alternate repeated trials to avoid cache or JIT favoring a fixed order.
Serial/parallel comparison keeps deployment unchanged; local/remote is a separate experiment. Do not simultaneously alter threads, storage, commits and rules and attribute everything to parallelism.
Observe critical paths at low load, then increase concurrency to locate queueing, rejection and saturation. Branch start/end events verify overlap. Artificial delays establish scheduling, not real workload performance.
C10 Metrics and Reports¶
Keep request start/end, result, retries and branch associations. Report median and percentiles from sorted durations; nearest-rank p95 is item ceil(0.95×N), with the method stated.
Report success, business rejection, technical failure and timeout separately. Do not discard slow failures and report success averages alone. Define throughput as completed requests or successful business, and distinguish replay from new settlement.
Retain versions, build, resources, workloads, warmup, rounds, correctness, raw data and analysis. Functional regression is not this benchmark.
C11 Remote Dependencies and Whole-Business Completion¶
This section asks whether valid business completes within a deadline. Eligibility rejection is not technical unavailability, and per-request completion probability is not time-based availability.
If every remote call must succeed, with Sᵢ its in-deadline success:
P(completion) = P(S₁ ∩ S₂ ∩ … ∩ Sₙ)
Only with independence, no retry/alternative/partial-completion policy and equal p:
P(completion) = pⁿ
p = 0.999, n = 20:
pⁿ ≈ 0.980189 ≈ 98.02%
For 0 < p < 1, each required call multiplies probability by a factor below one. This proves cost in that model, not universal incompatibility of microservice scalability and availability.
Shared networks, databases and hosts invalidate independence. Use joint probability or measurement instead. Retry, redundancy, isolation, alternatives and recovery change event definitions and structure and require new models.
C12 What Concurrency, Merging and Local Deployment Change¶
Serial and parallel require the same intersection if scheduling does not change success conditions. Starting order alone does not remove branch faults. Parallelism mainly reduces time; fixed deadlines may see fewer accumulated-time timeouts, not automatic availability improvement.
Merged requests reduce communication and protocol boundaries. Multiple deltas to one executor can arrive together, reducing request-level failures and confirmation cost. The executor still must apply every change; one entry does not make internal resources infallible.
Local calculation/checks remove separate remote dependencies without changing logical service count. Host and storage still fail, requiring their own statistics. Do not replace pⁿ by p and call it measured improvement.
The book's latency mechanisms are exposed independence, quantum request merging and local small operations. They do not prove SPP fixes remote-dependency availability.
Use C9–C10 with equal guarantees/resources, measuring remote calls, timeouts and failures. Keep slow failures in statistics.
C13 Property-Use Analysis and Multilevel Caching¶
Determining Query Sets¶
For role R, Uses(R) includes properties read by scenarios, calculations, validations, quantum calls and bound expressions within the compilation scope. Follow calculation calls, mappings and relationships, not merely direct expressions.
Queries also locate and confirm identity and obtain saving baselines:
Fields(R) = Uses(R) ∪ NeededIdentity(R) ∪ NeededBaseline(R)
Outputs count as use too. APP and output-protocol dependencies need analyzable implementation or explicit declarations. Without evidence, choose conservative fields rather than treating unrecognized access as absent.
Mapped attributes require source dependency sets: Buyer tier may come from a role and address from a root entity. Preserve identity/mapping/association requirements; on-demand querying is not arbitrarily skipping necessary role relationships.
Correctness requires every property to be completed from its source before use. Unloaded differs from actual null or zero. Pruning must not make defaults business facts or replace stable input participants.
Partial Queries and Saving¶
Saving must not overwrite unloaded facts with defaults. Loaded-range metadata, explicit writes or another preservation mechanism can protect them; valid baselines still support versions.
Analysis, reading, mapping and saving jointly implement optimization. Fewer SELECT columns or response fields alone do not prove whole-business equivalence.
Cache-Hit Conditions¶
Request caches reduce repeated scenario reads; process caches reuse stable facts across requests. Remote source facts can be locally cached then mapped.
Keys include source domain, identity and isolation conditions, not only type or incomplete numbers. Records state loaded sets. If requested fields F and cached C satisfy F ⊆ C, field coverage qualifies; otherwise fetch missing fields or refresh.
Versions, notifications or expiration offer different freshness guarantees chosen by requirements. Missing identity, technical read failure and expiry differ; old confirmation cannot be reused unconditionally.
Cache speeds retrieval, not actual quantum bounds/conservation. Display balances can be cached, while settlement uses authoritative facts. Protected ordinary transaction reads also need appropriate version, isolation and baseline conditions.
Gains and Verification¶
Pruning reduces transfer, reading and mapping but does not guarantee scan time proportional to columns. Cache savings depend on hits, refresh, size and contention.
Keep roles, rules and save results fixed. Record fields, payload, source calls, hits, latency and refresh costs. Test missing dependencies, partial hits, source changes, conflicts and saving unloaded fields to ensure unchanged meaning.
These are methods and correctness conditions, not acceptance evidence that current compiler implements generic pruning/caching. Editorial KI-014 tracks scope.
Sources: S++ concepts (maintainer reference: ../../../spp/docs/cn/concept.md) and deployment configuration.
Appendix D — Quantum Services and Conservation Mechanisms¶
Balances and inventory explain deltas, conservation, bounds, atomic settlement and inverses. Each conclusion separates mathematical grounds from execution conditions, avoiding conservation arithmetic as a substitute for commit guarantees.
D1 Changes as Vectors¶
The minimum quantum service is a pair of properties with equal opposite changes in one dimension. A larger vector can embed that pair or combine several services. State dimension differs from minimum service granularity.
For accounts A, B and C, A transfers 100 to B:
x = (1000, 200, 50)
δ = (−100, +100, 0)
x' = x + δ = (900, 300, 50)
Coordinates identify complete participants and properties, not merely “balance.” Units and precision must agree; inventory coordinates are per goods identity.
D2 Conservation Proof¶
Define total in one dimension:
Q(x) = Σ xᵢ
Q(x + δ) = Σ(xᵢ + δᵢ) = Σ xᵢ + Σ δᵢ
Σ δᵢ = 0 ⇒ Q(x + δ) = Q(x)
Before and after totals are equal exactly when deltas sum to zero. −100 +100 +0 qualifies; debit 100 and credit 99 leave −1. A fee transferred to another account requires that real destination in the model.
This proves the applied complete vector. Crashing after debit before credit can still violate actual conservation, so joint commit is necessary.
D3 Prove Independent Dimensions Separately¶
For available, reserved, sold and supply of goods P:
After receipt: (10, 0, 0, −10)
After reserving 2: (8, 2, 0, −10)
After shipping 2: (8, 0, 2, −10)
Each sums to zero. Goods Q needs a separate equation; one missing P and extra Q do not prove P correct. Money and item counts cannot be added. Exchange and unit conversion require rates, units, differences and rounding policies.
D4 Prepared Inputs and Actual Bounds¶
The caller prepares fixed amount a and postsettlement bounds. Execution uses current x, not an earlier snapshot:
Candidate xᵢ' = xᵢ + δᵢ
Require Lᵢ ≤ xᵢ' ≤ Uᵢ
null disables the corresponding side. Participant/contract facts determine limits before invocation; execution handles dynamic balances.
Two debits of 80 may both see 100. After one leaves 20, the other's −60 candidate rejects. Checking and protected writing belong to one mechanism, not a check followed by unprotected write.
D5 Whole-Group Settlement¶
Success applies the entire δ; rejection applies none of the group. Partial unfinished state must not be published as success.
A local backend can protect reads, calculate, validate and write in one database transaction. Actual connection, isolation or atomic conditions and transaction capability determine guarantees.
Cross-resource execution needs coordination/recovery. A declared boundary does not coordinate independent connections automatically. Later ordinary failure cannot locally roll back already committed quantum phases.
D6 Merged Submission and Delta Aggregation¶
Prepared services have order-independent joint results under B0, so one request can carry several without sequential send-and-wait order. The executor arranges changes and common submission.
A merged request can preserve individual changes, identities, bounds and result associations. If allowed, aggregate by complete identity and dimension:
A → B 100: δ₁ = (−100, +100, 0)
B → C 30: δ₂ = (0, −30, +30)
Net δ = δ₁ + δ₂ = (−100, +70, +30)
Net sum = 0
Zero-sum deltas retain conservation after aggregation. Communication merging differs from netting: one request can retain original details. Per-step and net-value bounds need not agree.
From (0,0), A→B100 then B→A100 nets zero. Final-only checks pass; non-overdraft checks reject the first step. The contract must select the semantic boundary instead of assuming conservation permits temporary overdraft.
With n changes, fixed request overhead h and per-change transmission p:
Separate communication = n × h + n × p
Merged communication = h + n × p
Fixed overhead saved = (n − 1) × h
Data still travels. This is not system timing prediction: size, response details, sharding and protocol affect savings. One submitted request may still cause backend cross-resource communication.
Keep duplicate detection, original interpretation and recovery evidence. Net zero does not mean no business occurred. The objective is reduced communication without altered meaning or guarantees.
D7 Request Identity and Idempotency¶
Identity binds immutable amounts, endpoints, group and bounds. Successful same-identity retries return original results without reapplying δ; changed facts conflict.
Durable identity/results must relate reliably to actual writes. Crashing between balance and dedupe recording can duplicate credit; recording success first can claim a nonexistent update. Backends must resolve this commit relationship.
D8 Why Inverse Transactions Preserve Later Changes¶
Original x, settled δ and later net e give:
Before inverse = x + δ + e
After inverse = x + δ + e − δ = x + e
Thus e remains. 100 +50 +20 −50 =120; restoring 100 erases twenty.
The system automatically inverses original records without developer reverse services. It must preserve exact components and identity, additive meaning and deduplication. Assignment or irreversible external effects do not satisfy this proof.
D9 Inverses Versus Subsequent Business¶
Failure recovery restores original quantum effects. Original location, inverse constraints, durable results, deduplication and recovery are system duties, with APP technical policy.
Later partial refund, reversal or fees are new business. A partial amount or deducted fee differs from −δ and needs its own eligibility/formula. Original inverse −δ must not be confused with a new δ′.
D10 Unknown Outcomes and Retry¶
Disconnection after commit but before response leaves timeout with possibly changed balance. Stable-identity lookup distinguishes confirmed success, rejection, protocol-confirmed nonexecution and unknown.
Unknown does not mean unexecuted. New identity may transfer twice; immediate compensation may reverse something that never occurred. Confirm under protocol or wait for recovery evidence.
D11 Boundaries and Implementation Coverage¶
| Relation | Required Actual Guarantee |
|---|---|
| LOCAL | Same JVM, actual database/schema, shared connection/commit resources |
| Non-LOCAL mixed phases | Defined quantum/ordinary order, durable outcomes and recovery |
| REQUIRED | Reuse outer boundary, no independent commit |
| REQUIRES_NEW | Independent resources/propagation and outer-failure handling |
| Unsupported propagation/protocol | Explicit build/deployment rejection, no silent weakening |
Appendices E/F describe example support. Names and passing test counts alone do not prove arbitrary resource combinations.
D12 Value Uncertainty After Settlement and Observation¶
At preparation the query sees b; this request settles δ. Let C contain other changes effective before later observation. In the same additive dimension:
b_observed = b + δ + Σ eⱼ (j ∈ C)
Confirming δ without knowing C cannot determine the observed balance from b+δ alone. With b=1000, δ=−100 and another e=−200:
Other request not effective: C = ∅, observed 900
Other request effective: C = {e}, observed 700
Both assume this debit settled. Superposition here is epistemic uncertainty after settlement and before observation, not two stored balances or physical probabilities/amplitudes. Confirmation does not identify every concurrent change included in observation.
For a fixed settled set:
(1000 − 100) − 200 = (1000 − 200) − 100 = 700
This does not prove every request can settle. From 100, −80 and −30 cannot both satisfy zero lower bound. Order/arbitration can determine rejection. Candidate states pass through bounds; not every algebraic value is legal.
Confirmation answers whether this delta succeeded; observation what the property is then. A preparation query does not freeze later changes and settlement does not fix b+δ. Observations have explicit read semantics and can be followed by new changes.
Lock-read/calculate/overwrite determines a result during protection. Quantum deltas defer dynamic values and bounds to settlement. This distinction does not prove a lock-free backend: short locks, atomic conditions or coordination may still protect delta application and commit. Evidence establishes actual capability.
Sources: quantum bounds, transaction/storage, environments. Unresolved contracts are outside the manuscript in known issues.
Appendix E — Language and Engineering Reference¶
This appendix gives language conventions and experiment commands used by the draft. It aids reading; module source and runtime instructions remain authoritative. Run commands at repository root.
Concept Reference¶
| Concept | Responsibility |
|---|---|
| Entity | Natural entity owned by this domain |
| Reference | External entity, role or contract with explicit source |
| Role | Participating identity and role facts |
| Contract | Parties, terms and scenario results |
| take ... as | Single, joint or further role playing |
| play ... by | APP binding of a role to a player, possibly in another domain |
| short | Short names of a participant type: short x, xs (scalar, array) |
| find... by | Read a participant by key from other participants or a constant |
| mapsame | Explicit compatible same-name mapping; not default |
| takeall | Import player properties and generate mappings |
| business | Explain true business use of a suspicious technical ID and remove habitual-ID warning |
| query | Complete participants and support identity confirmation |
| check | Judge conditions without mutation |
| calculate | Prepare candidates and compose pure calculations |
| update | Apply changes through application/resources |
| quantum update | Define deltas and settlement relationships |
| Scenario | Organize complete activities |
| transaction ... fail | Business handling after execution and technical recovery |
| ResultInfo | Built-in scenario result/recovery participant, not an atomic parameter |
Entries list participant types or collections, once per role; bodies use short names that default to the lower-camel type name. Argument-free calls require unique type binding. There are no business return values. Scalar input identity stays stable, while mutable collection contents can change.
A failing check ends its enclosing bare block and rolls back the transaction when that block is the transaction block; a nested serial { } exits only itself. checkXXX,breakTransaction rolls back from any depth. Participant execution defines conditions and provisional control flow; the text does not assume universal support across transaction modes.
Example Backend Coverage¶
These are concrete baseline capabilities, not new conceptual definitions:
| Feature | Conditions |
|---|---|
| LOCAL | Same JVM and verified common database/schema/connections |
| REQUIRED | Reuse execution and commit context |
| REQUIRES_NEW | Supported homogeneous outer/local combinations; independent results handled separately |
| NESTED | Rejected by example backend |
| Bare check in parallel | Limited stop scope; use supported serial or guard forms |
| Enhanced for | Collection-order iteration, not automatic parallel calculation |
| calculate calls | Pure calculation composition; no cycles or technical effects |
| fail | Outer transactions in serial scenarios; fail(targetContract) for multiple contracts; nested/parallel fail rejected |
| Remote transaction/quantum protocol | Actual coordination and recovery evidence required; otherwise rejected |
Execution, storage and environment specifications define exact checks. Principles establish when combinations make sense; backends still need actual runtime support.
Implementation References for Service Categories¶
| Characteristic | Source or Example |
|---|---|
| Independent concurrent queries followed by fact use | Ordering, payment |
| In-place completion and identity | Query binding, execution |
| Built-in query/update; visible scenario rules | Implicit CRUD |
| Atomic call restrictions and calculation cycles | SppDomain (maintainer reference: ../../lang/src/main/java/com/servpp/lang/models/SppDomain.java): validateBusinessCalculations, validateCalculationCycles |
| Calculation-only calls, no check mutation/require | BusinessCalculationValidator (maintainer reference: ../../lang/src/main/java/com/servpp/lang/models/app/expr/BusinessCalculationValidator.java) |
| Quotation reuses line calculation | Pricing: quoteOrder and priceLine |
| Lexical checks, guards and reversal | Execution, atomics |
| Record rejection after recovery | Reservation, system results |
| Local calculation/validation generation | SppService (maintainer reference: ../../lang/src/main/java/com/servpp/lang/models/SppService.java): isLocalService; generator (maintainer reference: ../../generator/src/main/java/com/servpp/generator/openapi/MustacheClassWriter.java); APP |
Concurrency and local sequencing follow duties/dependencies, not automatically service categories. Local execution still accepts concurrent requests. Part I explains common arrangements, Part II costs and dependencies.
Build and Test¶
mvn -pl :petstore-demo -am package -DskipTests -Dspp.environment=develop
mvn -pl :petstore-demo -am test-compile -DskipTests -Dspp.environment=testing
mvn -pl :petstore-demo -am test -Dtest=PetstoreScenarioTest -Dsurefire.failIfNoSpecifiedTests=false
The first two build/compile but skip running tests. The third runs selected tests. package success alone does not prove regression. Latest Petstore acceptance records provide joint-regression commands.
Local Web Application¶
SPP_PETSTORE_JDBC_URL='jdbc:h2:file:/tmp/spp-book-develop' \
./demos/petstore/run-demo.sh web
Default port is 8086. Existing matching builds can use SPP_DEMO_SKIP_BUILD=1. Fixed paths retain previous data; choose paths by experimental round.
Three-Process testing¶
Build testing artifacts first. Set identical caller credentials and experiment resources in all three terminals, replacing the token placeholder:
export SPP_ENVIRONMENT=testing
export SPP_DEMO_SKIP_BUILD=1
export SPP_DOMAIN_RPC_TOKEN='replace-with-session-token'
export SPP_TESTING_CUSTOMER_JDBC_URL='jdbc:h2:file:/tmp/spp-book-testing-customer'
export SPP_TESTING_PRODUCT_JDBC_URL='jdbc:h2:file:/tmp/spp-book-testing-product'
export SPP_TESTING_SHOP_JDBC_URL='jdbc:h2:file:/tmp/spp-book-testing-shop'
export SPP_TESTING_LEDGER_JDBC_URL='jdbc:h2:file:/tmp/spp-book-testing-ledger'
Start providers, confirm readiness, then start shop:
# Terminal 1, default port 8087
./demos/petstore/run-demo.sh web customerService
# Terminal 2, default port 8088
./demos/petstore/run-demo.sh web productService
# Terminal 3, default port 8086
./demos/petstore/run-demo.sh web petstore
Cross-host deployment needs endpoints and quantum resources ensuring one actual system. Identical copied H2 file-path strings do not create a shared remote database.
Numbers and Output¶
SPP numeric specifications give defaults; PHY replacement and field overrides select representation, with field overrides taking precedence. Capacity is not rounding. Generated output stays in target; source in src/main/spp.
See runtime instructions, launcher, execution, numbers and environments.
Appendix F — Sources and Verification Evidence¶
This appendix provides concepts, source, execution and performance references. Concepts form one system; remaining cross-document issues are separately tracked in editorial records, outside the narrative.
F1 Theory and Methods¶
| Reference | Coverage |
|---|---|
S++ Concepts and Applications (maintainer reference: ../../../spp/docs/cn/concept.md) |
Service model, decomposition, quantum services, polymorphism, separation and performance |
S++ Modeling (maintainer reference: ../../../spp/docs/cn/modeling.md) |
Shop participants, identity, agreements and storage |
Scenario Composition Design (maintainer reference: ../../scenario/docs/Composit.docx) |
Categories, dependency groups and scheduling |
Application Framework Design (maintainer reference: ../../lang/doc/ApplicationFrame.docx) |
Runtime, technical handling and transactions |
The neighboring spp repository must be obtained separately. Relative source references require that checkout beside this repository.
F2 Language and Engineering Specifications¶
| Topic | Reference |
|---|---|
| Meaning and participation | Business model boundaries |
| Query, identity and control | Participant execution |
| Calculation rules | Atomic calculation |
| Representation and rounding | Numeric semantics |
| Quantum bounds | Call bounds |
| Ownership, commit and recovery | Transaction/storage |
| Environments and resources | Deployment/physical configuration |
Petstore counts retain the separate baseline in F7. Bank source and newly added capabilities are checked against main revision 0fafa21d. Specifications state goals and constraints, source expresses implementation, and runtime records evidence specific paths. No single layer replaces the others.
F3 Petstore Functional Verification¶
October 13, 2026 technical-service verification records 1,123 passing tests: language 362, runtime 617, generator 105, Petstore 39, with zero failures, errors or skips. Coverage includes matching, compilation, phases, access rejection, observer isolation, concurrency and replay. Remote proxies use controlled transport, without real cross-JVM acceptance. The Petstore example shows all-service tracing. Capability comes from main revision 65c766fc; this book cites existing records.
October 13 failure handling records 1,104 develop tests: language 356, runtime 607, generator 105, Petstore 36, all passing without skips. Reservation evidence covers insufficient stock, ordinary-save fault and replay. Framework tests separately establish real JDBC settled inverse before fail. Petstore used LOCAL, not real distributed TCC/external quantum acceptance. These are cited records, not tests rerun for the manuscript.
October 12 final regression records 1,080 passing tests: lang 340, appframe 581, generator 105, appframe-seata 20, Petstore 34; no failures, errors or skips.
That record also covers complete Chrome flows in develop, three-JVM testing with four isolated file databases, and shop restart. After shutdown, checks compare fund totals, per-goods stock/supply and per-transaction delta sums.
Temporary log paths identify original evidence; independent environments must rerun commands to obtain their own results. Known limitations cover opening retries and split zero recovery, detailed in recovery design. Functional regression is not Appendix C's serial/parallel benchmark.
F4 Verification of the Bank Deposit Case¶
The bank deposit case has completed its migration to current syntax and runtime protocols. Its production source uses only SPP, APP and PHY, with no handwritten production Java. SPP does not use try/catch/throw; generated Java and runtime internals can still use exception handling for technical failures. Historical source remains for rule comparison, not as current executable examples.
This section checks the case against main revision 0fafa21d and cites existing repository evidence. The manuscript update did not rerun bank tests. The latest verification record preserves commands, results and scope by batch:
| Verification Batch | Result | Scope |
|---|---|---|
| October 13, 2026 clean develop joint regression | 1,226 tests; zero failures, errors or skips | Language 366, runtime 628, generator 107, bank case 86, Petstore 39; internal recipient accounts, historical snapshots and included fault/concurrency tests |
| Subsequent testing bank regression | 86 tests; zero failures or errors, two skips | Separate quantum and ordinary H2 data sources in one JVM; two LOCAL-only commit-fault tests skipped |
| Independent reversal-preview tests | Two passing tests in each of develop and testing | No preview writes; formal reversal preserves later deposits; missing originals are rejected without side effects |
| Chinese workbench verification | Backend tests and browser flows pass in both environments | Exact decimal display, negative-amount rejection, preview, reversal, receipt lookup and mobile layout; see workbench acceptance |
Split-storage testing does not constitute complete acceptance of real network distribution, XA, Seata AT or TCC. Independent JVM restart and forced exit after confirmed settlement cover their specified persistence paths, not automatic resolution of interrupted or unknown commits. Later targeted tests must not be added together and represented as one unexecuted joint regression.
The completion audit identifies implemented scenarios, storage, transactions and technical capabilities. The 86-entry historical migration inventory lists evidence, differences and unmigrated parts entry by entry. Those 86 historical entries and the 86 JUnit tests above are different measures; equal numbers do not establish one-to-one equivalence.
Known issues retain boundaries for committed ordinary Saga recovery, persisted pending authorization and cross-process resumption, automatic confirmation of unknown settlement, and durable auditing of every invocation. A split-storage failure can restore quantum funds while leaving ordinary committed facts. The system explicitly reports RECOVERY_REQUIRED and handled=false, not complete rollback.
Source mapping gives current directories and original rule locations. Source derivation, mathematical expectations, demonstration inputs, generated execution comparisons, original COBOL execution and bank-confirmed results represent different evidence levels. Case success does not establish every bank policy or original-system output equivalence.
F5 QService References¶
The neighboring qservice repository's SPP boundary contract (maintainer reference: ../../../qservice/docs/spp-qservice-boundary-contract.md) and quantum design (maintainer reference: ../../../qservice/docs/qservice-early-design.md) describe commands, durable identities, lookup and recovery.
It has separate artifacts and baselines. Verify the backend protocol actually integrated; independent-project tests do not extend to arbitrary deployments.
F6 Using Evidence¶
Parsing establishes accepted expression; compilation checks artifacts; runtime exercises paths; fault/restart tests cover specified recovery. Performance needs workload/resources.
For each claim, identify participants, behavior and configuration, then input, expectation, result and fault scope. These connections make conceptual arguments reviewable as engineering practice.
F7 Petstore Code-Size Statistics¶
The figures in this section describe their recorded source baseline. Subsequent English/USD presentation and expanded source formatting change physical line counts; they do not retroactively change these measurements.
On October 13, 2026, source at book branch 5b9b182c was measured; that manuscript change did not alter demo source. develop generation began with no existing generated Java directory, excluding stale files. Run at root:
mvn -pl :petstore-demo -am package -DskipTests -Dspp.environment=develop
Inputs are .spp, .enum, .app and .phy under demos/petstore/src/main/spp/; output is .java under demos/petstore/target/generated-sources/openapi/src/main/java/. Excluded are tests, pages, resources, build scripts, generator and shared runtime dependencies. Java includes both S++ and OpenAPI generation. Reproduce in a clean directory and recount after source/tool changes.
| Category | Files | Physical Lines Including Blanks/Comments | Code Lines |
|---|---|---|---|
| SPP | 63 | 1,104 | 999 |
| Enums | 2 | 25 | 18 |
| APP | 4 | 126 | 117 |
| PHY | 4 | 222 | 214 |
| Inputs total | 73 | 1,477 | 1,348 |
| Generated Java | 962 | 131,107 | 100,151 |
Models account for 64,431 code lines, services 21,031, interfaces/handlers 14,535, and mapping/configuration 154. Model and request/response expansion is substantial; every line is not independently designed business logic.
This script removes blank, line-comment and block-comment lines while preserving comment symbols in strings and brace-only lines. It fits this source, not every language construct:
from pathlib import Path
import re
pattern = re.compile(
r'"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'|//[^\n]*|/\*[\s\S]*?\*/'
)
def code_lines(source):
def remove_comment(match):
token = match.group()
if token.startswith(("//", "/*")):
return "\n" * token.count("\n")
return token
source = pattern.sub(remove_comment, source)
return sum(bool(line.strip()) for line in source.splitlines())
source_root = Path("demos/petstore/src/main/spp")
java_root = Path("demos/petstore/target/generated-sources/openapi/src/main/java")
for suffix in (".spp", ".enum", ".app", ".phy", ".java"):
root = java_root if suffix == ".java" else source_root
files = sorted(root.rglob("*" + suffix))
sources = [path.read_text(encoding="utf-8") for path in files]
print(suffix, len(files),
sum(len(source.splitlines()) for source in sources),
sum(code_lines(source) for source in sources))
SPP can place multiple declarations/calls on one line, while Java formatting, accessors and request/response types expand lines. This is version-specific scale, not a universal expressiveness, productivity or speed ratio. Exact handwritten Java comparison requires an independent implementation with equivalent business, capability and acceptance. The following is an estimate by responsibility.
Estimate with Common Java Frameworks¶
Assume Spring Boot + MyBatis + Lombok, existing reusable components, no separate remote interface for every internal operation and no manually expanded accessors. Lombok provides model boilerplate, MyBatis SQL mapping and Spring declarative transactions. Their source is dependency, not project-maintained code. See Lombok Data, MyBatis Mapper and Spring transactions. Documentation establishes capabilities; estimates are the book's engineering judgment, not vendor benchmarks.
| Maintained Content | Estimated Lines | Basis |
|---|---|---|
| Models, DTOs and enums | 1,000–2,000 | Four domains, reused models and Lombok |
| Entries, conversion and mapping | 1,000–2,000 | 34 scenario boundaries |
| Orchestration, calculation and eligibility | 3,000–5,000 | Approximately 90–150 per scenario including shared rules |
| Persistence, SQL, mappings and schema | 2,000–4,000 | Facts, snapshots, version conditions and associations |
| Conservation, idempotency and recovery integration | 2,000–5,000 | Bilateral deltas, bounds, original confirmation and phase recovery |
| Domain calls, environments and technical errors | 1,000–2,000 | Local/remote adaptation, resources and environment selection |
| Total | 10,000–20,000 | Java, SQL/Mapper and necessary configuration |
Responsibilities are allocated to avoid duplication: business rejection belongs to scenario/checks; timeout confirmation to recovery/technical handling. Proposed general cache pruning and full security/governance not yet implemented in the case are excluded, as is developing the shared framework itself.
A conventional monolith with local transactions, merged models, less domain adaptation and only local rollback may need 6,000–10,000 lines. That narrower scope omits domain deployment and its confirmation/recovery and is not an equivalent-capability baseline.
Mature accounting, idempotency and coordination middleware reduces handwritten code; building such general facilities can exceed these ranges. Formatting also matters. Ten to twenty thousand describes maintenance scale, not an exact productivity multiplier or development time.
F9 COBOL and S++ Code Size in the Bank Case¶
The count was made on October 14, 2026, using case source and reference documents at repository revision 92ed491b. Original COBOL and COPYBOOK files were read from the local bank-source directory, without modification or copying their contents into this book. That directory must be obtained separately. The figures are given in the tables of this appendix.
Source Scope and Deduplication¶
The “directly located for analysis” scope selects nine COBOL programs identified by program filename or specific line references in the source documentation. Located analysis means there is a source-tracing basis; it does not mean every branch of each program has been migrated.
| Program | Source Responsibility | Physical Lines | Lines Excluding Blanks and Comments |
|---|---|---|---|
| the legacy cash-deposit transaction | Front-office acceptance of a general deposit | 2,325 | 1,820 |
| the legacy deposit program | Deposit core, repayment allocation and reversal | 4,197 | 3,508 |
| the legacy query module | Account eligibility and acceptance checks | 2,654 | 1,867 |
| the legacy fee program | Fee entry point | 384 | 310 |
| the legacy fee module | Fee rules | 415 | 331 |
| the legacy date module | Calendar and day counting | 2,856 | 2,563 |
| the legacy product module A | Deposit and agreement accrual products | 483 | 315 |
| the legacy product module B | Overdraft accrual products | 237 | 154 |
| the legacy accounting-rule program | Accounting-rule integration and configuration-source analysis | 605 | 542 |
| Total | Nine programs | 14,156 | 11,410 |
Active COPY statements in those programs directly reference 135 COPYBOOKs. Nested references add another 26, yielding 161 distinct files. A shared COPYBOOK is counted once by actual file, even when several programs or repeated statements reference it. Invocation and expansion counts do not multiply it.
The broader “all related” scope selects 22 programs explicitly mentioned in the source documents and actually present in the original directory. It includes dispatch, query and configuration programs. It does not recursively expand every CALL dependency and is not the size of the entire banking system.
| Source Scope | COBOL Programs | Distinct COPYBOOKs | Program Physical Lines | COPYBOOK Physical Lines | Total Physical Lines | Total Lines Excluding Blanks and Comments |
|---|---|---|---|---|---|---|
| Directly located for analysis | 9 | 161 | 14,156 | 23,488 | 37,644 | 22,589 |
| All related programs mentioned in documentation | 22 | 192 | 20,626 | 24,961 | 45,587 | 28,358 |
Current S++ Source¶
Only production SPP, enums, APP and PHY are counted. Historical material, Java tests, test inputs, web pages, build scripts, generated Java, and shared compilers and runtime frameworks are excluded.
| Source Category | Files | Physical Lines, Including Blanks and Comments | Lines Excluding Blanks and Comments |
|---|---|---|---|
| SPP | 34 | 1,037 | 973 |
| Business enums | 1 | 6 | 6 |
| APP | 2 | 48 | 48 |
| PHY | 2 | 38 | 38 |
| Total | 39 | 1,129 | 1,065 |
SPP and enums total 979 nonblank, noncomment lines describing the business models, services, scenarios and finite value sets maintained in this case; APP and PHY add 86. Several S++ statements currently share a physical line. Line ratios therefore do not directly measure algorithmic complexity, work or productivity.
Counting and Reproduction¶
Physical lines follow each file's original line breaks. COBOL nonblank, noncomment counts use fixed-format processing: exclude lines whose seventh column is * or /, take content from columns 8–72, remove inline comments following *>, and count remaining nonempty lines. Sequence columns and right-hand identification areas are not code. Data definitions, COPY directives, procedures and control declarations still count; these are not business-statement counts.
COPYBOOKs follow the same rule. SPP, enums, APP and PHY remove // and /* … */ comments while preserving comment symbols in strings, then count remaining nonempty physical lines. COPYBOOKs are not expanded and repeatedly counted inside every program.
Limits of the Comparison¶
Source and implementation sizes help explain how concentrated the expression is; they do not prove equivalent conversion of every source line. Entire source programs include other transaction modes, shared configuration and unmigrated branches. The S++ case covers business paths explicitly implemented and verified.
Role and service models concentrate their rules, participating relationships and execution boundaries. Tools supply repetitive implementation, and APP/PHY connect storage and runtime facilities. The case still depends on shared frameworks, uses demonstration configuration for accounts and external facts, and retains authorization-resumption and ordinary Saga recovery limits described in F4. Dividing all source lines by case lines does not establish an unconditional compression factor or full replacement.