meta.contracts.cache_invocations

Every annotated source invocation is checked, including query cache hits and same-operation recursion. A Salsa request and its execution represent one architectural invocation. Internal validation, dependency reexecution, and accumulator traversal remain distinguishable from source requests; reexecution establishes the executing operation’s context without attributing its work to the suspended caller or inventing a source call.

Verification covers cold, reused, validated, invalidated/reexecuted, recursive, cancelled, and panicking runs, calls through generated query APIs, and an unannotated query beneath an annotated caller. Hand-reviewed traversals identify the architectural operations, Rust declaration sites, parentage, and cache outcomes. A warm forbidden request must fail even when its body does not execute.

Read in specification context · design/meta/contracts.md

Implementation

Implemented crates/sage-meta/src/salsa_contracts.rs:117–122

sage_meta::salsa_contracts · lib:sage_meta

Conditional source: #[cfg(feature = "salsa")]

#![allow(unused)]
fn main() {
    // {anchor}`meta.contracts.cache_invocations`
    pub fn event(&mut self, event: &salsa::Event) {
        let (key, kind, outcome) = match event.kind {
            EventKind::WillRequest { database_key } => {
                (database_key, QueryEventKind::Request, None)
            }

}

See more source ↗

TODO crates/sage-meta/tests/contracts_plan.rs:19–26

sage_meta::todo · test:contracts_plan

TODO: Observe real ordinary function entries, including two functions mapped to the same operation, through the selected instrumentation.

#![allow(unused)]
fn main() {
    // {anchor}`meta.contracts.cache_invocations`<<
    #[test]
    #[sage::test(meta.contracts.cache_invocations)]
    fn ordinary_rust_call_boundaries_are_instrumented() {
        // TODO: Observe real ordinary function entries, including two functions
        // mapped to the same operation, through the selected instrumentation.
    }
    // >>

}

See more source ↗

Tests and review

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

Implemented sage_meta::real_salsa_contract_fixture

crates/sage-meta/tests/contracts.rs · test:contracts

#![allow(unused)]
fn main() {
#[test]
#[sage::test(meta.language.calls.declared)]
#[sage::test(meta.language.calls.forbidden)]
#[sage::test(meta.contracts.validated_session)]
#[sage::test(meta.contracts.cache_invocations)]
#[sage::test(meta.contracts.observation_coverage)]
fn real_salsa_contract_fixture() {
    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    let fixture = root.join("tests/fixtures/contracts");
    let output = std::process::Command::new(env!("CARGO"))
        .args(["test", "--locked", "--manifest-path"])
        .arg(fixture.join("Cargo.toml"))
        .args(["--", "--nocapture", "--test-threads=1"])
        .env(
            "CARGO_TARGET_DIR",
            root.join("../../target/sage-contract-fixture"),
        )
        .output()
        .expect("run the isolated contracts fixture");
    assert!(
        output.status.success(),
        "contract fixture failed:\n{}\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8(output.stdout).unwrap();
    let evidence: Vec<serde_json::Value> = stdout
        .lines()
        .filter_map(|line| line.split_once("SAGE_CONTRACT_EVIDENCE:"))
        .map(|(_, json)| serde_json::from_str(json).unwrap())
        .collect();
    assert_eq!(evidence.len(), 2, "expected cold and prewarmed reports");
    let root = "sage_contract_fixture::nodes::Root::run";
    let helper = "sage_contract_fixture::nodes::Helper::work";
    let leaf = "sage_contract_fixture::nodes::Leaf::read";
    for prewarmed in [false, true] {
        let sample = evidence
            .iter()
            .find(|sample| sample["prewarmed"] == prewarmed)
            .expect("each cache scenario must report evidence");
        let operations = &sample["model"]["operations"];
        assert!(operations[helper]["invokes"].as_array().unwrap().is_empty());
        assert_eq!(
            operations[root]["prohibits"][0]["targets"],
            serde_json::json!([leaf])
        );
        let report = &sample["contracts"];
        assert_eq!(report["calls_conform"], false);
        assert_eq!(report["coverage"]["checked_requests"], 3);
        assert!(report["coverage"]["gaps"].as_array().unwrap().is_empty());
        let violations = report["violations"].as_array().unwrap();
        assert_eq!(violations.len(), 2);
        assert_eq!(violations[0]["kind"], "UndeclaredCall");
        assert_eq!(violations[1]["kind"], "ForbiddenTransitive");
        assert_eq!(violations[1]["rule"]["operation"], root);
        assert_eq!(
            violations[1]["path"]
                .as_array()
                .unwrap()
                .iter()
                .map(|frame| frame["operation"].as_str().unwrap())
                .collect::<Vec<_>>(),
            [root, helper, leaf],
        );
        if prewarmed {
            let events = sample["query_events"].as_array().unwrap();
            assert!(events.iter().any(|event| {
                let event = event.as_str().unwrap();
                event.starts_with("return Leaf::read") && event.contains("[Reused]")
            }));
            assert!(
                !events
                    .iter()
                    .any(|event| event.as_str().unwrap().starts_with("execute Leaf::read"))
            );
        }
    }
}
}

See more source ↗

TODO sage_meta::todo::ordinary_rust_call_boundaries_are_instrumented

crates/sage-meta/tests/contracts_plan.rs · test:contracts_plan

#![allow(unused)]
fn main() {
#[test]
    #[sage::test(meta.contracts.cache_invocations)]
    fn ordinary_rust_call_boundaries_are_instrumented() {
        // TODO: Observe real ordinary function entries, including two functions
        // mapped to the same operation, through the selected instrumentation.
    }
}

See more source ↗

Implemented sage_meta::internal_reexecution_establishes_context_without_fabricating_a_call

crates/sage-meta/tests/runtime_contracts.rs · test:runtime_contracts

#![allow(unused)]
fn main() {
#[test]
#[sage::test(meta.contracts.cache_invocations)]
fn internal_reexecution_establishes_context_without_fabricating_a_call() {
    let mut session = session(
        model(
            r#"
        class Root { """Root.""" query run() -> u32 { """Run.""" envelope {} } }
        class Dependency { """Dependency."""
            query run() -> u32 { """Run.""" envelope { invokes crate::Leaf::read(); } }
        }
        class Leaf { """Leaf.""" query read() -> u32 { """Read.""" envelope {} } }
    "#,
        ),
        &["Root::run"],
    );
    let root = session.enter("demo::Root::run", None);
    let validation = session.enter_validation("demo::Dependency::run", None);
    let leaf = session.enter("demo::Leaf::read", None);
    session.exit(leaf);
    session.exit(validation);
    session.exit(root);
    let report = session.finish();
    report.assert_calls_conform();
    assert_eq!(report.coverage.validation_contexts, 1);
    assert!(
        matches!(&report.trace[1], ContractEvent::Enter(frame) if frame.kind == EntryKind::Validation)
    );
}
}

See more source ↗

Implemented sage_meta::same_operation_entry_is_recursion_and_needs_permission

crates/sage-meta/tests/runtime_contracts.rs · test:runtime_contracts

#![allow(unused)]
fn main() {
#[test]
#[sage::test(meta.language.calls.declared)]
#[sage::test(meta.contracts.cache_invocations)]
#[sage::test(meta.language.envelopes.receiver_calls)]
fn same_operation_entry_is_recursion_and_needs_permission() {
    let leaf = r#"class Tree { """Tree.""" fn walk() -> u32 { """Walk.""" envelope {} } }"#;
    let mut denied = session(model(leaf), &["Tree::walk"]);
    let a = denied.enter("demo::Tree::walk", Some("tree:1"));
    let b = denied.enter("demo::Tree::walk", Some("tree:1"));
    denied.exit(b);
    denied.exit(a);
    assert_eq!(
        denied.finish().violations[0].kind,
        ViolationKind::UndeclaredCall
    );

    let recursive = leaf.replace("envelope {}", "envelope { invokes self.walk(); }");
    let mut allowed = session(model(&recursive), &["Tree::walk"]);
    let a = allowed.enter("demo::Tree::walk", Some("tree:1"));
    let b = allowed.enter("demo::Tree::walk", Some("tree:1"));
    allowed.exit(b);
    allowed.exit(a);
    let report = allowed.finish();
    report.assert_calls_conform();
    assert_eq!(report.coverage.checked_requests, 2);
    assert!(matches!(&report.trace[1], ContractEvent::Enter(frame) if frame.parent == Some(a)));
}
}

See more source ↗

Review: Accepted · Codex /root/anchor_183.

Reassessed the complete claim, both implementation entries and all four associated tests. Independently verified exact byte equality of all five coordinator-listed historical implementation/test source snapshots with current files; the prior rationale remains supported by current source, rather than being treated as execution evidence. Captured the runtime engine, runtime test helpers, real fixture sources/model and expected traversals through review read.
SalsaObserver checks WillRequest even on cache reuse; a matching WillExecute adds only an execution scope, so a request and body count once. Standalone execution and accumulator traversal install Validation context, preserving the executing operation without inventing a caller permission edge. ContractSession gives recursive entries distinct IDs and parents, checks requests individually and retains ancestor prohibitions. The associated recursion test asserts denied recursion, allowed recursion, two requests and parentage; internal_reexecution_establishes_context_without_fabricating_a_call checks conformance where Root cannot call Dependency but Dependency may call Leaf, plus one Validation context.
The associated real_salsa_contract_fixture visibly asserts cold/prewarmed reports, three checked requests, no gaps, both violations, the full Root/Helper/Leaf path, and warm Leaf reuse without execution. Its subprocess runs the captured fixture tests: exact cold/warm/validated traversals map architectural operations to Rust declarations and dispositions; changing input 10 to 11 reexecutes Helper while Root validates; panic yields Cancelled and the next session conforms; generated accumulated API remains observable without invented calls; removing Helper annotation beneath Root yields an unmapped gap. Captured malformed lifecycle assertions guard nesting, missing execution, cached-after-executed and changed causes. These collectively cover cold, reused, validated, invalidated/reexecuted, recursive, cancelled/panicking, generated API and unannotated-query scenarios and parentage.
The TODO implementation/test ordinary_rust_call_boundaries_are_instrumented explicitly defers real ordinary function entry instrumentation, including two functions mapped to one operation. Its prerequisite is selecting and implementing that instrumentation, then replacing the empty stub with actual boundary/recursion assertions. It supplies no behavioral proof; the universal annotated-source invocation guarantee therefore remains visibly deferred. No N/A entries exist and no edits are requested for this justified deferral.
Execution: I ran review start/read and byte-comparison commands, not behavior tests or cargo build. The coordinator separately reports 321 functional tests and root cargo build passing; that is baseline context, not my execution result.

Browse meta anchors

116 anchors

Specification anchors and declared coverage
AnchorImplementationTests
meta (116)102 Implemented24 TODO103 Implemented36 TODO
meta.anchors (22)22 Implemented21 Implemented12 TODO
anchor_pagesImplementedImplementedTODO
book_explorerImplementedImplementedTODO
canonical_sourcesImplementedImplementedTODO
meta.anchors.content (7)7 Implemented7 Implemented
blocksImplementedImplemented
explicit_endImplementedImplemented
headingImplementedImplemented
literal_syntaxImplementedImplemented
next_anchorImplementedImplemented
source_endImplementedImplemented
unmatched_endImplementedImplemented
context_navigationImplementedImplementedTODO
evidence_statusImplementedImplementedTODO
explorer_navigationImplementedTODO
implementation_coverageImplementedImplementedTODO
implementation_referencesImplementedImplementedTODO
placeholder_statusImplementedImplementedTODO
point_excerptsImplementedImplementedTODO
region_balanceImplementedImplemented
region_excerptsImplementedImplementedTODO
test_coverageImplementedImplemented
test_referencesImplementedImplemented
unique_namesImplementedImplementedTODO
meta.book (21)10 Implemented18 TODO12 Implemented18 TODO
anchor_movesImplementedTODOImplementedTODO
authorityImplementedTODOImplementedTODO
browser_deliveryTODOImplementedTODO
browser_dependenciesTODOTODO
browser_rust_sourceTODOTODO
browser_searchTODOTODO
browser_serveTODOTODO
browser_structureTODOTODO
chapter_namesImplementedTODOImplementedTODO
crate_ownershipImplementedImplemented
crates_landingImplementedImplemented
entity_linksTODOTODO
index_groupsImplementedTODOImplementedTODO
index_namespace_pagesImplementedImplemented
index_rowsImplementedTODOImplementedTODO
index_statusImplementedTODOImplementedTODO
rfd_changesTODOTODO
sage_chaptersTODOImplementedTODO
self_descriptionTODOTODO
shared_modelImplementedTODOImplementedTODO
source_rolesTODOTODO
meta.contracts (4)4 Implemented3 TODO4 Implemented3 TODO
cache_invocationsImplementedTODOImplementedTODO
correspondenceImplementedImplemented
observation_coverageImplementedTODOImplementedTODO
validated_sessionImplementedTODOImplementedTODO
meta.language (39)39 Implemented39 Implemented
meta.language.calls (2)2 Implemented2 Implemented
declaredImplementedImplemented
forbiddenImplementedImplemented
meta.language.classes (3)3 Implemented3 Implemented
abstract_completeImplementedImplemented
override_signatureImplementedImplemented
single_inheritanceImplementedImplemented
meta.language.contexts (1)1 Implemented1 Implemented
inheritanceImplementedImplemented
meta.language.envelopes (7)7 Implemented7 Implemented
class_callsImplementedImplemented
createsImplementedImplemented
direct_callsImplementedImplemented
leafImplementedImplemented
permissionsImplementedImplemented
readsImplementedImplemented
receiver_callsImplementedImplemented
meta.language.fields (2)2 Implemented2 Implemented
context_stateImplementedImplemented
kindsImplementedImplemented
meta.language.methods (2)2 Implemented2 Implemented
kindsImplementedImplemented
proseImplementedImplemented
meta.language.model (3)3 Implemented3 Implemented
forbidden_pathsImplementedImplemented
inherited_prohibitionsImplementedImplemented
virtual_dispatchImplementedImplemented
meta.language.types (19)19 Implemented19 Implemented
argument_arityImplementedImplemented
declaration_proseImplementedImplemented
enum_variantsImplementedImplemented
field_proseImplementedImplemented
generic_parametersImplementedImplemented
member_commasImplementedImplemented
name_resolutionImplementedImplemented
opaque_representationImplementedImplemented
preludeImplementedImplemented
qualified_namesImplementedImplemented
recursive_valuesImplementedImplemented
struct_fieldsImplementedImplemented
tuplesImplementedImplemented
type_expressionsImplementedImplemented
unique_fieldsImplementedImplemented
unique_parametersImplementedImplemented
unique_variantsImplementedImplemented
unknown_namesImplementedImplemented
variant_proseImplementedImplemented
meta.reviews (27)27 Implemented27 Implemented
claim_textImplementedImplemented
complete_test_setImplementedImplemented
decisionsImplementedImplemented
fragment_associationsImplementedImplemented
fragment_formatImplementedImplemented
fragment_freshnessImplementedImplemented
gateImplementedImplemented
input_formatImplementedImplemented
input_fragmentsImplementedImplemented
output_formatImplementedImplemented
preparationImplementedImplemented
record_requiredImplementedImplemented
recorded_readsImplementedImplemented
recordingImplementedImplemented
review_delegationImplementedImplemented
review_diagnosticsImplementedImplemented
review_instructionsImplementedImplemented
review_scopeImplementedImplemented
selector_claimImplementedImplemented
selector_line_rangeImplementedImplemented
selector_testImplementedImplemented
selector_whole_fileImplementedImplemented
source_representationImplementedImplemented
stalenessImplementedImplemented
summary_formatImplementedImplemented
test_sourceImplementedImplemented
validation_layoutImplementedImplemented
meta.validation (3)3 TODO3 TODO
claim_specific_evidenceTODOTODO
independent_inspectionTODOTODO
review_packetsTODOTODO