Skip to main content

tensor4all_core/defaults/
contract_session.rs

1use std::sync::Arc;
2
3use tenferro::{Tensor as NativeTensor, TensorScalar};
4
5use crate::defaults::contract::PairwiseContractionOptions;
6use crate::defaults::idx_tensor::{IdxTensor, IdxTensorError, SessionDenseOperand};
7use crate::index_like::IndexLike;
8use crate::index_ops::prepare_contraction;
9
10/// Operation name the refusals and errors of this entry point carry.
11///
12/// Exceptions are the errors that carry a more specific origin: a deferred storage failure keeps
13/// [`IdxTensorError::Storage`], and a planning or publication failure keeps its own operation name.
14const OP: &str = "contract_pair_on_session";
15
16/// Contract two dense host tensors on a caller-held explicit concrete session.
17///
18/// The planning is the compatibility route's own (`operand_indices_for_contraction` plus
19/// `prepare_contraction`), so the result's indices - id, prime level and tags - are the ones
20/// [`contract_pair_with_operand_options`](crate::contract_pair_with_operand_options) produces. The
21/// execution is the caller's session ([`Session::contraction`](tensor4all_tensorbackend::explicit::Session::contraction),
22/// which also promotes mixed `f64`/`c64` operands on that session), and the result is published as dense
23/// host storage, so neither the process-global session nor an ambient eager runtime is entered and no
24/// graph is compiled.
25///
26/// Operands are adapted by representation rather than by materialization: dense host storage goes through
27/// the existing host/native bridge, and an untracked eager host value through its borrowed read
28/// representation, which the session consumes itself.
29///
30/// # Errors
31///
32/// Returns a typed [`IdxTensorError`] for an operand whose representation this slice does not serve - an
33/// AD-tracked value, a device-resident operand, or a diagonal, structured or compact payload - for a
34/// non-floating dtype, for an operand whose index list repeats an index, for incompatible
35/// index spaces (the planner's shape and dimension errors), when the session rejects the contraction, or
36/// when the result cannot be published. Every floating dtype (`f32`, `f64`, `c32`, `c64`) is served and the
37/// result keeps the session's dtype. A deferred storage error is returned as
38/// [`IdxTensorError::Storage`] with its original source.
39///
40/// # Examples
41///
42/// ```
43/// use tensor4all_core::index::{DefaultIndex as Index, DynId};
44/// use tensor4all_core::{contract_pair_on_session, IdxTensor, PairwiseContractionOptions};
45/// use tensor4all_tensorbackend::CpuExecutionContext;
46/// use tensor4all_tensorbackend::CpuBackend;
47///
48/// let context = CpuExecutionContext::from_backend(CpuBackend::with_threads(1)?);
49/// let i = Index::new_dyn(2);
50/// let j = Index::new_dyn(3);
51/// let k = Index::new_dyn(2);
52/// let lhs: IdxTensor =
53///     IdxTensor::from_dense(vec![i.clone(), k.clone()], vec![1.0_f64, 2.0, 3.0, 4.0])?;
54/// let rhs: IdxTensor = IdxTensor::from_dense(
55///     vec![k.clone(), j.clone()],
56///     vec![1.0_f64, 1.0, 1.0, 1.0, 1.0, 1.0],
57/// )?;
58///
59/// let product = context.with_concrete_session(|session| {
60///     contract_pair_on_session(session, &lhs, &rhs, PairwiseContractionOptions::new())
61/// })??;
62/// assert_eq!(product.indices().len(), 2);
63/// // Column-major over `[i, j]`: each `j` column sums the two `k` entries of that `i` row.
64/// assert_eq!(product.to_vec::<f64>()?, vec![4.0, 6.0, 4.0, 6.0, 4.0, 6.0]);
65/// # Ok::<(), Box<dyn std::error::Error>>(())
66/// ```
67pub fn contract_pair_on_session(
68    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
69    lhs: &IdxTensor,
70    rhs: &IdxTensor,
71    options: PairwiseContractionOptions,
72) -> Result<IdxTensor, IdxTensorError> {
73    // Malformed index lists are refused before planning: a repeated index makes the planner's
74    // result-length arithmetic underflow, and `replace_indices` can produce one through public API.
75    if !lhs.has_unique_indices() || !rhs.has_unique_indices() {
76        return Err(IdxTensorError::Operation {
77            operation: OP,
78            source: Arc::from(
79                anyhow::anyhow!(
80                    "every index of an operand must be distinct; a repeated index cannot be contracted"
81                )
82                .into_boxed_dyn_error(),
83            ),
84        });
85    }
86
87    // Planning: the compatibility route's own preparation, with the same conjugated operand index lists.
88    let lhs_indices = lhs.operand_indices_for_contraction(options.lhs_conj);
89    let rhs_indices = rhs.operand_indices_for_contraction(options.rhs_conj);
90    let lhs_dims = lhs.dims();
91    let rhs_dims = rhs.dims();
92    let spec = prepare_contraction(&lhs_indices, &lhs_dims, &rhs_indices, &rhs_dims)
93        .map_err(|error| IdxTensorError::operation(OP, anyhow::Error::new(error)))?;
94
95    // Adaptation: refuse every representation this slice does not serve before touching a session.
96    let lhs_operand = lhs.session_dense_operand(OP)?;
97    let rhs_operand = rhs.session_dense_operand(OP)?;
98
99    // An Eager (read) operand that is not conjugated goes straight into the contraction instead of
100    // through an identity einsum; storage operands are converted as before. A dtype mismatch needs
101    // promotion, which `Session::contraction` does on owned tensors, so a mismatched pair is
102    // materialized first.
103    let lhs_held = hold_operand(session, lhs_operand, options.lhs_conj)?;
104    let rhs_held = hold_operand(session, rhs_operand, options.rhs_conj)?;
105    let value = if lhs_held.dtype() == rhs_held.dtype() {
106        session.contraction_reads(
107            lhs_held.as_read(),
108            &spec.axes_a,
109            rhs_held.as_read(),
110            &spec.axes_b,
111        )
112    } else {
113        let lhs_value = owned_operand(session, lhs_held)?;
114        let rhs_value = owned_operand(session, rhs_held)?;
115        session.contraction(&lhs_value, &spec.axes_a, &rhs_value, &spec.axes_b)
116    }
117    .map_err(|error| session_error(OP, error))?;
118
119    IdxTensor::publish_dense_session_result_owned(spec.result_indices, value)
120}
121
122/// Compute the inner product of two dense host tensors on a caller-held explicit session.
123///
124/// This is the reduction companion of [`contract_pair_on_session`] and the operation #510's TT inner
125/// product runs hottest. It mirrors [`IdxTensor::inner_product`]: when both operands carry the same index
126/// set the right operand is aligned to the left one's order on the session and contracted with the left
127/// operand conjugated, and otherwise the two are contracted over their shared indices and the remaining
128/// axes are reduced on the session. The result is a plain scalar.
129///
130/// # Errors
131///
132/// Returns a typed [`IdxTensorError`] under exactly the conditions [`contract_pair_on_session`] refuses an
133/// operand - a tracked value, a device-resident operand, a diagonal, structured or compact payload, an
134/// unsupported dtype, a repeated index, an incompatible index space - when the session rejects the
135/// contraction or the reduction, or when the result cannot be published.
136///
137/// # Examples
138///
139/// ```
140/// use tensor4all_core::index::{DefaultIndex as Index, DynId};
141/// use tensor4all_core::{inner_product_on_session, IdxTensor};
142/// use tensor4all_tensorbackend::CpuExecutionContext;
143/// use tensor4all_tensorbackend::CpuBackend;
144///
145/// let context = CpuExecutionContext::from_backend(CpuBackend::with_threads(1)?);
146/// let i = Index::new_dyn(2);
147/// let j = Index::new_dyn(2);
148/// let lhs: IdxTensor =
149///     IdxTensor::from_dense(vec![i.clone(), j.clone()], vec![1.0_f64, 2.0, 3.0, 4.0])?;
150/// let rhs: IdxTensor =
151///     IdxTensor::from_dense(vec![i.clone(), j.clone()], vec![1.0_f64, 1.0, 1.0, 1.0])?;
152///
153/// let value = context.with_concrete_session(|session| {
154///     inner_product_on_session(session, &lhs, &rhs)
155/// })??;
156/// // conj(lhs) contracted with rhs over both indices: 1 + 2 + 3 + 4.
157/// assert_eq!(value.real(), 10.0);
158/// # Ok::<(), Box<dyn std::error::Error>>(())
159/// ```
160pub fn inner_product_on_session(
161    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
162    lhs: &IdxTensor,
163    rhs: &IdxTensor,
164) -> Result<crate::AnyScalar, IdxTensorError> {
165    // Malformed index lists are refused before planning, as in the contraction entry point.
166    if !lhs.has_unique_indices() || !rhs.has_unique_indices() {
167        return Err(IdxTensorError::Operation {
168            operation: OP,
169            source: Arc::from(
170                anyhow::anyhow!(
171                    "every index of an operand must be distinct; an inner product needs a valid index space"
172                )
173                .into_boxed_dyn_error(),
174            ),
175        });
176    }
177
178    let lhs_dims = lhs.dims();
179    let rhs_dims = rhs.dims();
180    // Both operands are adapted - and therefore refused - before either is materialized, so a refusal on
181    // the right cannot follow session work on the left.
182    let lhs_operand = lhs.session_dense_operand(OP)?;
183    let rhs_operand = rhs.session_dense_operand(OP)?;
184    // Planning is metadata too, so it happens before any numerical session work, and the route is decided
185    // once: an aligned pair needs only the permutation, an unaligned one needs the planner's axes.
186    let route = match alignment_permutation(lhs.indices(), rhs.indices()) {
187        Some(perm) => Route::Aligned(perm),
188        None => {
189            let lhs_indices = lhs.operand_indices_for_contraction(true);
190            let rhs_indices = rhs.operand_indices_for_contraction(false);
191            Route::Planned(Box::new(
192                prepare_contraction(&lhs_indices, &lhs_dims, &rhs_indices, &rhs_dims)
193                    .map_err(|error| IdxTensorError::operation(OP, anyhow::Error::new(error)))?,
194            ))
195        }
196    };
197
198    let mut lhs_value = materialize_on_session(OP, session, lhs_operand)?;
199    let mut rhs_value = materialize_on_session(OP, session, rhs_operand)?;
200    // The left operand is conjugated, exactly as the compatibility route conjugates it.
201    lhs_value = session
202        .conj(&lhs_value)
203        .map_err(|error| session_error(OP, error))?;
204
205    let product = match route {
206        // Same index set: align the right operand to the left one's order and contract every axis.
207        Route::Aligned(perm) => {
208            let axes: Vec<usize> = (0..rhs_dims.len()).collect();
209            if perm != axes {
210                rhs_value = session
211                    .permute(&rhs_value, &perm)
212                    .map_err(|error| session_error(OP, error))?;
213            }
214            session
215                .contraction(&lhs_value, &axes, &rhs_value, &axes)
216                .map_err(|error| session_error(OP, error))?
217        }
218        // Different index sets: contract the shared axes and reduce the rest.
219        Route::Planned(spec) => {
220            let contracted = session
221                .contraction(&lhs_value, &spec.axes_a, &rhs_value, &spec.axes_b)
222                .map_err(|error| session_error(OP, error))?;
223            session
224                .sum(&contracted)
225                .map_err(|error| session_error(OP, error))?
226        }
227    };
228
229    // The scalar is taken from the concrete value, not through the tensor's eager representation, which
230    // would adopt it into the process-global eager runtime.
231    let published = IdxTensor::publish_dense_session_result(Vec::new(), &product)?;
232    let scalar = match product.dtype() {
233        tenferro::DType::F64 => {
234            let value = first_scalar::<f64>(&product)?;
235            crate::AnyScalar::from_published(value, published)
236        }
237        tenferro::DType::F32 => {
238            let value = first_scalar::<f32>(&product)?;
239            crate::AnyScalar::from_published(value, published)
240        }
241        tenferro::DType::C32 => {
242            let value = first_scalar::<num_complex::Complex32>(&product)?;
243            crate::AnyScalar::from_published(value, published)
244        }
245        tenferro::DType::C64 => {
246            let value = first_scalar::<num_complex::Complex64>(&product)?;
247            crate::AnyScalar::from_published(value, published)
248        }
249        other => {
250            return Err(IdxTensorError::operation(
251                OP,
252                anyhow::anyhow!(
253                    "the explicit-session route returns floating-point scalars, not {other:?}"
254                ),
255            ));
256        }
257    };
258    Ok(scalar)
259}
260
261/// How the session should combine the two operands, decided before any session work.
262enum Route {
263    /// Both operands carry the same index set: permute the right one into the left one's order.
264    Aligned(Vec<usize>),
265    /// The index sets differ: contract the planned axes and reduce what is left.
266    ///
267    /// Boxed because the plan is much larger than the permutation and this enum is matched by value.
268    Planned(Box<crate::index_ops::ContractionSpec<crate::defaults::DynIndex>>),
269}
270
271/// Read the single element of a rank-zero result.
272fn first_scalar<T: TensorScalar>(value: &NativeTensor) -> Result<T, IdxTensorError> {
273    value
274        .as_slice::<T>()
275        .map_err(|error| IdxTensorError::operation(OP, anyhow::Error::new(error)))?
276        .first()
277        .copied()
278        .ok_or_else(|| {
279            IdxTensorError::operation(OP, anyhow::anyhow!("the reduced result is empty"))
280        })
281}
282
283/// The permutation that reorders `rhs`'s axes into `lhs`'s index order, when both carry the same set.
284///
285/// Returns `None` when an index of `lhs` does not appear in `rhs`, which is the case the caller handles by
286/// contracting the shared axes and reducing the rest.
287fn alignment_permutation(
288    lhs_indices: &[crate::defaults::DynIndex],
289    rhs_indices: &[crate::defaults::DynIndex],
290) -> Option<Vec<usize>> {
291    if lhs_indices.len() != rhs_indices.len() {
292        return None;
293    }
294    let mut perm = Vec::with_capacity(lhs_indices.len());
295    for index in lhs_indices {
296        let position = rhs_indices
297            .iter()
298            .position(|candidate| candidate == index)?;
299        perm.push(position);
300    }
301    Some(perm)
302}
303
304/// Operation name the sum entry point reports; it shares the seam's adaptation, not its identity.
305const SUM_OP: &str = "sum_on_session";
306
307/// Sum every element of a dense host tensor on a caller-held explicit session.
308///
309/// The reduction companion of the F1 seam for the dense host representations this slice serves, so an app
310/// can reduce a value inside a region it holds open. The result is a plain scalar, published from the
311/// concrete value rather than adopted into any eager runtime.
312///
313/// **A zero-length axis folds to the operation's identity**: the compatibility route accumulates from zero
314/// over the empty payload and answers `0`, and the session's reduction answers the same `0`, because the
315/// backend treats an empty reduction domain as the fold's unit rather than as invalid input (tenferro
316/// #2453). The two routes therefore agree over the whole served domain. The unit is the fold's own - `sum`
317/// answers `0`, `prod` would answer `1` - and a reduction with no finite unit (`max`/`min`) keeps the
318/// backend's typed refusal; this seam serves `sum` only, so it never exercises that boundary.
319///
320/// # Errors
321///
322/// Returns a typed [`IdxTensorError`] under the same conditions as [`contract_pair_on_session`] refuses an
323/// operand - a tracked value, a device-resident operand, a diagonal, structured or compact payload, a
324/// deferred storage error, an unsupported dtype - when the session rejects the reduction, or when the
325/// result cannot be published.
326///
327/// # Examples
328///
329/// ```
330/// use tensor4all_core::index::{DefaultIndex as Index, DynId};
331/// use tensor4all_core::{sum_on_session, IdxTensor};
332/// use tensor4all_tensorbackend::CpuExecutionContext;
333/// use tensor4all_tensorbackend::CpuBackend;
334///
335/// let context = CpuExecutionContext::from_backend(CpuBackend::with_threads(1)?);
336/// let i = Index::new_dyn(2);
337/// let k = Index::new_dyn(3);
338/// let tensor: IdxTensor =
339///     IdxTensor::from_dense(vec![i.clone(), k.clone()], vec![1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0])?;
340///
341/// let total = context.with_concrete_session(|session| sum_on_session(session, &tensor))??;
342/// assert_eq!(total.real(), 21.0);
343/// # Ok::<(), Box<dyn std::error::Error>>(())
344/// ```
345pub fn sum_on_session(
346    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
347    tensor: &IdxTensor,
348) -> Result<crate::AnyScalar, IdxTensorError> {
349    // The operand is adapted - and therefore refused - before any session work, as in the other slices. The
350    // result is published as a rank-zero `IdxTensor` whose compact storage keeps the reduced dtype, so a
351    // narrow `f32`/`c32` operand yields a narrow scalar rather than a widened one.
352    let operand = tensor.session_dense_operand(SUM_OP)?;
353    let value = materialize_on_session(SUM_OP, session, operand)?;
354    // `Session::sum` reduces every axis and duplicates an already rank-zero value, so one call covers both.
355    let reduced = session
356        .sum(&value)
357        .map_err(|error| session_error(SUM_OP, error))?;
358    let published = IdxTensor::publish_dense_session_result(Vec::new(), &reduced)?;
359    let scalar = match reduced.dtype() {
360        tenferro::DType::F64 => {
361            crate::AnyScalar::from_published(first_scalar::<f64>(&reduced)?, published)
362        }
363        tenferro::DType::F32 => {
364            crate::AnyScalar::from_published(first_scalar::<f32>(&reduced)?, published)
365        }
366        tenferro::DType::C32 => crate::AnyScalar::from_published(
367            first_scalar::<num_complex::Complex32>(&reduced)?,
368            published,
369        ),
370        tenferro::DType::C64 => crate::AnyScalar::from_published(
371            first_scalar::<num_complex::Complex64>(&reduced)?,
372            published,
373        ),
374        other => {
375            return Err(IdxTensorError::operation(
376                SUM_OP,
377                anyhow::anyhow!(
378                    "the explicit-session route reduces floating-point dtypes, not {other:?}"
379                ),
380            ));
381        }
382    };
383    Ok(scalar)
384}
385
386/// Permute a dense host tensor's axes on a caller-held explicit session.
387///
388/// The numerical counterpart of [`IdxTensor::permute`]: the compatibility entry point materializes an eager
389/// transpose, which is numerical work rather than metadata, so an app that holds a region open needs this
390/// route too. The permutation convention is the compatibility one - `perm[new_axis] = old_axis` - and the
391/// result is the same materialized dense host value with the same permuted index list. An identity
392/// permutation is returned unchanged, exactly as the compatibility route returns a clone, and performs no
393/// session work.
394///
395/// # Errors
396///
397/// Returns a typed [`IdxTensorError`] for a permutation whose length does not match the rank, an axis out of
398/// range or repeated - with the shared validator's messages - and, **for a nonidentity permutation**, under
399/// the same conditions as [`contract_pair_on_session`] refuses an operand: an AD-tracked value, a
400/// device-resident operand, a diagonal, structured or compact payload, a deferred storage error, or a
401/// non-floating dtype. It also returns one when the session rejects the permutation or the
402/// result cannot be published.
403///
404/// **An identity permutation never reaches those refusals**: like the compatibility route it returns the
405/// tensor unchanged, whatever its representation or dtype, because it is metadata only. Execution - and
406/// therefore the floating-dtype domain of this seam - applies to the nonidentity case.
407///
408/// # Examples
409///
410/// ```
411/// use tensor4all_core::index::{DefaultIndex as Index, DynId};
412/// use tensor4all_core::{permute_on_session, IdxTensor};
413/// use tensor4all_tensorbackend::CpuExecutionContext;
414/// use tensor4all_tensorbackend::CpuBackend;
415///
416/// let context = CpuExecutionContext::from_backend(CpuBackend::with_threads(1)?);
417/// let i = Index::new_dyn(2);
418/// let k = Index::new_dyn(3);
419/// let tensor: IdxTensor =
420///     IdxTensor::from_dense(vec![i.clone(), k.clone()], (1..=6).map(|v| v as f64).collect())?;
421///
422/// let transposed = context.with_concrete_session(|session| {
423///     permute_on_session(session, &tensor, &[1, 0])
424/// })??;
425/// assert_eq!(transposed.indices()[0], k);
426/// assert_eq!(transposed.indices()[1], i);
427/// // Column-major with the axes swapped: row major in the old order.
428/// assert_eq!(transposed.to_vec::<f64>()?, vec![1.0, 3.0, 5.0, 2.0, 4.0, 6.0]);
429/// # Ok::<(), Box<dyn std::error::Error>>(())
430/// ```
431pub fn permute_on_session(
432    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
433    tensor: &IdxTensor,
434    perm: &[usize],
435) -> Result<IdxTensor, IdxTensorError> {
436    const PERMUTE_OP: &str = "permute_on_session";
437    let rank = tensor.indices().len();
438    // The shared validator, before any session work: one definition of the contract for both entry points.
439    if let Err(message) = crate::defaults::idx_tensor::validate_permutation(rank, perm) {
440        return Err(IdxTensorError::operation(
441            PERMUTE_OP,
442            anyhow::anyhow!(message),
443        ));
444    }
445    if perm.iter().copied().eq(0..rank) {
446        // Identity is metadata only: no session work, exactly as the compatibility route clones.
447        return Ok(tensor.clone());
448    }
449
450    let operand = tensor.session_dense_operand(PERMUTE_OP)?;
451    let value = materialize_on_session(PERMUTE_OP, session, operand)?;
452    let input_ids: Vec<usize> = (0..rank).collect();
453    let read = tenferro::TensorRead::from_tensor(&value);
454    // Output labels in the requested order: new axis `i` takes old axis `perm[i]`.
455    let permuted = session
456        .einsum_reads(&[read], &[&input_ids], perm)
457        .map_err(|error| session_error(PERMUTE_OP, error))?;
458
459    let new_indices: Vec<crate::defaults::DynIndex> = perm
460        .iter()
461        .map(|&axis| tensor.indices()[axis].clone())
462        .collect();
463    IdxTensor::publish_dense_session_result_owned(new_indices, permuted)
464}
465
466/// Align a dense host tensor to a caller-supplied index order on a caller-held explicit session.
467///
468/// The numerical counterpart of [`IdxTensor::permute_indices`], which the app crates use to align operands
469/// before a contraction. The index list must be a permutation of the tensor's own indices by full index
470/// equality, exactly as the compatibility route requires; the permutation is derived with the same helper,
471/// so the two routes refuse the same inputs with the same messages. Execution is
472/// [`permute_on_session`]'s, so this route serves the same dense floating-dtype domain, and an identity
473/// permutation is metadata only - it returns the same storage under the supplied index list, for any
474/// representation, without touching the session.
475///
476/// # Errors
477///
478/// Returns a typed [`IdxTensorError`] when the index list is not a permutation of the tensor's indices (the
479/// compatibility helper's reason, reported under this entry point's operation name), when a supplied index
480/// carries a different dimension than the tensor's matching index (this route's own message), under the same
481/// conditions as a nonidentity [`permute_on_session`] refuses an operand - whose errors keep that route's
482/// operation name, because the execution is delegated - and when the session rejects the permutation or the
483/// result cannot be published. A delegated storage error keeps its original source rather than being
484/// re-labelled.
485///
486/// # Examples
487///
488/// ```
489/// use tensor4all_core::index::{DefaultIndex as Index, DynId};
490/// use tensor4all_core::{permute_indices_on_session, IdxTensor};
491/// use tensor4all_tensorbackend::CpuExecutionContext;
492/// use tensor4all_tensorbackend::CpuBackend;
493///
494/// let context = CpuExecutionContext::from_backend(CpuBackend::with_threads(1)?);
495/// let i = Index::new_dyn(2);
496/// let k = Index::new_dyn(3);
497/// let tensor: IdxTensor =
498///     IdxTensor::from_dense(vec![i.clone(), k.clone()], (1..=6).map(|v| v as f64).collect())?;
499///
500/// let aligned = context.with_concrete_session(|session| {
501///     permute_indices_on_session(session, &tensor, &[k.clone(), i.clone()])
502/// })??;
503/// assert_eq!(aligned.indices()[0], k);
504/// assert_eq!(aligned.to_vec::<f64>()?, vec![1.0, 3.0, 5.0, 2.0, 4.0, 6.0]);
505/// # Ok::<(), Box<dyn std::error::Error>>(())
506/// ```
507pub fn permute_indices_on_session(
508    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
509    tensor: &IdxTensor,
510    new_indices: &[crate::defaults::DynIndex],
511) -> Result<IdxTensor, IdxTensorError> {
512    const OP: &str = "permute_indices_on_session";
513    // The compatibility route's own permutation derivation, so invalid index lists are refused identically.
514    let perm = crate::defaults::idx_tensor::compute_permutation_from_indices(
515        tensor.indices(),
516        new_indices,
517    )
518    .map_err(|error| IdxTensorError::operation(OP, anyhow::Error::new(error)))?;
519
520    // Full index equality ignores the dimension, so a supplied list can carry a different shape than the
521    // tensor's matching index. The compatibility route rejects that for a nonidentity order when it builds
522    // the result, and this route refuses it before either branch rather than silently keeping the tensor's
523    // own dimensions. For an identity order that is deliberately stricter than compatibility, which accepts
524    // malformed dimension metadata there.
525    for (position, supplied) in new_indices.iter().enumerate() {
526        let expected = &tensor.indices()[perm[position]];
527        if supplied.dim != expected.dim {
528            return Err(IdxTensorError::operation(
529                OP,
530                anyhow::anyhow!(
531                    "index {position} is supplied with dimension {} but the tensor's matching index has dimension {}",
532                    supplied.dim,
533                    expected.dim
534                ),
535            ));
536        }
537    }
538
539    if perm.iter().copied().eq(0..perm.len()) {
540        // Identity is metadata only: the same storage and eager cache under the supplied index list, for
541        // any representation.
542        return Ok(tensor.aligned_identity_metadata(new_indices));
543    }
544
545    permute_on_session(session, tensor, &perm)
546}
547
548/// Compute the squared Euclidean norm of a dense host tensor on a caller-held explicit session.
549///
550/// The compatibility entry point accumulates the norm over the tensor's payload through a scaled
551/// accumulator), so it computes the same value as the compatibility route rather than an algebraic
552/// shortcut. The session's part is the materialization: the operand is adapted and materialized on the
553/// caller's session instead of through the compatibility route.
554///
555/// Note what that accumulator does and does not change here: this API squares the accumulated norm, so for a
556/// tensor whose norm is representable but whose square is not - the `1e-200` scale - the returned value is
557/// `0` in the compatibility route as well. [`norm_on_session`] finishes the accumulator directly and
558/// preserves that representable norm. The
559/// accumulator's benefit is that individually underflowing squares can still add up to a representable
560/// result; it is not a promise about any single fixture.
561///
562/// # Errors
563///
564/// Returns [`IdxTensorError::NaNInput`] naming `norm_squared_on_session` when an element or the accumulated
565/// result is NaN. Otherwise it returns a typed [`IdxTensorError`] for the representation and dtype refusals
566/// the shared admission applies - a tracked value, a device-resident operand, a diagonal, structured or
567/// compact payload, a deferred storage error, or a non-floating dtype; note that this is the admission's
568/// refusal, not the compatibility route's `ScalarTypeMismatch`, and that the contraction route's
569/// repeated-index and planning refusals do not apply here - and for a materialization, session-copy or
570/// host-read failure while the operand is brought onto the caller's session.
571///
572/// **`f32` and `c32` operands are served here**, because this route returns a scalar: they are promoted into
573/// the same `f64` accumulation the compatibility route uses for them.
574///
575/// # Examples
576///
577/// ```
578/// use tensor4all_core::index::{DefaultIndex as Index, DynId};
579/// use tensor4all_core::{norm_squared_on_session, IdxTensor};
580/// use tensor4all_tensorbackend::CpuExecutionContext;
581/// use tensor4all_tensorbackend::CpuBackend;
582///
583/// let context = CpuExecutionContext::from_backend(CpuBackend::with_threads(1)?);
584/// let i = Index::new_dyn(2);
585/// let tensor: IdxTensor = IdxTensor::from_dense(vec![i.clone()], vec![3.0_f64, 4.0])?;
586///
587/// let squared = context.with_concrete_session(|session| {
588///     norm_squared_on_session(session, &tensor)
589/// })??;
590/// assert!((squared - 25.0).abs() < 1e-12);
591/// # Ok::<(), Box<dyn std::error::Error>>(())
592/// ```
593pub fn norm_squared_on_session(
594    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
595    tensor: &IdxTensor,
596) -> Result<f64, IdxTensorError> {
597    norm_on_session_impl::<true>(session, tensor)
598}
599
600fn norm_on_session_impl<const SQUARED: bool>(
601    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
602    tensor: &IdxTensor,
603) -> Result<f64, IdxTensorError> {
604    let op = if SQUARED {
605        "norm_squared_on_session"
606    } else {
607        "norm_on_session"
608    };
609    let operand = tensor.session_dense_operand(op)?;
610    let value = materialize_on_session(op, session, operand)?;
611    let reduced =
612        match value.dtype() {
613            // The compatibility route accumulates every accepted floating dtype in `f64`, so promoting here is
614            // its behaviour rather than a widening of this route's own.
615            tenferro::DType::F32 => {
616                let values = value
617                    .as_slice::<f32>()
618                    .map_err(|error| IdxTensorError::operation(op, anyhow::Error::new(error)))?;
619                crate::defaults::idx_tensor::lassq_norm::<SQUARED>(
620                    values
621                        .iter()
622                        .map(|value| num_complex::Complex64::new(f64::from(*value), 0.0)),
623                )
624            }
625            tenferro::DType::C32 => {
626                let values = value
627                    .as_slice::<num_complex::Complex32>()
628                    .map_err(|error| IdxTensorError::operation(op, anyhow::Error::new(error)))?;
629                crate::defaults::idx_tensor::lassq_norm::<SQUARED>(values.iter().map(|value| {
630                    num_complex::Complex64::new(f64::from(value.re), f64::from(value.im))
631                }))
632            }
633            tenferro::DType::F64 => {
634                let values = value
635                    .as_slice::<f64>()
636                    .map_err(|error| IdxTensorError::operation(op, anyhow::Error::new(error)))?;
637                crate::defaults::idx_tensor::lassq_norm::<SQUARED>(
638                    values
639                        .iter()
640                        .map(|value| num_complex::Complex64::new(*value, 0.0)),
641                )
642            }
643            tenferro::DType::C64 => {
644                let values = value
645                    .as_slice::<num_complex::Complex64>()
646                    .map_err(|error| IdxTensorError::operation(op, anyhow::Error::new(error)))?;
647                crate::defaults::idx_tensor::lassq_norm::<SQUARED>(values.iter().copied())
648            }
649            other => {
650                return Err(IdxTensorError::operation(
651                    op,
652                    anyhow::anyhow!(
653                    "the explicit-session route serves the dtypes this seam serves, not {other:?}"
654                ),
655                ));
656            }
657        };
658    reduced.ok_or(IdxTensorError::NaNInput { operation: op })
659}
660
661/// Compute the Euclidean norm of a dense host tensor on a caller-held explicit session.
662///
663/// Uses the same scaled accumulation as [`norm_squared_on_session`] and
664/// [`IdxTensor::norm`], finishing directly as a norm so its square cannot
665/// underflow or overflow before the result is returned.
666///
667/// # Errors
668///
669/// Returns [`IdxTensorError::NaNInput`] when an element or the accumulated result is NaN, and
670/// [`IdxTensorError::Operation`] for the representation and dtype refusals the shared admission applies (a
671/// tracked value, a device-resident operand, a diagonal, structured or compact payload, a deferred storage
672/// error, or a non-floating dtype) and for a materialization, session-copy or host-read failure. `f32` and
673/// `c32` operands are **served** by this route, promoted into the same `f64` accumulation the compatibility
674/// route uses.
675/// Errors carry `norm_on_session` as their operation name.
676///
677/// # Examples
678///
679/// ```
680/// use tensor4all_core::index::{DefaultIndex as Index, DynId};
681/// use tensor4all_core::{norm_on_session, IdxTensor};
682/// use tensor4all_tensorbackend::CpuExecutionContext;
683/// use tensor4all_tensorbackend::CpuBackend;
684///
685/// let context = CpuExecutionContext::from_backend(CpuBackend::with_threads(1)?);
686/// let i = Index::new_dyn(2);
687/// let tensor: IdxTensor = IdxTensor::from_dense(vec![i.clone()], vec![3.0_f64, 4.0])?;
688///
689/// let norm = context.with_concrete_session(|session| norm_on_session(session, &tensor))??;
690/// assert!((norm - 5.0).abs() < 1e-12);
691/// # Ok::<(), Box<dyn std::error::Error>>(())
692/// ```
693pub fn norm_on_session(
694    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
695    tensor: &IdxTensor,
696) -> Result<f64, IdxTensorError> {
697    norm_on_session_impl::<false>(session, tensor)
698}
699
700/// Read the dense column-major values of a host tensor under `new_indices` on a caller-held session.
701///
702/// The session counterpart of `permute_indices(new_indices)` followed by
703/// [`IdxTensor::to_vec`]: the reorder and the readback run on `session`, so a
704/// caller already inside a session reads an operand without entering the
705/// process-global context or the eager runtime that owns the operand. Compact
706/// host storage and untracked eager host values are both served; `new_indices`
707/// must be a reordering of the tensor's indices with the same dimensions.
708///
709/// # Errors
710///
711/// Returns [`IdxTensorError::PayloadScalarTypeMismatch`] when the payload is not `T`
712/// (classified exactly as [`IdxTensor::to_vec`] classifies it, so
713/// [`IdxTensorError::is_payload_scalar_type_mismatch`] holds), and the refusals of
714/// [`permute_indices_on_session`] for an invalid index list, a tracked, device-resident or
715/// structured operand, a deferred storage error or a session failure.
716///
717/// # Examples
718///
719/// ```
720/// use tensor4all_core::{dense_values_on_session, DynIndex, IdxTensor};
721/// use tensor4all_tensorbackend::{CpuBackend, CpuExecutionContext};
722///
723/// let context = CpuExecutionContext::from_backend(CpuBackend::with_threads(1)?);
724/// let i = DynIndex::new_dyn(2);
725/// let j = DynIndex::new_dyn(3);
726/// let tensor = IdxTensor::from_dense(vec![i.clone(), j.clone()], vec![1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0])?;
727/// let values = context.with_concrete_session(|session| {
728///     dense_values_on_session::<f64>(session, &tensor, &[j.clone(), i.clone()])
729/// })??;
730/// // Column-major over `[j, i]`: the transpose of the `[i, j]` buffer.
731/// assert_eq!(values, vec![1.0, 3.0, 5.0, 2.0, 4.0, 6.0]);
732/// let mismatch = context.with_concrete_session(|session| {
733///     dense_values_on_session::<f32>(session, &tensor, &[i.clone(), j.clone()])
734/// })?;
735/// assert!(mismatch.unwrap_err().is_payload_scalar_type_mismatch());
736/// # Ok::<(), Box<dyn std::error::Error>>(())
737/// ```
738pub fn dense_values_on_session<T: TensorScalar + Copy>(
739    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
740    tensor: &IdxTensor,
741    new_indices: &[crate::defaults::DynIndex],
742) -> Result<Vec<T>, IdxTensorError> {
743    const OP: &str = "dense_values_on_session";
744    let aligned = permute_indices_on_session(session, tensor, new_indices)?;
745    let operand = aligned.session_dense_operand(OP)?;
746    let value = materialize_on_session(OP, session, operand)?;
747    value.as_slice::<T>().map(<[T]>::to_vec).map_err(|source| {
748        if matches!(
749            source.kind(),
750            tenferro_tensor::ErrorKind::Validation(tenferro_tensor::ValidationKind::DTypeMismatch)
751        ) {
752            IdxTensorError::PayloadScalarTypeMismatch
753        } else {
754            IdxTensorError::operation(OP, anyhow::Error::new(source))
755        }
756    })
757}
758
759/// Publish a compact host copy of one operand on the caller's session.
760///
761/// The copy is the representation boundary the runtime-free indexed operations
762/// use: once an operand is compact, selection, stacking, gathering and
763/// permutation move host values without entering any runtime.
764fn compact_on_session(
765    op: &'static str,
766    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
767    tensor: &IdxTensor,
768) -> Result<IdxTensor, IdxTensorError> {
769    let operand = tensor.session_dense_operand(op)?;
770    let value = materialize_on_session(op, session, operand)?;
771    IdxTensor::publish_dense_session_result_owned(tensor.indices().to_vec(), value)
772}
773
774/// Contract a connected tensor network on a caller-held explicit session.
775///
776/// The runtime-free counterpart of [`contract_with_options`](crate::contract_with_options)
777/// for the concrete (non-AD) frontend: validation, connectivity, retained-index
778/// handling and the output index order come from the compatibility route's own
779/// planner, while the numerical contraction runs on `session` and the result is
780/// published as compact host storage. `f32`, `f64`, `c32` and `c64` operands are
781/// served, and the result keeps the session's dtype.
782///
783/// An empty input, an unreachable retained index, a disconnected network, a
784/// tracked or device-resident operand, or a structured/diagonal payload is
785/// refused with a typed [`IdxTensorError`].
786///
787/// # Errors
788///
789/// Returns [`IdxTensorError::Operation`] when the input is empty, when a
790/// retained index does not appear in any operand, when the operands form
791/// disconnected components, when an operand is tracked, device-resident, or a
792/// compact structured/diagonal payload, when the session rejects a
793/// materialization or the contraction, or when the result cannot be published.
794///
795/// # Examples
796///
797/// ```
798/// use tensor4all_core::{contract_with_options_on_session, ContractionOptions, DynIndex, IdxTensor};
799/// use tensor4all_tensorbackend::CpuExecutionContext;
800/// use tensor4all_tensorbackend::CpuBackend;
801///
802/// let context = CpuExecutionContext::from_backend(CpuBackend::with_threads(1)?);
803/// let i = DynIndex::new_dyn(2);
804/// let j = DynIndex::new_dyn(2);
805/// let batch = DynIndex::new_dyn(2);
806/// let left = IdxTensor::from_dense(
807///     vec![i.clone(), batch.clone()],
808///     vec![1.0_f64, 2.0, 3.0, 4.0],
809/// )?;
810/// let right = IdxTensor::from_dense(
811///     vec![i, j.clone()],
812///     vec![1.0_f64, 0.0, 0.0, 1.0],
813/// )?;
814/// let result = context.with_concrete_session(|session| {
815///     contract_with_options_on_session(
816///         session,
817///         &[&left, &right],
818///         ContractionOptions::new().with_retain_indices(&[batch.clone()]),
819///     )
820/// })??;
821/// assert_eq!(result.indices(), &[batch, j]);
822/// // Column-major over `[batch, j]`: each `j` column holds the two batch values.
823/// assert_eq!(result.dense_host_values::<f64>()?, vec![1.0, 3.0, 2.0, 4.0]);
824/// # Ok::<(), Box<dyn std::error::Error>>(())
825/// ```
826pub fn contract_with_options_on_session(
827    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
828    tensors: &[&IdxTensor],
829    options: crate::defaults::contract::ContractionOptions<'_>,
830) -> Result<IdxTensor, IdxTensorError> {
831    const OP: &str = "contract_with_options_on_session";
832    let Some(plan) = crate::defaults::contract::session_contraction_plan(tensors, options)
833        .map_err(|error| anyhow_error(OP, error))?
834    else {
835        let tensor = tensors.first().ok_or_else(|| {
836            IdxTensorError::operation(OP, anyhow::anyhow!("No tensors to contract"))
837        })?;
838        return Ok((*tensor).clone());
839    };
840
841    // Adapt every operand before any session work, so a refusal on a later
842    // operand cannot follow numerical work on an earlier one.
843    let operands = tensors
844        .iter()
845        .map(|tensor| tensor.session_dense_operand(OP))
846        .collect::<Result<Vec<_>, _>>()?;
847    let values = operands
848        .into_iter()
849        .map(|operand| materialize_on_session(OP, session, operand))
850        .collect::<Result<Vec<_>, _>>()?;
851    let value_refs = values.iter().collect::<Vec<_>>();
852    let input_ids = plan.input_ids.iter().map(Vec::as_slice).collect::<Vec<_>>();
853    let contracted = session
854        .einsum(&value_refs, &input_ids, &plan.output_ids)
855        .map_err(|error| session_error(OP, error))?;
856    IdxTensor::publish_dense_session_result_owned(plan.result_indices, contracted)
857}
858
859/// Select fixed coordinates of a dense host tensor on a caller-held explicit session.
860///
861/// The session counterpart of [`IdxTensor::select_indices`]: the operand is
862/// published as compact host storage on `session` and the selection is the
863/// runtime-free host movement the compact route already uses. All four floating
864/// dtypes are served, and the result is compact host storage.
865///
866/// # Errors
867///
868/// Returns a typed [`IdxTensorError`] for the same malformed selections as the
869/// compatibility route and for the representation/dtype refusals the session
870/// admission applies (a tracked or device-resident operand, a structured or
871/// diagonal payload, or a non-floating dtype).
872///
873/// # Examples
874///
875/// ```
876/// use tensor4all_core::{select_indices_on_session, DynIndex, IdxTensor};
877/// use tensor4all_tensorbackend::CpuExecutionContext;
878/// use tensor4all_tensorbackend::CpuBackend;
879///
880/// let context = CpuExecutionContext::from_backend(CpuBackend::with_threads(1)?);
881/// let i = DynIndex::new_dyn(2);
882/// let j = DynIndex::new_dyn(3);
883/// let tensor = IdxTensor::from_dense(
884///     vec![i, j.clone()],
885///     vec![1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0],
886/// )?;
887/// let selected = context.with_concrete_session(|session| {
888///     select_indices_on_session(session, &tensor, std::slice::from_ref(&j), &[1])
889/// })??;
890/// assert_eq!(selected.dense_host_values::<f64>()?, vec![3.0, 4.0]);
891/// # Ok::<(), Box<dyn std::error::Error>>(())
892/// ```
893pub fn select_indices_on_session(
894    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
895    tensor: &IdxTensor,
896    selected_indices: &[crate::defaults::DynIndex],
897    positions: &[usize],
898) -> Result<IdxTensor, IdxTensorError> {
899    const OP: &str = "select_indices_on_session";
900    let compact = compact_on_session(OP, session, tensor)?;
901    compact.select_indices(selected_indices, positions)
902}
903
904/// Stack dense host tensors along a newly inserted index on a caller-held explicit session.
905///
906/// The session counterpart of [`IdxTensor::stack_along_new_index`]: every operand
907/// is published as compact host storage on `session`, then the runtime-free host
908/// stacking route concatenates them. All four floating dtypes are served.
909///
910/// # Errors
911///
912/// Returns a typed [`IdxTensorError`] for the same malformed inputs as the
913/// compatibility route (no tensors, a mismatched new-index dimension, differing
914/// index orders or dimensions, an invalid insertion axis) and for the
915/// representation/dtype refusals the session admission applies.
916///
917/// # Examples
918///
919/// ```
920/// use tensor4all_core::{stack_along_new_index_on_session, DynIndex, IdxTensor};
921/// use tensor4all_tensorbackend::CpuExecutionContext;
922/// use tensor4all_tensorbackend::CpuBackend;
923///
924/// let context = CpuExecutionContext::from_backend(CpuBackend::with_threads(1)?);
925/// let i = DynIndex::new_dyn(2);
926/// let batch = DynIndex::new_dyn(2);
927/// let left = IdxTensor::from_dense(vec![i.clone()], vec![1.0_f64, 2.0])?;
928/// let right = IdxTensor::from_dense(vec![i], vec![3.0_f64, 4.0])?;
929/// let stacked = context.with_concrete_session(|session| {
930///     stack_along_new_index_on_session(session, &[&left, &right], batch, -1)
931/// })??;
932/// assert_eq!(stacked.dense_host_values::<f64>()?, vec![1.0, 2.0, 3.0, 4.0]);
933/// # Ok::<(), Box<dyn std::error::Error>>(())
934/// ```
935pub fn stack_along_new_index_on_session(
936    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
937    tensors: &[&IdxTensor],
938    new_index: crate::defaults::DynIndex,
939    axis: isize,
940) -> Result<IdxTensor, IdxTensorError> {
941    const OP: &str = "stack_along_new_index_on_session";
942    let compact = tensors
943        .iter()
944        .map(|tensor| compact_on_session(OP, session, tensor))
945        .collect::<Result<Vec<_>, _>>()?;
946    let refs = compact.iter().collect::<Vec<_>>();
947    IdxTensor::stack_along_new_index(&refs, new_index, axis)
948}
949
950/// Gather positions along one index on a caller-held explicit session.
951///
952/// The session counterpart of [`IdxTensor::index_select`]: the operand is
953/// published as compact host storage on `session` and the gather runs on that
954/// host payload, so it enters no runtime. All four floating dtypes are served.
955///
956/// # Errors
957///
958/// Returns a typed [`IdxTensorError`] when the target dimension does not match
959/// the position count, the source index is absent, a position is out of range,
960/// or the session admission refuses the operand.
961///
962/// # Examples
963///
964/// ```
965/// use tensor4all_core::{index_select_on_session, DynIndex, IdxTensor};
966/// use tensor4all_tensorbackend::CpuExecutionContext;
967/// use tensor4all_tensorbackend::CpuBackend;
968///
969/// let context = CpuExecutionContext::from_backend(CpuBackend::with_threads(1)?);
970/// let source = DynIndex::new_dyn(3);
971/// let target = DynIndex::new_dyn(2);
972/// let tensor = IdxTensor::from_dense(vec![source.clone()], vec![10.0_f64, 20.0, 30.0])?;
973/// let gathered = context.with_concrete_session(|session| {
974///     index_select_on_session(session, &tensor, &source, target, &[2, 0])
975/// })??;
976/// assert_eq!(gathered.dense_host_values::<f64>()?, vec![30.0, 10.0]);
977/// # Ok::<(), Box<dyn std::error::Error>>(())
978/// ```
979pub fn index_select_on_session(
980    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
981    tensor: &IdxTensor,
982    source_index: &crate::defaults::DynIndex,
983    target_index: crate::defaults::DynIndex,
984    positions: &[usize],
985) -> Result<IdxTensor, IdxTensorError> {
986    const OP: &str = "index_select_on_session";
987    if target_index.dim() != positions.len() {
988        return Err(IdxTensorError::operation(
989            OP,
990            anyhow::anyhow!(
991                "index_select: target index dim {} does not match position count {}",
992                target_index.dim(),
993                positions.len()
994            ),
995        ));
996    }
997    let axis = tensor
998        .indices()
999        .iter()
1000        .position(|index| index == source_index)
1001        .ok_or_else(|| {
1002            IdxTensorError::operation(
1003                OP,
1004                anyhow::anyhow!("index_select: source index is not present"),
1005            )
1006        })?;
1007    let source_dim = tensor.indices()[axis].dim();
1008    for &position in positions {
1009        if position >= source_dim {
1010            return Err(IdxTensorError::operation(
1011                OP,
1012                anyhow::anyhow!(
1013                    "index_select: position {position} is out of range for source dim {source_dim}"
1014                ),
1015            ));
1016        }
1017    }
1018    let compact = compact_on_session(OP, session, tensor)?;
1019    compact.gather_dense_host(axis, positions, target_index)
1020}
1021
1022/// A contraction operand held for one session call: an owned value or a borrowed read.
1023// Stack-only and per call: boxing the owned tensor would add an allocation to the hot path.
1024#[allow(clippy::large_enum_variant)]
1025enum HeldOperand<'a> {
1026    Owned(tenferro::Tensor),
1027    Read(Box<tenferro_tensor::TensorRead<'a>>),
1028}
1029
1030impl<'a> HeldOperand<'a> {
1031    fn dtype(&self) -> tenferro_tensor::DType {
1032        match self {
1033            Self::Owned(tensor) => tensor.dtype(),
1034            Self::Read(read) => read.dtype(),
1035        }
1036    }
1037
1038    fn as_read(&self) -> tenferro_tensor::TensorRead<'_> {
1039        match self {
1040            Self::Owned(tensor) => tenferro_tensor::TensorRead::from_tensor(tensor),
1041            Self::Read(read) => (**read).clone(),
1042        }
1043    }
1044}
1045
1046/// Prepare one operand for contraction: a read stays borrowed unless it must be conjugated.
1047fn hold_operand<'a>(
1048    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
1049    operand: SessionDenseOperand<'a>,
1050    conj: bool,
1051) -> Result<HeldOperand<'a>, IdxTensorError> {
1052    match operand {
1053        SessionDenseOperand::Read(read, _) if !conj => Ok(HeldOperand::Read(read)),
1054        operand => {
1055            let value = materialize_on_session(OP, session, operand)?;
1056            if conj {
1057                session
1058                    .conj(&value)
1059                    .map(HeldOperand::Owned)
1060                    .map_err(|error| session_error(OP, error))
1061            } else {
1062                Ok(HeldOperand::Owned(value))
1063            }
1064        }
1065    }
1066}
1067
1068/// Turn a held operand into an owned tensor (copying a borrowed read on the session).
1069fn owned_operand(
1070    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
1071    held: HeldOperand<'_>,
1072) -> Result<tenferro::Tensor, IdxTensorError> {
1073    match held {
1074        HeldOperand::Owned(tensor) => Ok(tensor),
1075        HeldOperand::Read(read) => {
1076            let ids: Vec<usize> = (0..read.shape().len()).collect();
1077            session
1078                .einsum_reads(&[*read], &[&ids], &ids)
1079                .map_err(|error| session_error(OP, error))
1080        }
1081    }
1082}
1083
1084/// Materialize one operand as an owned concrete host value of the caller's session.
1085///
1086/// Host storage is converted by the existing bridge, which does not enter a runtime; an untracked eager
1087/// host value is read through its borrowed representation and copied by the session itself.
1088fn materialize_on_session(
1089    op: &'static str,
1090    session: &mut tensor4all_tensorbackend::explicit::Session<'_>,
1091    operand: SessionDenseOperand<'_>,
1092) -> Result<tenferro::Tensor, IdxTensorError> {
1093    match operand {
1094        SessionDenseOperand::Storage(storage, dims) => {
1095            tensor4all_tensorbackend::storage_to_native_tensor(&storage, &dims)
1096                .map_err(|error| anyhow_error(op, anyhow::Error::new(error)))
1097        }
1098        SessionDenseOperand::Read(read, rank) => {
1099            let ids: Vec<usize> = (0..rank).collect();
1100            session
1101                .einsum_reads(&[*read], &[&ids], &ids)
1102                .map_err(|error| session_error(op, error))
1103        }
1104    }
1105}
1106
1107/// Map a session-side failure into this crate's error, named by its own operation.
1108fn session_error<E: Into<Box<dyn std::error::Error + Send + Sync>>>(
1109    op: &'static str,
1110    error: E,
1111) -> IdxTensorError {
1112    IdxTensorError::Operation {
1113        operation: op,
1114        source: Arc::from(error.into()),
1115    }
1116}
1117
1118/// Map a planning-side failure into this crate's error, named by its own operation.
1119fn anyhow_error(op: &'static str, error: anyhow::Error) -> IdxTensorError {
1120    IdxTensorError::Operation {
1121        operation: op,
1122        source: Arc::from(error.into_boxed_dyn_error()),
1123    }
1124}