Qyxo-Zhaenivoth-Guard / source /docs /DYNAMIC_API.md
PureOne's picture
Publish Qyxo-Zhaenivoth Guard v1.0.0 research release
25c6e75 verified
|
Raw History Blame Contribute Delete
11.4 kB

DynamicBank API — version 1.0.0

DynamicBank is a standard-library exact index for static value bounds and sparsely replaced mass intervals. CompactDynamicBank exposes the same model and operations as an explicit retained-memory alternative. Both return the same frozen result dataclasses. All accepted numeric inputs first convert to finite binary64. Guarantees refer to those converted numbers, not to an unrounded decimal, rational, measurement or model that the caller intended to represent.

from qzguard import DynamicBank

bank = DynamicBank([0, 100], [1, 1], [10, 10])
answer = bank.query(60, total_mass=19)
assert answer.guaranteed == (True,)

Construction

DynamicBank(
    value_lower,
    mass_lower,
    mass_upper,
    value_upper=None,
    *,
    base_numerator=0,
    base_denominator=0,
)

mass_lower and mass_upper are ordered length-M sequences. Require 0 <= L_i <= U_i. value_lower is either a length-M scalar sequence, giving one coordinate, or a rectangular M × P sequence with P > 0. value_upper=None fixes each value to its lower bound. Otherwise its shape must match and each lower value must not exceed its upper value. Values can be signed.

base_numerator is a scalar broadcast to all coordinates or a length-P sequence. It can be signed. base_denominator is a nonnegative scalar. Require D0 + sum(L) > 0 in exact arithmetic after conversion. This requirement also applies when every later query will supply a fixed total. The implementation excludes zero-baseline models whose denominator becomes positive only under that additional constraint.

Empty row sequences are accepted if D0 > 0. A scalar base numerator selects one coordinate; a nonempty base-numerator sequence determines the coordinate count for empty rows. Source arrays and nested lists are copied into owned scalar tuples or private mass lists. Later caller mutations cannot alter the bank.

Boolean inputs, strings used as numbers, nonfinite or nonreal numbers, invalid shapes, and mappings/sets used as sequences are rejected with ValueError. Ordered generators are supported and consumed during validation. Exceptions raised by user generators or conversion methods can propagate. No optional dependency is imported by the exact index.

Sparse replacement

bank.update(indices=[0], mass_lower=[2], mass_upper=[9])
assert bank.revision == 1

The three sequences must have the same length. An index must implement the integer-index protocol, be in 0 <= i < M, and appear only once. Booleans, integral-valued floats and duplicate indices are rejected. The patch replaces complete mass intervals; it is not an increment.

All indices, bounds and the proposed minimum denominator are validated before tree mutation. A validation failure leaves the masses, revision and maintained summaries unchanged. Empty patches return the bank without advancing the revision. Every successful nonempty patch advances the revision once, including replacement by identical values, and returns the same bank.

The atomic-validation guarantee does not cover allocation failures, arbitrary side effects inside user conversion methods, or concurrent access. Synchronize concurrent updates and queries externally. Static values and bases cannot be replaced through the public API; construct another bank when they change.

Exact threshold decision

answer = bank.query(60, relation="<=", total_mass=None)
# Equivalent name:
same = bank.guard(60, relation="<=")

Only the inclusive relations <= and >= are supported. A scalar threshold broadcasts; an ordered threshold vector must have P entries. total_mass=None uses independent mass intervals. Supplying a scalar W adds the exact constraint sum(w_i) = W after conversion and requires sum(L) <= W <= sum(U) exactly. A rounded user-supplied sum can therefore be rejected if it falls outside the exact feasible interval.

DynamicDecision is a frozen dataclass:

Member Meaning
guaranteed Tuple of P booleans; true exactly when every configuration satisfies that coordinate's relation
all_guaranteed Conjunction of guaranteed
counterexample_exists Tuple containing the negation of each guarantee
relation Requested inclusive relation
thresholds Owned tuple of exact Fraction representations of converted thresholds
support / margins Eager exact support fractions; maximum N - T D for <=, minimum for >=
decision_margins Negated support for <=, unmodified support for >=; nonnegative means guaranteed
revision Bank revision when the result was computed
total_mass Exact converted W as a Fraction, or None
model "independent_box" or "fixed_total_mass"
counters Per-call tree-work counters

False establishes existence of a violation in this declared continuous model; it does not establish that every configuration fails. Different coordinates can have different violating configurations. A fixed-total result does not contain a witness and does not offer a lazy conversion to an independent-box witness.

Sharp enclosure

bounds = bank.enclose(total_mass=19)
print(bounds.lower, bounds.upper)

DynamicBounds is frozen and owns lower and upper tuples of exact Fraction extrema, lower_float and upper_float tuples of tight outward binary64 endpoints, revision, total_mass, model, and counters. Outward endpoints can be infinite when a finite exact ratio exceeds the binary64 range. The rational endpoints remain finite. Each coordinate's extrema are sharp separately; they need not be simultaneously attainable with one common mass vector.

No endpoint method uses a numerical tolerance, sorting or a row scan. Independent-box roots use one Fenwick binary-lifting traversal per endpoint. Fixed-total endpoints select width capacity in value order with at most one partial row. All results remain unchanged after later patches.

Inspection and explicit snapshots

Property Behavior and cost
rows, coordinates, revision Integers, constant-time access
mass_exponent DynamicBank: fixed -1074; CompactDynamicBank: current historical global scale, nonincreasing and at most zero
value_exponent Static shared value scale exponent, at most zero
mass_lower, mass_upper New immutable float tuples; each call copies M entries
value_lower, value_upper Immutable owned row-by-coordinate float tuples
base_numerator Immutable coordinate tuple of floats
base_denominator Float scalar
cumulative_stats New frozen aggregate statistics snapshot
snapshot = bank.snapshot()
counterexamples = snapshot.guard(60, witness=True).witnesses

snapshot() explicitly spends O(M P) work and creates an immutable NormalizedBox for the current independent-box state. Its existing guard, enclose and witness APIs are available. It does not include a fixed-total constraint. Using these witnesses to explain a fixed-total decision would be invalid unless separately checking that the selected masses have the required total.

Public getters and frozen results do not expose mutable aliases. Private attributes are implementation details; deliberate modification of them is outside the contract.

Counters and complexity

DynamicCounters contains rows, coordinates, prefix_steps, binary_lifting_steps and sort_count. Prefix steps count visited Fenwick nodes; lifting steps count candidate-node tests. Query-time sort_count is zero. These counters omit binary-search comparisons, numeric conversion, integer bit costs and Fraction reduction. They are arithmetic instrumentation rather than wall-clock work estimates.

DynamicStats contains construction_sorts, patched_rows, update_nodes, queries, prefix_steps and binary_lifting_steps. queries counts both decision and enclosure calls. update_nodes counts actual updated moment-tree nodes, with shared lower/upper trees counted once. Obtaining a mass getter or snapshot is not a logarithmic indexed operation.

Preparation uses O(P M log M) comparisons and O(P M) state. Replacing K rows requires O(K P log M) integer operations. A decision or enclosure requires O(P log M) integer operations. Integer widths depend on binary64 exponents, moment products and sum sizes. The universal mass scale prevents whole-bank rescaling when a patch introduces a previously absent exponent, but can make ordinary integer summaries wider than an adaptive common scale. Finite testing supports these claims on supplied cases; the full asymptotic and correctness arguments are derivations in DYNAMIC_THEORY.md.

Choosing another path

Use PreparedBank for full-array mass replacements, especially when an eligible certified NumPy filter resolves signs cheaply. Use cached NormalizedBox endpoints when the weight box does not change. If the threshold and relation never change, exact per-row support deltas avoid the index's logarithmic work and extra memory; the benchmark includes that specialization. None of these recommendations is a universal performance theorem. See DYNAMIC_RESULTS.md for completed measurements and DYNAMIC_PROTOCOL.md for their boundary.

CompactDynamicBank

from qzguard import CompactDynamicBank

compact = CompactDynamicBank([0, 100], [1, 1], [10, 10])
assert compact.query(60, total_mass=19).all_guaranteed
compact.update([0], [2], [9])
assert compact.enclose().lower[0] == 10

This subclass uses the same constructor arguments, update, query/guard, enclose, getters, snapshots, exact models, validation rules and result types. It is selected explicitly by class name. It has no tuning parameter or automatic hardware choice.

The global mass scale starts at the finest nonzero initial mass/base-denominator exponent, capped at zero. It becomes finer when a patch introduces a smaller exponent, and never becomes coarser. Only O(P) global baselines/totals are rebased. Individual Fenwick nodes retain independent canonical exponents and are aligned only during reads or affected path updates. Joint removal of common powers of two lets a touched node recover a coarse representation after fine contributions disappear. Node exponents use a packed signed-short array; the positive-capacity bound places them between -1074 and 1087 on ordinary 64-bit Python.

Per-row integer mass arrays are not retained. A patch decodes the old raw floats only for the affected rows. A finer fixed-total query uses a temporary scale and leaves bank/node scales unchanged. The historical global exponent can remain -1074 after a tiny contribution is removed: compact node storage can recover while later query temporaries still become wide. The mechanism improves a particular storage cost, not every arithmetic bit cost.

Choose this representation only when its measured RAM/latency tradeoff fits the application. The diagnostic prototype and shipping implementation have separate source hashes and measured scopes. Approximate retained Python payload is not process RSS or a promise about allocator peaks. All asymptotic indexed-operation bounds and independent-box snapshot restrictions above still apply.