crates.sage_stash.storage.handle_ownership

Handles never cross stash ownership implicitly. A Ptr<T> or Slice<T> is interpreted only by its allocating Stash. Retaining a value across a stash boundary requires a structural copy into the destination; a checked output tree must not contain handles back into its source CST or an imported query result.

Read in specification context · design/crates/sage_stash/storage.sage

Implementation

Implemented crates/sage-ir/src/check/finalize.rs:23–28

sage_ir::check::finalize · lib:sage_ir

#![allow(unused)]
fn main() {
// {anchor}`crates.sage_stash.storage.handle_ownership`
// {anchor}`crates.sage_stash.storage.immutable_entries`
pub(super) fn finalize_typed_body<'db>(
    source: &Stash,
    egraph: &VersionedEGraph<'db>,
    root: Ptr<TyExpr<'db>>,

}

See more source ↗

Implemented crates/sage-stash/src/lib.rs:1021–1026

sage_stash · lib:sage_stash

Conditional source: #[cfg(debug_assertions)]

#![allow(unused)]
fn main() {
    // {anchor}`crates.sage_stash.storage.handle_ownership`
    fn validate_stash_id<T>(&self, handle_stash_id: u32) {
        assert_eq!(
            handle_stash_id,
            self.id,
            "stash identity mismatch: handle from stash {} used on stash {} (type `{}`)",

}

See more source ↗

Implemented crates/sage-stash-macros/src/lib.rs:226–231

sage_stash_macros · proc-macro:sage_stash_macros

#![allow(unused)]
fn main() {
// {anchor}`crates.sage_stash.storage.handle_ownership`
fn generate_stash_copy_body(input: &DeriveInput) -> proc_macro2::TokenStream {
    match &input.data {
        syn::Data::Struct(data) => generate_stash_copy_struct_fields(&data.fields),
        syn::Data::Enum(data) => {
            let arms: Vec<_> = data

}

See more source ↗

Tests and review

Indexed tests and the implementation-completeness and test-adequacy review; no test run is implied.

Implemented sage_ir::check::finalize::tests::finalized_nested_body_owns_resolved_and_imported_types_after_sources_drop

crates/sage-ir/src/check/finalize.rs · lib:sage_ir

#![allow(unused)]
fn main() {
#[test]
    #[sage::test(crates.sage_stash.storage.handle_ownership)]
    #[sage::test(crates.sage_stash.storage.immutable_entries)]
    #[sage::test(crates.sage_ir.types.body.no_inference)]
    fn finalized_nested_body_owns_resolved_and_imported_types_after_sources_drop() {
        use crate::cst::expr::Literal;

        let mut imported_stash = Stash::new();
        let imported_bool = imported_stash.alloc(Ty::Bool);
        let imported = Stashed::new(imported_stash, imported_bool);
        let mut source = Stash::new();
        source.alloc(123_u64);
        let boolean = imported.copy_into(&mut source);
        let mut egraph = VersionedEGraph::new();
        let variable = egraph.alloc_var(Version::ROOT, Universe::ROOT);
        let inference = source.alloc(Ty::InferVar(variable));
        try_unify(&mut egraph, &mut source, Version::ROOT, inference, boolean).unwrap();
        let span = RelativeSpan { start: 0, end: 4 };
        let child = source.alloc(TyExpr {
            data: TyExprData::Literal(Literal::Bool(true)),
            ty: inference,
            span,
        });
        let pending = source.alloc(TyExpr {
            data: TyExprData::Unresolved(ExprSlot(0)),
            ty: inference,
            span,
        });
        let elements = source.alloc_slice(&[pending, child]);
        let types = source.alloc_slice(&[inference, boolean]);
        let tuple = source.alloc(Ty::Tuple(types));
        let root = source.alloc(TyExpr {
            data: TyExprData::Tuple(elements),
            ty: tuple,
            span,
        });
        let completed = finalize_typed_body(&source, &egraph, root, &[child], &[], span);
        assert_eq!(source[inference], Ty::InferVar(variable));
        assert_eq!(source[types], [inference, boolean]);
        assert_eq!(source[elements], [pending, child]);
        assert_eq!(source[pending].data, TyExprData::Unresolved(ExprSlot(0)));
        assert_eq!(imported.root_deref(), Ty::Bool);
        drop(egraph);
        drop(source);
        drop(imported);

        let (
            target,
            TyBodyData {
                root,
                locals,
                span: completed_span,
            },
        ) = completed.open_deref();
        assert_eq!(completed_span, span);
        assert!(target[locals].is_empty());
        let TyExpr {
            data,
            ty,
            span: root_span,
        } = target[root];
        assert_eq!(root_span, span);
        let Ty::Tuple(types) = target[ty] else {
            panic!("expected tuple type")
        };
        assert_eq!(target[types].len(), 2);
        for ty in &target[types] {
            assert_eq!(target[*ty], Ty::Bool);
        }
        let TyExprData::Tuple(elements) = data else {
            panic!("expected tuple expression")
        };
        assert_eq!(target[elements].len(), 2);
        assert_eq!(target[elements][0], target[elements][1]);
        for child in &target[elements] {
            let TyExpr {
                data,
                ty,
                span: child_span,
            } = target[*child];
            assert_eq!(data, TyExprData::Literal(Literal::Bool(true)));
            assert_eq!(target[ty], Ty::Bool);
            assert_eq!(child_span, span);
        }
    }
}

Conditional source: #[cfg(test)]

See more source ↗

Implemented sage_stash::tests::copy_into_compound

crates/sage-stash/tests/arena_tests.rs · test:arena_tests

#![allow(unused)]
fn main() {
#[test]
    #[sage::test(crates.sage_stash.storage.handle_ownership)]
    fn copy_into_compound() {
        #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, AllocStashData)]
        struct Pair {
            a: Ptr<Point>,
            b: Ptr<Point>,
        }

        let mut src = Stash::new();
        let a = src.alloc(Point { x: 1, y: 2 });
        let b = src.alloc(Point { x: 3, y: 4 });
        let pair = src.alloc(Pair { a, b });
        let stashed = Stashed::new(src, pair);

        let mut target = Stash::new();
        let copied: Ptr<Pair> = stashed.copy_into(&mut target);
        let p = target[copied];
        assert_eq!(target[p.a], Point { x: 1, y: 2 });
        assert_eq!(target[p.b], Point { x: 3, y: 4 });
    }
}

Conditional source: #[cfg(test)]

See more source ↗

Implemented sage_stash::tests::copy_into_with_slice

crates/sage-stash/tests/arena_tests.rs · test:arena_tests

#![allow(unused)]
fn main() {
#[test]
    #[sage::test(crates.sage_stash.storage.handle_ownership)]
    fn copy_into_with_slice() {
        let mut src = Stash::new();
        let pts = src.alloc_slice(&[Point { x: 1, y: 2 }, Point { x: 3, y: 4 }]);
        let stashed = Stashed::new(src, pts);

        let mut target = Stash::new();
        let copied: Slice<Point> = stashed.copy_into(&mut target);
        assert_eq!(target[copied], [Point { x: 1, y: 2 }, Point { x: 3, y: 4 }]);
    }
}

Conditional source: #[cfg(test)]

See more source ↗

Implemented sage_stash::tests::cross_stash_ptr_same_type_panics_in_debug

crates/sage-stash/tests/arena_tests.rs · test:arena_tests

#![allow(unused)]
fn main() {
#[test]
    #[cfg_attr(debug_assertions, should_panic(expected = "stash identity mismatch"))]
    #[sage::test(crates.sage_stash.storage.handle_ownership)]
    fn cross_stash_ptr_same_type_panics_in_debug() {
        let mut stash1 = Stash::new();
        let mut stash2 = Stash::new();
        let p1 = stash1.alloc(Point { x: 1, y: 2 });
        let _p2 = stash2.alloc(Point { x: 99, y: 100 });
        let _ = stash2[p1];
    }
}

Conditional source: #[cfg(test)], #[cfg_attr(debug_assertions, should_panic(expected = "stash identity mismatch"))]

See more source ↗

Implemented sage_stash::tests::cross_stash_ptr_wrong_type

crates/sage-stash/tests/arena_tests.rs · test:arena_tests

#![allow(unused)]
fn main() {
#[test]
    #[cfg_attr(debug_assertions, should_panic(expected = "stash identity mismatch"))]
    #[cfg_attr(not(debug_assertions), should_panic(expected = "stash type mismatch"))]
    #[sage::test(crates.sage_stash.storage.handle_ownership)]
    fn cross_stash_ptr_wrong_type() {
        let mut stash1 = Stash::new();
        let mut stash2 = Stash::new();
        let p1 = stash1.alloc(Point { x: 1, y: 2 });
        let _c2 = stash2.alloc(Color { r: 0, g: 0, b: 0 });
        let _ = stash2[p1];
    }
}

Conditional source: #[cfg(test)], #[cfg_attr(debug_assertions, should_panic(expected = "stash identity mismatch"))], #[cfg_attr(not(debug_assertions), should_panic(expected = "stash type mismatch"))]

See more source ↗

Implemented sage_stash::tests::cross_stash_slice_panics_in_debug

crates/sage-stash/tests/arena_tests.rs · test:arena_tests

#![allow(unused)]
fn main() {
#[test]
    #[cfg_attr(debug_assertions, should_panic(expected = "stash identity mismatch"))]
    #[sage::test(crates.sage_stash.storage.handle_ownership)]
    fn cross_stash_slice_panics_in_debug() {
        let mut stash1 = Stash::new();
        let mut stash2 = Stash::new();
        let s1 = stash1.alloc_slice(&[Point { x: 1, y: 2 }]);
        let _s2 = stash2.alloc_slice(&[Point { x: 99, y: 100 }]);
        let _ = &stash2[s1];
    }
}

Conditional source: #[cfg(test)], #[cfg_attr(debug_assertions, should_panic(expected = "stash identity mismatch"))]

See more source ↗

Implemented sage_stash::copied_nested_handles_survive_source_drop_and_destination_growth

crates/sage-stash/tests/storage_contracts.rs · test:storage_contracts

#![allow(unused)]
fn main() {
#[test]
#[sage::test(crates.sage_stash.storage.handle_ownership)]
fn copied_nested_handles_survive_source_drop_and_destination_growth() {
    let mut source = Stash::new();
    let value = source.alloc(42_u32);
    let other = source.alloc(99_u32);
    let children = source.alloc_slice(&[value, other, value]);
    let root = source.alloc(Branch { value, children });
    let tree = Stashed::new(source, root);
    let mut destination = Stash::new();
    // Different entry layout detects a shallow copy even in release builds.
    destination.alloc(7_u64);
    destination.alloc_slice(&[1_u8, 2, 3]);
    let copied = tree.copy_into(&mut destination);
    drop(tree);
    for n in 0..4096_u64 {
        destination.alloc(n);
    }
    let Branch { value, children } = destination[copied];
    assert_eq!(destination[value], 42);
    let children = &destination[children];
    assert_eq!(children.len(), 3);
    assert_eq!(children[0], children[2]);
    assert_eq!(children[0], value);
    assert_eq!(
        children.iter().map(|p| destination[*p]).collect::<Vec<_>>(),
        [42, 99, 42]
    );
}
}

See more source ↗

Implemented sage_stash::cross_stash_slice_with_different_element_type_is_rejected

crates/sage-stash/tests/storage_contracts.rs · test:storage_contracts

#![allow(unused)]
fn main() {
#[test]
#[cfg_attr(debug_assertions, should_panic(expected = "stash identity mismatch"))]
#[cfg_attr(not(debug_assertions), should_panic(expected = "stash type mismatch"))]
#[sage::test(crates.sage_stash.storage.handle_ownership)]
fn cross_stash_slice_with_different_element_type_is_rejected() {
    let mut source = Stash::new();
    let handle = source.alloc_slice(&[42_u32]);
    let mut destination = Stash::new();
    destination.alloc_slice(&[42_u64]);
    let _ = &destination[handle];
}
}

Conditional source: #[cfg_attr(debug_assertions, should_panic(expected = "stash identity mismatch"))], #[cfg_attr(not(debug_assertions), should_panic(expected = "stash type mismatch"))]

See more source ↗

Review: Accepted · final_quality.

Reviewed all three implementation entries and eight associated tests for handle_ownership. Requirements are owner-relative Ptr/Slice interpretation, explicit structural transfer across stash boundaries, and completed output ownership independent of source CST/imported query stashes. Captured storage-guide and architectural rationale explicitly distinguish debug ownership checks from release reliance on the invariant; this is not a claim of release-time owner branding.

sage-stash::validate_stash_id checks the debug handle tag against the owning stash before pointer/slice indexing. Both indexing paths additionally validate entry type, including release builds. Handles contain an entry index (plus debug owner tag), and equality/hash alone do not establish cross-stash identity. StashCopy for Ptr reads the source value, recursively copies it, and allocates in the target; Slice recursively copies every element into a target slice. Stashed::copy_into supplies its own source owner. Self-contained StashDirect values are copied directly, rather than confusing database identities with stash handles.

The macro implementation generate_stash_copy_body recursively invokes StashCopy for every named/tuple struct field and every named/tuple enum field, handles unit cases, and rejects unions. This makes derived compound copies traverse nested handles instead of copying their numerical indices. finalize_typed_body creates a fresh stash and structurally copies root, locals and body. BodyFinalizer resolves source egraph representatives/expression slots and recursively rebuilds type, alias, trait/call argument, expression, statement, pattern, field and arm edges in the destination, using memo tables to preserve repeated references. Captured Const and TokenTree definitions confirm the directly retained array length/token fields are self-contained values or database handles, not hidden stash pointers. The review concerns copy ownership, not authored expression-checking semantics.

All eight tests have meaningful visible expectations. cross_stash_ptr_same_type_panics_in_debug and cross_stash_slice_panics_in_debug require owner mismatch only under debug assertions; they intentionally do not assert owner rejection in release. cross_stash_ptr_wrong_type and cross_stash_slice_with_different_element_type_is_rejected require debug owner mismatch and release type mismatch. copy_into_compound checks both nested Point values through copied pointers; copy_into_with_slice checks copied elements. copied_nested_handles_survive_source_drop_and_destination_growth uses a different destination entry layout, drops the source-owned tree, grows the destination by 4096 allocations, then checks values, slice length and repeated-handle equality. This exercises structural copying even without debug owner tags. finalized_nested_body_owns_resolved_and_imported_types_after_sources_drop constructs an imported bool and source inference/slot/tuple tree, finalizes it, asserts the original source remains unchanged, drops egraph/source/imported storage, and traverses the destination to assert concrete bool types, literal values, spans, repeated resolved children and empty locals.

Captured fixture type declarations ensure those nested fields are actual Ptr/Slice members with generated copying, not opaque helper assertions. Coverage is focused unit/constructed completed-body evidence, not an exhaustive audit of all future tree variants or every compiler query. Within the documented debug/release ownership contract, the set covers the specified pointer/slice misuse, recursive copying and source-independent output scenarios. No TODO/N/A entries are associated here. No code changes or tests executed in this review; commands were fresh review start/read and source inspection before recording. No requested edits.

Browse crates anchors

139 anchors

Specification anchors and declared coverage
AnchorImplementationTests
crates (139)114 Implemented37 TODO2 N/A74 Implemented107 TODO
crates.sage_inspector (15)13 Implemented1 TODO2 N/A3 Implemented15 TODO
crates.sage_inspector.inspection (15)13 Implemented1 TODO2 N/A3 Implemented15 TODO
balanced_tracesImplementedTODO
canonical_ownershipImplementedImplementedTODO
derive_reflectionImplementedImplementedTODO
detail_free_indexImplementedTODO
deterministic_traceImplementedTODO
durable_navigationN/ATODO
generic_browserN/ATODO
owned_reflectionImplementedImplementedTODO
product_availabilityImplementedTODO
revision_and_demandImplementedTODO
semantic_phase_boundaryImplementedTODO
source_evidenceImplementedTODO
typed_serviceImplementedTODO
unknown_workImplementedTODOTODO
workspace_actorImplementedTODO
crates.sage_ir (90)67 Implemented34 TODO40 Implemented88 TODO
crates.sage_ir.checking (12)12 Implemented3 TODO5 Implemented12 TODO
crates.sage_ir.checking.body (5)5 Implemented2 TODO3 Implemented5 TODO
elaborationImplementedImplementedTODO
expected_typesImplementedTODOTODO
interface_dependenciesImplementedImplementedTODO
isolated_completionImplementedImplementedTODO
operator_callsImplementedTODOTODO
identity_mintingImplementedTODO
owned_productsImplementedImplementedTODO
crates.sage_ir.checking.signature (4)4 Implemented1 TODO1 Implemented4 TODO
body_independenceImplementedTODO
narrow_detailImplementedTODOTODO
owner_binderImplementedImplementedTODO
storageImplementedTODO
symbol_keyed_interfacesImplementedTODO
crates.sage_ir.crate (9)9 TODO9 TODO
explicit_restrictionsTODOTODO
identity_before_detailTODOTODO
incremental_evidenceTODOTODO
narrow_demandsTODOTODO
reexecution_and_invalidationTODOTODO
represented_completenessTODOTODO
restrictions_and_gapsTODOTODO
semantic_query_boundariesTODOTODO
terminal_incompletenessTODOTODO
crates.sage_ir.inference (8)8 Implemented6 Implemented8 TODO
atomic_checkingImplementedImplementedTODO
body_local_quiescenceImplementedImplementedTODO
canonical_boundaryImplementedImplementedTODO
completed_body_boundaryImplementedTODO
numeric_domainsImplementedImplementedTODO
subtyping_and_coercionImplementedImplementedTODO
terminal_obligationsImplementedTODO
transaction_isolationImplementedImplementedTODO
crates.sage_ir.metadata (4)4 Implemented1 TODO4 TODO
explicit_incompletenessImplementedTODO
keyed_reuseImplementedTODOTODO
product_boundariesImplementedTODO
provider_authorityImplementedTODO
crates.sage_ir.modules (8)7 Implemented1 TODO4 Implemented8 TODO
crates.sage_ir.modules.expand (4)4 Implemented2 Implemented4 TODO
completenessImplementedImplementedTODO
dependenciesImplementedTODO
direct_membersImplementedTODO
recursion_and_fixpointImplementedImplementedTODO
crates.sage_ir.modules.parse (4)3 Implemented1 TODO2 Implemented4 TODO
dependenciesImplementedTODO
detail_firewallImplementedImplementedTODO
recovery_completenessTODOTODO
syntax_identitiesImplementedImplementedTODO
crates.sage_ir.resolution (5)5 Implemented1 TODO3 Implemented4 TODO
crates.sage_ir.resolution.lookup (5)5 Implemented1 TODO3 Implemented4 TODO
completenessImplementedTODOImplementedTODO
dependenciesImplementedTODO
expansion_import_ambiguityImplementedImplemented
identity_onlyImplementedTODO
precedenceImplementedImplementedTODO
crates.sage_ir.solver (9)7 Implemented7 TODO5 Implemented9 TODO
alternative_isolationImplementedTODOImplementedTODO
bounded_completenessImplementedTODOTODO
candidate_completenessImplementedTODO
canonical_cyclesTODOTODO
canonical_outputsImplementedImplementedTODO
local_index_firewallTODOTODO
normalization_demandImplementedTODOImplementedTODO
schedule_independenceImplementedTODOImplementedTODO
shared_final_resultImplementedTODOImplementedTODO
crates.sage_ir.symbols (8)8 Implemented4 Implemented7 TODO
associated_identityImplementedImplemented
associated_interfacesImplementedTODO
body_interfacesImplementedImplementedTODO
definition_identityImplementedTODO
external_fact_queriesImplementedTODO
external_identityImplementedTODO
kind_wrappersImplementedImplementedTODO
local_identityImplementedImplementedTODO
crates.sage_ir.types (27)16 Implemented12 TODO13 Implemented27 TODO
crates.sage_ir.types.aliases (2)1 Implemented1 TODO1 Implemented2 TODO
identityImplementedImplementedTODO
revelationTODOTODO
crates.sage_ir.types.binder (1)1 Implemented1 TODO1 Implemented1 TODO
owner_parametersImplementedTODOImplementedTODO
crates.sage_ir.types.body (13)4 Implemented9 TODO3 Implemented13 TODO
awaitTODOTODO
closuresTODOTODO
conditional_patternsTODOTODO
coroutinesTODOTODO
diagnosed_recoveryImplementedImplementedTODO
elaboratedTODOImplementedTODO
for_iterationTODOTODO
indexingTODOTODO
macro_expansionTODOTODO
no_inferenceImplementedImplementedTODO
resolved_referencesImplementedTODO
try_residualTODOTODO
typed_provenanceImplementedTODO
crates.sage_ir.types.calls (2)1 Implemented1 TODO1 Implemented2 TODO
dispatch_familiesTODOTODO
selected_semanticsImplementedImplementedTODO
crates.sage_ir.types.lifetimes (2)2 Implemented2 Implemented2 TODO
dummyImplementedImplementedTODO
unchecked_borrowsImplementedImplementedTODO
crates.sage_ir.types.operators (2)2 Implemented1 Implemented2 TODO
lazy_control_flowImplementedTODO
trait_callsImplementedImplementedTODO
scoped_identitiesImplementedTODO
crates.sage_ir.types.spans (4)4 Implemented4 Implemented4 TODO
generated_identityImplementedImplementedTODO
item_originImplementedImplementedTODO
offset_reuseImplementedImplementedTODO
relative_compositionImplementedImplementedTODO
crates.sage_oracle_harness (4)4 Implemented2 TODO1 Implemented4 TODO
crates.sage_oracle_harness.crate (4)4 Implemented2 TODO1 Implemented4 TODO
deterministic_emissionImplementedTODO
exact_comparisonImplementedTODOImplementedTODO
fixed_projectionImplementedTODO
independent_coverageImplementedTODOTODO
crates.sage_stash (5)5 Implemented5 Implemented
crates.sage_stash.storage (5)5 Implemented5 Implemented
handle_ownershipImplementedImplemented
immutable_entriesImplementedImplemented
query_valueImplementedImplemented
rooted_equalityImplementedImplemented
typed_interningImplementedImplemented
crates.sage_test_harness (25)25 Implemented25 Implemented
crates.sage_test_harness.compile_tests (25)25 Implemented25 Implemented
annotation_validationImplementedImplemented
blessing_gateImplementedImplemented
callsite_updatesImplementedImplemented
checking_scopeImplementedImplemented
compiler_conditionsImplementedImplemented
completed_typesImplementedImplemented
coordinatesImplementedImplemented
dependenciesImplementedImplemented
diagnostic_countsImplementedImplemented
diagnostic_locationsImplementedImplemented
editionImplementedImplemented
fixturesImplementedImplemented
grouped_observationsImplementedImplemented
invocationImplementedImplemented
production_executionImplementedImplemented
project_isolationImplementedImplemented
query_captureImplementedImplemented
query_projectionImplementedImplemented
renderingImplementedImplemented
resolved_symbolsImplementedImplemented
review_visibilityImplementedImplemented
rustc_executionImplementedImplemented
rustc_lintsImplementedImplemented
starting_expressionsImplementedImplemented
target_lineImplementedImplemented