Core Concept Examples
These examples illustrate core Constraint Modeling Language (CML) concepts including type, relationships, constraints, and so on.
For an explanation of the constraint model structure in these examples, see Model Structure.
-
The
GeneratorSettype is related to theGeneralModeltype through a single relation.Parent Type Relation Name Child Type Cardinality Key Attribute Usage GeneratorSetGeneralModelsGeneralModelNot Applicable Constrained by requiredKWon the parent type. -
Parent Type (
GeneratorSet): Defined as aLineItemcomponent, theGeneratorSetholds configuration parameters such as the user’s power requirement (requiredKW), the specified voltage (Voltage), and compliance standards (standardsAndCompliance). It also includes calculated attributes likesurgeLoadKWandVoltage3. -
Child Type (
GeneralModel): Defined as aLineItemcomponent, theGeneralModelspecifies the technical attributes of the selected generator configuration, including its power output (powerKW) and noise rating (dB). -
Cardinality: The relation
GeneralModels : GeneralModelspecifies the quantity bounds for the component, indicating that exactly 11 instances of theGeneralModeltype must be included in this configuration.
Using Groupby annotation for types, this model creates a virtual VoltageGroup for every unique voltage (for example, “220/380”, “480/277”) found in the transaction.
groupBy=Voltage: The engine scans allGeneratorSetinstances and creates one virtualVoltageGroupfor each unique voltage value detected (for example, one group for all “220/380” units, another for all “277/480” units).sourceContextNode: This tells the virtual group to pull its “children” (the generators) from the specific path in the Salesforce context where quote line items are stored.- Bottom-Up Aggregation: Each
VoltageGroupindependently calculates itsgroupTotalSurgeKWbased strictly on the generators assigned to it by the groupBy logic. - Explicit Domains: Following best practices, the
surgeLoadKWandgroupTotalSurgeKWuse explicit domains (for example, [0.00..99999.99]) to prevent “NullPointer” or initialization errors during solving.
In this example, we apply sharingcount annotation to the Accessory type to allow the engine to reuse accessory instances across the configuration up to a specified limit.
- Parallel Solving: By setting
split = true, the engine can process the 99 possible accessories in parallel rather than sequentially, which is critical for large-scale generator configurations. - Resource Management: The
sharingCount = 5tells the solver that it doesn’t need to instantiate 99 uniqueAccessoryobjects; it can reuse the same object definition up to five times across different parts of the configuration graph. - Relationship Requirement: For
sharingCountto take effect, the Relation (the port) must also be annotated with@(sharing = true)to grant the engine permission to reuse instances.
- External Variable (
extern): These are declared outside of any type to hold values supplied by the environment (Salesforce). contextPathAnnotation: This maps the variable directly to a header-level field in the Sales Transaction.tagNameAnnotation: This links the variable to a specific Context Tag identifier within the Salesforce Context Definition.
Rules depending on these external variables (such as the ShippingCountry message) only re-evaluate when a Line Item change occurs (For example, updating requiredKW), not solely when the header field changes.
In this example, we define a generator configuration that validates the required power (requiredKW) against the duty rating and voltage, providing specific feedback when a mismatch occurs.
- Multiple Arguments: You can pass several variables after the string literal. The engine maps them to the placeholders in the exact order they appear.
- Format Specifiers
%sis used for string variables (for example,DutyRatingorVoltage).%dis used for integer variables (for example,requiredKW).- Placeholder Usage: Alternatively, you can use the {} syntax, which the constraint engine automatically replaces with the actual argument values during runtime evaluation.
- Comparison Logic with Dates: You can treat dates as comparable values in
constraintormessagerules to enforce scheduling logic (for example, ensuring a delivery date is not too early for a complex build).
This example demonstrates using aggregate functions (a virtual type for transaction-level aggregation) and mathematical functions within the GeneratorSet type for precise quantity calculation.
When implementing these functions in CML, follow these architectural best practices for robustness and performance.
- Explicit domains are required: All the derived attributes that result from a calculation or aggregation must have an explicit variable domain definition. This practice ensures accurate aggregation and helps prevent runtime errors.
- Separate calculation from declaration: Define the aggregation or calculation in a separate constraint rather than using an inline derived attribute declaration (for example,
int total = items.sumPrice;). This separation helps avoid issues where domains may not initialize correctly. - Correct Pattern: Define the relation aggregate (
totalQty = sum(quantity);) and then enforce the result via a constraint (constraint(totalItemCount == items.totalQty);).
This example shows how to enforce quantity rules that span both in-flight items on the current sales transaction and products the customer already owns (the installed base). The sourceContextNode="Asset" annotation on a relation pulls existing asset records into the model as read-only data, so that a require() rule can combine those asset quantities with in-transaction quantities to drive configuration logic.
sourceContextNode="SalesTransaction.SalesTransactionItem": Binds the relation to line items on the current quote or order. The engine reads and writes these instances during configuration.sourceContextNode="Asset": Binds the relation to asset records that represent products the customer already owns from prior transactions. These records exist outside the current transaction and are treated as read-only context data.closerelation=true: Required on asset-sourced relations to prevent the engine from attempting to add new instances to the installed base. Without this annotation, the engine may try to create asset records to satisfy cardinality or require rules.- Asset-based
require(): The rulerequire(heaters[Heater] + heaterAssets[Heater] > 10, generators[GeneratorSet] == 100)combines cardinality from two separate relations — one sourced from the transaction and one from the installed base — in a single logical expression. This lets the model enforce quantity thresholds that account for what the customer is buying now and what they already have. - Virtual grouping: The
groupby=FuelTypeannotation onGeneratorGroupensures that the asset-based constraint is evaluated independently per fuel type, so heaters and generator sets of different fuel types do not count toward each other’s totals.
These examples show how to use the installed base (existing customer assets) as a condition in a require() rule to automatically add products to the current quote. The positive asset check triggers an auto-add when the customer already owns a product. The negative asset check enforces a prerequisite product when the customer does not yet own it.
Positive asset check: if the customer already owns at least one GeneratorSet in their installed base, the engine automatically adds a MaintenanceKit to the current quote.
Negative asset check: if the customer does not yet own a GeneratorSet in their installed base but is adding more than one MaintenanceKit to the quote, the engine requires a GeneratorSet to also be added to the quote.
- Positive asset check (
generatorAssets[GeneratorSet] >= 1): Evaluates to true when the installed base contains at least one matching asset. Use this pattern to trigger upsell or companion-product logic for existing customers. - Negative asset check (
generatorAssets[GeneratorSet] < 1): Evaluates to true when the customer has no matching asset. Use this pattern to enforce a prerequisite product for net-new buyers. - Auto-add result: When the
require()condition is met, the engine adds the specified product to the relation automatically. Passing only the relation and type without a quantity (maintenanceKits[MaintenanceKit]) requires exactly one instance. Append== Nto require a specific quantity. closeRelation=trueis required on the asset relation to prevent the engine from attempting to write back to the installed base when evaluating the condition.
This example demonstrates how to model a multi-relation bundle that uses type inheritance to organize components and enforces compatibility rules using both require() and exclude() in the same model. GeneratorBundle holds three relations of different types and uses require() to enforce cross-relation dependencies based on quantity and presence. ExhaustBundle, a subtype of Accessory, uses exclude() to prevent incompatible child component combinations. The type hierarchy (Heater : Accessory, ExhaustFilter : Filter, GeneratorSet : PowerUnit) shows how subtypes participate in relations typed to their parent while carrying their own attributes and rules.
- Supertype as relation target: The
accessories : Accessoryrelation accepts any subtype instance, includingHeater,ExhaustBundle, orMaintenanceKit, because all three extendAccessory. The engine resolves which subtype is present at runtime. To target a specific subtype in a rule, reference it by name in the cardinality expression, for exampleaccessories[Heater]. - Cross-relation
require():require(controlSystems[ControlSystem] > 1, accessories[Heater])evaluates a condition on one relation (controlSystems) and enforces a requirement on a different relation (accessories). The condition and the result do not have to involve the same relation or type. - Supertype cardinality in
require():require(accessories[Accessory], generators[GeneratorSet])uses the supertypeAccessoryin the condition to check whether any accessory of any subtype is present. This is broader than checking for a specific subtype and fires regardless of whichAccessorysubtype the user selects. require()andexclude()in the same model:GeneratorBundleusesrequire()to mandate components;ExhaustBundleusesexclude()to block incompatible combinations. Both rules coexist in the same model without conflict because they apply to different types and relations.- Multi-level hierarchy:
ExhaustFilter : FilterandHeater : Accessoryeach inherit from their respective parent types. Thefilters : ExhaustFilterrelation inExhaustBundletargets the concrete subtype directly rather than the parentFilter, which constrains the relation to only that subtype’s instances.