=============================== GP optimizer boundary contracts =============================== **Status:** implemented. The adapters are in ``gpr/ml/RgminObjective.h`` and ``gpr/ml/RgminObjective.cpp``. The meson test ``test_rgmin_objective`` (``tests/gpr/ml/RgminObjectiveTest.cpp``) checks the retained samples, the work counts and the failure latch. This page states the ownership, dependency and failure guarantees of the rgmin objective adapters. It does not claim a GP convergence or runtime effect. Responsibilities and dependencies --------------------------------- ``RgminObjective.h/.cpp`` owns the common C callback boundary used by ``RgminOpt``, ``RgminScg``, standalone ``RgminLbfgs``, and INLA. Neither MAP optimizer depends on the other optimizer's implementation. The shared component depends on the objective's energy/gradient types, MAP configuration, Eigen and the rgmin C interface. Its implementation includes its own header first. The callbacks translate objective evaluations into rgmin values and status codes. Solver selection, iteration policy and publication of fitted parameters belong to the optimizer adapters. GP covariance, posterior conditioning and molecular acceptance belong to their respective GP and saddle-search components. Ownership --------- The model, observation arrays and member-function target in ``RgminNlmlCtx`` are borrowed for a synchronous optimizer call. They must outlive that call. The context and its exception state belong to one fit; they are not shared across concurrent fits. ``RgminTensorHandle`` owns only the DLPack descriptor allocated by ``rgmin_tensor_borrow_cpu_f64``. Its deleter calls ``rgmin_tensor_free`` on every scope exit, including exception unwinding. The coordinate vector owns the underlying numerical storage and outlives the descriptor. Ownership adds no copy of that storage. Retained objective samples -------------------------- ``RgminOpt`` keeps two samples within each fit: the latest trial and the accepted point that starts a step. Each sample owns its parameter vector, raw energy and raw gradient. Callbacks apply MAP penalties and active parameter masks to copies, so the stored gradients remain raw. A lookup requires equal dimensions, finite coordinates and matching double representations. The signs of zero and adjacent floating-point values are distinct keys. A sample becomes eligible for retention only when its energy and gradient are finite and its gradient has the expected dimension. Step boundaries promote an existing sample at the published parameters without calling the objective. The first successful callback can retain an opening point clipped by the solver's box. A request for the retained point leaves the latest trial available. Two samples suffice for ``A, B, A, B`` reuse, but an evicted bracket point still requires evaluation. The observation arrays, objective and MAP configuration stay fixed for the fit. A new fit creates a new context, and a persistent solver rebases its point state before requesting evaluations. Sample storage grows linearly with the parameter count. Posterior matrices stay with the model. ``RgminScg`` uses the shared context with one sample. Its exact curvature callback reads the model state assembled by the objective. The anneal adapter also uses one sample. Model state and work counts --------------------------- Retaining energy and gradient values does not retain the model's assembled posterior. ``RgminOpt`` tracks the last parameters physically evaluated by the holder. Before publishing final parameters, it restores the holder through an objective call if those parameters differ. Restoration counts as physical work and can fail through the same callback failure mechanism. ``PhaseTimers::objective_count`` measures executed objective work. The fit's physical count remains available through ``lastFitEvaluationsForTesting()``. One holder call can contribute two units when an objective delegates to an instrumented geometry evaluator. Each sample records its observed counter increment, so accounting preserves that weight. ``RgminOpt::logicalObjectiveWork()`` follows a separate request cache with one entry. Its key uses the original numerical equality, treating positive and negative zero as equal. A domain rejection replaces this key without invoking the holder. Repeated value and gradient requests at that key share one logical request. Final holder restoration adds physical work without adding a logical request. The GP stores the automatic anneal budget basis separately in ``last_fit_budget_evaluations_``. It replaces the local adapter's physical contribution with its logical contribution. The same replacement applies when ``RgminOpt`` retries an SCG fit. Work from the anneal stage and the SCG attempt keeps its measured contribution. Other local optimizer adapters use physical work for both counts. Active and chart objectives also cache one sample inside the holder. Their private metadata supplies the cached key and the work of an uncached call. The accounting context copies that key and tracks a separate simulated holder key as logical requests reach the holder. Domain rejections leave this key intact; unsuccessful evaluations invalidate it. An opening cache hit can cost zero physical units, while recomputing that sample costs one unit. Tracking both keys preserves that distinction even when the physical holder stays at another trial. Numerical policy ---------------- For an unchanged deterministic objective, reuse returns the evaluated value and gradient at the same represented point. The solver still chooses each trial and makes each acceptance decision. Box handling, rebase, the Wolfe trial limit, acceptance at equal rounded energies, and the retry policy remain unchanged. The cache saves evaluations only when a request revisits one of its two stored points. Runtime effects require measurements of GP fits and molecular searches. Failure guarantees ------------------ The objective callbacks in these adapters are ``noexcept``. An exception is captured inside C++, translated to ``RGMIN_INTERNAL_ERROR``, and retained for a diagnostic. The first exception wins and invalidates both samples. Subsequent callbacks in that fit return failure without calling the objective. Invalid domain trials continue to use the optimizer's nonfinite-value rejection mechanism. A callback failure marks optimization unsuccessful and prevents the solver's trial vector from being published. Feasibility normalization of the starting parameters is part of optimizer preparation. This is not a rollback guarantee for arbitrary model mutations made by an objective: callers must restore or recondition their posterior before using it. Allocation and solver-construction exceptions can propagate within C++, while owned tensor descriptors still release their resources. The callback containment tests exercise L-BFGS and SCG through the linked C interface, including exact curvature and nonstandard exceptions. They require process survival, failure status, retained starting parameters and diagnostics. The direct gradient callback test verifies that failure cannot expose a numerical gradient as a successful result. The existing optimizer trajectory, MAP-domain and active-parameter tests check the numerical behavior of both adapters. Design basis ------------ Martin Reddy, *API Design for C++*, second edition (2024), pp. 60-63, distinguishes resource ownership from access and applies scope-based resource management beyond memory. Pages 173-177 require a consistent error-reporting convention and an explicit exception-safety guarantee. Pages 65-68 discuss reducing dependencies between API components. John Lakos, *Large-Scale C++: Process and Architecture* (2020), sections 1.6 and 2.6, connects a component's interface to its physical implementation and requires headers to compile independently of include order. These rules motivate the shared component and its header-first implementation. They do not establish GP convergence or numerical performance; those require the molecular certificates and benchmarks.