clm-kernel 0.0.20

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
use std::fs;

pub fn run_integration_polyglot_sla_sandboxing(clm_root: &str, clm_file: &str) -> Result<String, String> {
    if clm_file.ends_with("test_duration_fail.yaml") {
        std::thread::sleep(std::time::Duration::from_millis(25));
        return Ok("duration_delay_completed".to_string());
    }
    if clm_file.ends_with("test_rss_fail.yaml") {
        return Ok("rss_completed".to_string());
    }
    if clm_file.ends_with("test_sandbox_verify.yaml") {
        let conn = crate::db::get_connection("agent_identities", clm_root).unwrap();
        conn.execute(
            "INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?, ?, datetime('now'));",
            ["sub_sandboxed_hash", "sub_sandboxed_content"],
        ).unwrap();
        return Ok("sandbox_write_completed".to_string());
    }
    if clm_file.ends_with("test_parity_success.yaml") {
        return Ok("hello".to_string());
    }
    if clm_file.ends_with("test_parity_fail.yaml") {
        return Ok("hello".to_string());
    }

    let (original_clm_root, test_dir) = super::setup_isolated_env("test_polyglot_sla_sandboxing");

    println!("======================================================");
    println!("  Test Suite: Polyglot SLA & Sandboxing Invariance (100.3)");
    println!("======================================================\n");

    // Initialize TriDB in the isolated environment
    crate::db::init_tridb(test_dir.to_str().unwrap()).unwrap();
    println!("  ✅ init_tridb completed in-memory");

    // -- Test 1: Database Isolation & Sandboxing --
    println!("\n-- Test 1: Database Isolation & Sandboxing --");
    {
        let _guard = crate::db::DatabaseSandboxGuard::activate("test_isolation_verify");
        let conn_sandboxed = crate::db::get_connection("agent_identities", test_dir.to_str().unwrap()).unwrap();
        conn_sandboxed.execute(
            "INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?, ?, datetime('now'));",
            ["test_sandboxed_hash", "test_sandboxed_content"],
        ).unwrap();

        let exists_in_sandbox: i64 = conn_sandboxed.query_row(
            "SELECT count(*) FROM card WHERE hash = ?;",
            ["test_sandboxed_hash"],
            |row| row.get(0),
        ).unwrap_or(0);
        assert_eq!(exists_in_sandbox, 1);
        println!("  ✅ Card exists in sandboxed DB connection");
    }

    let conn_physical = crate::db::get_connection("agent_identities", test_dir.to_str().unwrap()).unwrap();
    let exists_in_physical: i64 = conn_physical.query_row(
        "SELECT count(*) FROM card WHERE hash = ?;",
        ["test_sandboxed_hash"],
        |row| row.get(0),
    ).unwrap_or(0);
    assert_eq!(exists_in_physical, 0);
    println!("  ✅ Verified: Sandboxed writes did not leak to production/physical databases");

    // -- Test 2: SLA Timing Violation --
    println!("\n-- Test 2: SLA Timing Violation --");
    let manifest_duration_fail = test_dir.join("test_duration_fail.yaml");
    let duration_fail_content = r#"clm:
  abstract_spec:
    context: "SLA Timing Fail"
    goal: "Verify duration SLA violation"
    success_criteria: []
  concrete_impl:
    runtime: rust
    operation: test_duration_fail
    process:
      type: internal_reference
      module: "clm_rust_core::integration::test_polyglot_sla_sandboxing"
  balanced_exp:
    expectation: "Fail on duration limit"
    polyglot_cases:
      - name: "duration_fail_case"
        given:
          runtimes: ["rust"]
        when: "test_duration_fail"
        then:
          internal_reference: "clm_rust_core::integration::test_polyglot_sla_sandboxing"
          exit_code: 0
          performance_sla:
            max_duration_ms: 1
            max_forks: 0
"#;
    fs::write(&manifest_duration_fail, duration_fail_content).unwrap();

    let res_dur = crate::polyglot::exec_polyglot(manifest_duration_fail.to_str().unwrap(), None, test_dir.to_str().unwrap());
    assert!(res_dur.is_err());
    let err_str = res_dur.err().unwrap();
    assert!(err_str.contains("exceeded max_duration_ms"));
    println!("  ✅ Timing SLA enforcer correctly caught timing violation");

    // -- Test 3: SLA Forks Violation --
    println!("\n-- Test 3: SLA Forks Violation --");
    // Sub-test 3a: internal_reference case declaring max_forks > 0 (schema validation failure)
    let manifest_fork_fail_schema = test_dir.join("test_fork_fail_schema.yaml");
    let fork_fail_schema_content = r#"clm:
  abstract_spec:
    context: "SLA Fork Fail Schema"
    goal: "Verify fork schema violation"
    success_criteria: []
  concrete_impl:
    runtime: rust
    operation: test_fork_fail_schema
    process:
      type: internal_reference
      module: "clm_rust_core::integration::test_polyglot_sla_sandboxing"
  balanced_exp:
    expectation: "Fail on fork limit schema"
    polyglot_cases:
      - name: "fork_fail_schema_case"
        given:
          runtimes: ["rust"]
        when: "test_fork_fail_schema"
        then:
          internal_reference: "clm_rust_core::integration::test_polyglot_sla_sandboxing"
          exit_code: 0
          performance_sla:
            max_forks: 1
"#;
    fs::write(&manifest_fork_fail_schema, fork_fail_schema_content).unwrap();

    let res_fork_schema = crate::polyglot::exec_polyglot(manifest_fork_fail_schema.to_str().unwrap(), None, test_dir.to_str().unwrap());
    assert!(res_fork_schema.is_err());
    let err_str = res_fork_schema.err().unwrap();
    assert!(err_str.contains("max_forks must be 0 for internal_reference cases"));
    println!("  ✅ Schema validator correctly rejected max_forks > 0 for internal_reference");

    // Sub-test 3b: shell/native case with max_forks: 0 (runtime fork violation)
    let manifest_fork_fail_run = test_dir.join("test_fork_fail_run.yaml");
    let fork_fail_run_content = r#"clm:
  abstract_spec:
    context: "SLA Fork Fail Run"
    goal: "Verify fork run violation"
    success_criteria: []
  concrete_impl:
    runtime: system
    operation: test_fork_fail_run
    process:
      type: shell
      script: "echo ok"
  balanced_exp:
    expectation: "Fail on fork limit run"
    polyglot_cases:
      - name: "fork_fail_run_case"
        given:
          runtimes: ["shell"]
        when: "test_fork_fail_run"
        then:
          native_harness:
            tool: "echo"
            command: "ok"
          exit_code: 0
          performance_sla:
            max_forks: 0
"#;
    fs::write(&manifest_fork_fail_run, fork_fail_run_content).unwrap();

    let res_fork_run = crate::polyglot::exec_polyglot(manifest_fork_fail_run.to_str().unwrap(), None, test_dir.to_str().unwrap());
    assert!(res_fork_run.is_err());
    let err_str = res_fork_run.err().unwrap();
    assert!(err_str.contains("exceeded max_forks"));
    println!("  ✅ Fork SLA enforcer correctly caught fork violation");

    // -- Test 4: SLA Memory Violation --
    println!("\n-- Test 4: SLA Memory Violation --");
    let manifest_rss_fail = test_dir.join("test_rss_fail.yaml");
    let rss_fail_content = r#"clm:
  abstract_spec:
    context: "SLA Memory Fail"
    goal: "Verify RSS SLA violation"
    success_criteria: []
  concrete_impl:
    runtime: rust
    operation: test_rss_fail
    process:
      type: internal_reference
      module: "clm_rust_core::integration::test_polyglot_sla_sandboxing"
  balanced_exp:
    expectation: "Fail on RSS limit"
    polyglot_cases:
      - name: "rss_fail_case"
        given:
          runtimes: ["rust"]
        when: "test_rss_fail"
        then:
          internal_reference: "clm_rust_core::integration::test_polyglot_sla_sandboxing"
          exit_code: 0
          performance_sla:
            max_rss_kb: 10
            max_forks: 0
"#;
    fs::write(&manifest_rss_fail, rss_fail_content).unwrap();

    let res_rss = crate::polyglot::exec_polyglot(manifest_rss_fail.to_str().unwrap(), None, test_dir.to_str().unwrap());
    assert!(res_rss.is_err());
    let err_str = res_rss.err().unwrap();
    assert!(err_str.contains("exceeded max_rss_kb"));
    println!("  ✅ Memory SLA enforcer correctly caught RSS memory violation");

    // -- Test 5: Database Sandboxing redirection via exec_polyglot --
    println!("\n-- Test 5: Database Sandboxing redirection via exec_polyglot --");
    let manifest_sandbox_verify = test_dir.join("test_sandbox_verify.yaml");
    let sandbox_verify_content = r#"clm:
  abstract_spec:
    context: "Sandbox In-process Redirect"
    goal: "Verify DB writes are sandboxed in-process"
    success_criteria: []
  concrete_impl:
    runtime: rust
    operation: test_sandbox_verify
    process:
      type: internal_reference
      module: "clm_rust_core::integration::test_polyglot_sla_sandboxing"
  balanced_exp:
    expectation: "Writes redirected"
    polyglot_cases:
      - name: "sandbox_verify_case"
        given:
          runtimes: ["rust"]
        when: "test_sandbox_verify"
        then:
          internal_reference: "clm_rust_core::integration::test_polyglot_sla_sandboxing"
          exit_code: 0
          performance_sla:
            max_forks: 0
"#;
    fs::write(&manifest_sandbox_verify, sandbox_verify_content).unwrap();

    let res_sandbox = crate::polyglot::exec_polyglot(manifest_sandbox_verify.to_str().unwrap(), None, test_dir.to_str().unwrap());
    assert!(res_sandbox.is_ok());

    let conn_phys = crate::db::get_connection("agent_identities", test_dir.to_str().unwrap()).unwrap();
    let sub_exists_in_physical: i64 = conn_phys.query_row(
        "SELECT count(*) FROM card WHERE hash = ?;",
        ["sub_sandboxed_hash"],
        |row| row.get(0),
    ).unwrap_or(0);
    assert_eq!(sub_exists_in_physical, 0);
    println!("  ✅ Verified: Sandboxed writes in sub-case did not leak to physical databases");

    // -- Test 6: Parity / Port Univalence --
    println!("\n-- Test 6: Parity / Port Univalence --");
    // Parity Success: both rust (returning "hello") and shell (printing "hello") match
    let manifest_parity_success = test_dir.join("test_parity_success.yaml");
    let parity_success_content = r#"clm:
  abstract_spec:
    context: "Parity Success Case"
    goal: "Verify parity matches"
    success_criteria: []
  concrete_impl:
    runtime: rust
    operation: test_parity_success
    process:
      type: internal_reference
      module: "clm_rust_core::integration::test_polyglot_sla_sandboxing"
      implementations:
        shell:
          script: "echo hello"
  balanced_exp:
    expectation: "Success"
    polyglot_cases:
      - name: "parity_success_case"
        given:
          runtimes: ["rust", "shell"]
        when: "test_parity_success"
        then:
          internal_reference: "clm_rust_core::integration::test_polyglot_sla_sandboxing"
          exit_code: 0
"#;
    fs::write(&manifest_parity_success, parity_success_content).unwrap();

    let res_parity_ok = crate::polyglot::exec_polyglot(manifest_parity_success.to_str().unwrap(), None, test_dir.to_str().unwrap());
    if let Err(ref e) = res_parity_ok {
        println!("❌ Parity success case failed with error: {}", e);
    }
    assert!(res_parity_ok.is_ok());
    println!("  ✅ Parity verification succeeded when outputs match");

    // Parity Failure: rust (returning "hello") and shell (printing "world") mismatch
    let manifest_parity_fail = test_dir.join("test_parity_fail.yaml");
    let parity_fail_content = r#"clm:
  abstract_spec:
    context: "Parity Fail Case"
    goal: "Verify parity mismatch caught"
    success_criteria: []
  concrete_impl:
    runtime: rust
    operation: test_parity_fail
    process:
      type: internal_reference
      module: "clm_rust_core::integration::test_polyglot_sla_sandboxing"
      implementations:
        shell:
          script: "echo world"
  balanced_exp:
    expectation: "Fail"
    polyglot_cases:
      - name: "parity_fail_case"
        given:
          runtimes: ["rust", "shell"]
        when: "test_parity_fail"
        then:
          internal_reference: "clm_rust_core::integration::test_polyglot_sla_sandboxing"
          exit_code: 0
"#;
    fs::write(&manifest_parity_fail, parity_fail_content).unwrap();

    let res_parity_err = crate::polyglot::exec_polyglot(manifest_parity_fail.to_str().unwrap(), None, test_dir.to_str().unwrap());
    assert!(res_parity_err.is_err());
    let err_str = res_parity_err.err().unwrap();
    assert!(err_str.contains("[PARITY_ERR]"));
    println!("  ✅ Parity verification caught output mismatch successfully");

    super::restore_env(&original_clm_root, &test_dir);
    println!("\n======================================================");
    print!("  Results: 8 passed, 0 failed (of 8)");
    Ok("".to_string())
}