transaction
¶
Retryable, all-or-nothing blocks of correlated random draws for StochasBase. Reach this module through StochasBase.transaction() rather than constructing a Transaction directly.
Transaction
dataclass
¶
Transaction(
base: StochasBase,
retry_on: type[Exception] | tuple[type[Exception], ...],
max_retries: int,
)
Iterable of retry attempts returned by StochasBase.transaction().
Each iteration yields a TransactionAttempt to use as with attempt:. Construct via Transaction.begin(), which snapshots base.dists, base.design, and base.named. A failed attempt (retryable or not) rolls back to that snapshot before the exception is either suppressed (to retry) or allowed to propagate, so a transaction only ever commits the registrations made by the attempt that succeeds.
Iteration ends as soon as an attempt finishes without raising. If max_retries attempts are rejected without one succeeding, the next iteration raises RuntimeError, chained to the last rejected exception.
base
class-attribute
instance-attribute
¶
base: StochasBase = field(repr=False)
The model whose dists, design, and named registries are snapshotted and rolled back.
retry_on
instance-attribute
¶
Exception type(s) that mean "bad draw, retry" rather than a real error. Any other exception propagates after rollback.
max_retries
instance-attribute
¶
max_retries: int
Maximum number of attempts before giving up with RuntimeError.
begin
classmethod
¶
begin(
base: StochasBase,
retry_on: type[Exception],
max_retries: int = 10,
) -> Self
begin(
base: StochasBase,
retry_on: type[Exception] | tuple[type[Exception], ...],
max_retries: int = 10,
) -> Self
Starts a transaction, snapshotting base.dists, base.design, and base.named for rollback.
The snapshots are shallow copies of each registry's underlying dict, so a rollback restores which names are registered, not the internal state of the registered objects. A distribution's RNG stream therefore keeps advancing across attempts, which is what lets a retry draw a new value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base
|
StochasBase
|
Model to run the transaction against. |
required |
retry_on
|
type[Exception] | tuple[type[Exception], ...]
|
Exception type(s) that mean "bad draw, retry" rather than a real error. |
required |
max_retries
|
int
|
Maximum number of attempts before raising |
10
|
Returns:
| Name | Type | Description |
|---|---|---|
Transaction |
Self
|
The new transaction, ready to iterate over. |
Source code in src/stochas/transaction.py
__next__
¶
__next__() -> TransactionAttempt
Returns the next attempt, or ends the loop once an attempt has succeeded.
Returns:
| Name | Type | Description |
|---|---|---|
TransactionAttempt |
TransactionAttempt
|
A fresh attempt to wrap in |
Raises:
| Type | Description |
|---|---|
StopIteration
|
If an attempt has already finished without raising. |
RuntimeError
|
If |
Source code in src/stochas/transaction.py
TransactionAttempt
dataclass
¶
TransactionAttempt(transaction: Transaction)
One attempt of a StochasBase.transaction(); use as with attempt:.
Sample through attempt.sample_dist and attempt.sample_design instead of the model's own methods, so retries draw new values and everything registered during a rejected attempt is rolled back. Anything else on the model is reachable through attempt.base. Raise one of the transaction's retry_on exceptions inside the with block to reject the attempt.
-
Code Reference
stochas
transaction
instance-attribute
¶
transaction: Transaction
The transaction this attempt belongs to.
base
property
¶
base: StochasBase
The StochasBase model this transaction is retrying against, which is the one .transaction() was called on. Use it for anything not wrapped on attempt, e.g. attempt.base.with_seed(...) or attempt.base.model_dump().
attempt_number
property
¶
attempt_number: int
1-indexed number of this attempt, which is the number of attempts rejected so far plus one.
sample_dist
¶
sample_dist(
dist: Distribution[T],
size: int = 1,
force: bool = False,
warn: bool = True,
convert_units: bool = True,
) -> NamedValue[NDArray[Any, T]]
Samples dist through attempt.base, reseeding it only the first time this transaction sees dist.name.
Reseeding on every attempt would reset the distribution's RNG to the same state each time and draw the exact same rejected value forever, so reset_rng is not exposed here. It is derived instead from whether this transaction has already seeded a distribution with this name. Reusing one instance across attempts and building a fresh instance with the same name on every attempt both work: the previous instance's seed, trial number, and live RNG stream are carried over to the new one (Distribution.adopt_prior_state), so both patterns draw identical values.
If the carried-over state leaves dist.is_nominal true, every remaining attempt for that name will return the same nominal value that was already rejected. A warning is logged once per name per transaction, not once per retry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dist
|
Distribution
|
Distribution to sample and register. |
required |
size
|
int
|
Number of samples to take. Defaults to 1. |
1
|
force
|
bool
|
Force the sampled value into the model's registries if the name already exists. Defaults to False. |
False
|
warn
|
bool
|
Whether or not to warn if there is a conflict while forcing. Defaults to True. |
True
|
convert_units
|
bool
|
Whether to convert the samples into the model's base unit when |
True
|
Returns:
| Type | Description |
|---|---|
NamedValue[NDArray[Any, T]]
|
NamedValue[NDArray]: NamedValue containing the random draw. |
Source code in src/stochas/transaction.py
sample_design
¶
sample_design(
dv: DesignFloat,
force: bool = False,
warn: bool = True,
convert_units: bool = True,
) -> float
sample_design(
dv: DesignInt,
force: bool = False,
warn: bool = True,
convert_units: bool = True,
) -> int
sample_design(
dv: DesignBool,
force: bool = False,
warn: bool = True,
convert_units: bool = True,
) -> bool
sample_design(
dv: DesignCategorical[T],
force: bool = False,
warn: bool = True,
convert_units: bool = True,
) -> T
sample_design(
dv: AnyDesignValue,
force: bool = False,
warn: bool = True,
convert_units: bool = True,
) -> Any
Samples dv through attempt.base.
Design variables are not RNG-backed (an optimizer, not stochas, picks their value), so there is no reseeding to manage. This is a plain passthrough to StochasBase.sample_design, kept on the attempt so a design variable stays fixed for the duration of one attempt and rolls back with everything else on a rejected one, exactly like sample_dist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dv
|
AnyDesignValue
|
Design variable to register and sample. |
required |
force
|
bool
|
Overwrite an existing entry in the model's |
False
|
warn
|
bool
|
Whether or not to log a message when using an override or forcing. Defaults to True. |
True
|
convert_units
|
bool
|
Whether to convert the value into the model's base unit when |
True
|
Returns:
| Type | Description |
|---|---|
Any
|
The design variable's value: |
Source code in src/stochas/transaction.py
__exit__
¶
__exit__(
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: object,
) -> bool
Ends the attempt: commits it on success, otherwise rolls back and decides whether to retry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exc_type
|
type[BaseException] | None
|
Type of the exception raised in the |
required |
exc_value
|
BaseException | None
|
The raised exception, or None if the block exited cleanly. |
required |
traceback
|
object
|
Traceback of the raised exception. Unused. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the exception is one of the transaction's |