reasoninglayer 1.0.3

Rust client SDK for the Reasoning Layer API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! End-to-end scenario tests against a running backend.
//!
//! Where `tests/diagnosis.rs` smoke-tests one endpoint at a time, this file
//! exercises *workflows* — the multi-step paths a real user takes. Each
//! scenario:
//!
//! 1. Creates a fresh per-test tenant (UUID v4).
//! 2. Runs the workflow.
//! 3. Best-effort wipes the tenant via `AdminClient::clear_tenant_data`.
//!
//! Gated with `#[ignore]`. Run with:
//!
//! ```sh
//! cargo test --test scenarios -- --ignored --test-threads=1
//! ```

mod common;

use common::{build_client, cleanup, fresh_tenant, require_backend};
use reasoninglayer::api_spec::{
    BulkCreateSortsRequest, BulkSortDefinition, ComputeGlbRequest, ComputeLubRequest,
    CreateSortRequest, FeatureDescriptorDto,
};
use reasoninglayer::{
    constrained, guard, psi, var, AddFactRequest, AddRuleRequest, BackwardChainRequest,
    CreateTermRequest, FeatureInputValueDto, FindBySortRequest, GuardOp, Value,
};
use std::collections::BTreeMap;
use uuid::Uuid;

// ─── Scenario 1: Sort lifecycle (create, get, list, delete) ───────────────────

#[tokio::test]
#[ignore = "requires a running backend"]
async fn scenario_sort_lifecycle() {
    let tenant = fresh_tenant();
    let client = build_client(&tenant);
    require_backend(&client).await;

    // Create.
    let sort = client
        .sorts()
        .create_sort(CreateSortRequest::with_name("scenario_animal"), None)
        .await
        .expect("create_sort succeeds");
    let sort_id = sort.id.to_string();

    // Get.
    let fetched = client
        .sorts()
        .get_sort(&sort_id, None)
        .await
        .expect("get_sort succeeds");
    assert_eq!(fetched.id, sort.id);
    assert_eq!(fetched.name, "scenario_animal");

    // List.
    let listed = client
        .sorts()
        .list_sorts(None)
        .await
        .expect("list_sorts succeeds");
    assert_eq!(listed.len(), 1, "expected exactly one sort, got {}", listed.len());

    // Delete.
    client
        .sorts()
        .delete_sort(&sort_id, None)
        .await
        .expect("delete_sort succeeds");

    let after = client
        .sorts()
        .list_sorts(None)
        .await
        .expect("list_sorts after delete succeeds");
    assert!(
        after.is_empty(),
        "expected empty sort list after delete, got {} sorts",
        after.len()
    );

    cleanup(&client, &tenant).await;
}

// ─── Scenario 2: Sort hierarchy + subtype + GLB / LUB ─────────────────────────

#[tokio::test]
#[ignore = "requires a running backend"]
async fn scenario_sort_hierarchy_with_glb_lub() {
    let tenant = fresh_tenant();
    let client = build_client(&tenant);
    require_backend(&client).await;

    // animal <- dog
    let animal = client
        .sorts()
        .create_sort(CreateSortRequest::with_name("animal"), None)
        .await
        .expect("create animal sort");
    let dog_req = CreateSortRequest {
        name: Some("dog".to_string()),
        parents: vec![animal.id],
        ..Default::default()
    };
    let dog = client
        .sorts()
        .create_sort(dog_req, None)
        .await
        .expect("create dog sort");

    // animal <- cat
    let cat_req = CreateSortRequest {
        name: Some("cat".to_string()),
        parents: vec![animal.id],
        ..Default::default()
    };
    let cat = client
        .sorts()
        .create_sort(cat_req, None)
        .await
        .expect("create cat sort");

    // dog ⊆ animal
    let is_sub = client
        .sorts()
        .is_subtype(&dog.id.to_string(), &animal.id.to_string(), None)
        .await
        .expect("is_subtype succeeds");
    assert!(is_sub, "expected dog ⊆ animal");

    // GLB(dog, cat) — disjoint sibling sorts share no proper subtype.
    let glb = client
        .sorts()
        .compute_glb(
            ComputeGlbRequest {
                sort1_id: dog.id,
                sort2_id: cat.id,
            },
            None,
        )
        .await
        .expect("compute_glb succeeds");
    // Backend may return None (no shared subtype) or a synthetic GLB sort —
    // both are valid; just verify the call deserializes.
    let _ = glb.glb;

    // LUB(dog, cat) → animal
    let lub = client
        .sorts()
        .compute_lub(
            ComputeLubRequest {
                sort1_id: dog.id,
                sort2_id: cat.id,
            },
            None,
        )
        .await
        .expect("compute_lub succeeds");
    assert_eq!(
        lub.lub,
        Some(animal.id),
        "expected LUB(dog, cat) = animal"
    );

    cleanup(&client, &tenant).await;
}

// ─── Scenario 3: Term lifecycle within a sort ─────────────────────────────────

#[tokio::test]
#[ignore = "requires a running backend"]
async fn scenario_term_lifecycle() {
    let tenant = fresh_tenant();
    let client = build_client(&tenant);
    require_backend(&client).await;

    let sort = client
        .sorts()
        .create_sort(CreateSortRequest::with_name("person"), None)
        .await
        .expect("create person sort");

    let mut features = BTreeMap::new();
    features.insert("name".into(), Value::string("Alice"));
    features.insert("age".into(), Value::integer(30));
    let term = client
        .terms()
        .create_term(
            CreateTermRequest {
                sort_id: sort.id.to_string(),
                owner_id: tenant.clone(),
                features,
            },
            None,
        )
        .await
        .expect("create_term succeeds")
        .term;

    // Round-trip via find_by_sort.
    let found = client
        .query()
        .find_by_sort(
            FindBySortRequest {
                sort_name: Some("person".into()),
                ..Default::default()
            },
            None,
        )
        .await
        .expect("find_by_sort succeeds");
    assert_eq!(found.len(), 1);
    assert_eq!(found[0].id, term.id);
    assert_eq!(found[0].display_name.as_deref(), Some("Alice"));

    cleanup(&client, &tenant).await;
}

// ─── Scenario 4: End-to-end inference (rule + fact + backward chain) ──────────

#[tokio::test]
#[ignore = "requires a running backend"]
async fn scenario_backward_chain_finds_fact() {
    let tenant = fresh_tenant();
    let client = build_client(&tenant);
    require_backend(&client).await;

    // Create sorts: employee, well_paid (both have a `name`/`person` feature
    // we'll bind via inference rules). Backend infers feature shapes lazily,
    // so we don't need to declare features up front for this scenario.
    client
        .sorts()
        .create_sort(CreateSortRequest::with_name("employee"), None)
        .await
        .expect("create employee");
    client
        .sorts()
        .create_sort(CreateSortRequest::with_name("well_paid"), None)
        .await
        .expect("create well_paid");

    // Fact: employee(name="Alice", salary=95_000)
    client
        .inference()
        .add_fact(
            AddFactRequest {
                term: psi(
                    "employee",
                    [
                        ("name", FeatureInputValueDto::string("Alice")),
                        ("salary", FeatureInputValueDto::Integer(95_000)),
                    ],
                ),
            },
            None,
        )
        .await
        .expect("add_fact succeeds");

    // Rule: well_paid(person=?X) :- employee(name=?X, salary=?S where ?S > 80_000).
    client
        .inference()
        .add_rule(
            AddRuleRequest {
                term: psi("well_paid", [("person", var("?X"))]),
                antecedents: vec![psi(
                    "employee",
                    [
                        ("name", var("?X")),
                        (
                            "salary",
                            constrained("?S", guard(GuardOp::Gt, 80_000_i64)),
                        ),
                    ],
                )],
                certainty: None,
            },
            None,
        )
        .await
        .expect("add_rule succeeds");

    // Goal: well_paid(person=?Who)
    let resp = client
        .inference()
        .backward_chain(
            BackwardChainRequest {
                goal: Some(psi("well_paid", [("person", var("?Who"))])),
                max_solutions: Some(10),
                ..Default::default()
            },
            None,
        )
        .await
        .expect("backward_chain succeeds");

    assert!(
        !resp.solutions.is_empty(),
        "expected at least one solution binding ?Who, got {} solutions",
        resp.solutions.len()
    );

    cleanup(&client, &tenant).await;
}

// ─── Scenario 5: Bulk sort creation with name-based parent refs ───────────────

#[tokio::test]
#[ignore = "requires a running backend"]
async fn scenario_bulk_create_sorts_by_name() {
    let tenant = fresh_tenant();
    let client = build_client(&tenant);
    require_backend(&client).await;

    let req = BulkCreateSortsRequest {
        sorts: vec![
            BulkSortDefinition {
                name: "vehicle".into(),
                parents: vec![],
                features: vec![],
                alt_labels: vec![],
                description: None,
            },
            BulkSortDefinition {
                name: "car".into(),
                parents: vec!["vehicle".into()],
                features: vec![FeatureDescriptorDto {
                    name: "wheels".into(),
                    required: true,
                    annotations: Default::default(),
                    constraint: None,
                    expected_sort: None,
                    expected_type_hint: Some("Integer".into()),
                }],
                alt_labels: vec![],
                description: None,
            },
            BulkSortDefinition {
                name: "truck".into(),
                parents: vec!["vehicle".into()],
                features: vec![],
                alt_labels: vec![],
                description: None,
            },
        ],
    };
    let resp = client
        .sorts()
        .bulk_create_sorts(req, None)
        .await
        .expect("bulk_create_sorts succeeds");

    assert_eq!(resp.created_count, 3);
    assert!(resp.errors.is_empty(), "unexpected errors: {:?}", resp.errors);
    assert_eq!(resp.sort_ids.len(), 3);

    // Verify hierarchy: car ⊆ vehicle.
    let car_id = resp
        .sort_ids
        .get("car")
        .expect("car sort_id present")
        .to_string();
    let vehicle_id = resp
        .sort_ids
        .get("vehicle")
        .expect("vehicle sort_id present")
        .to_string();
    let is_sub = client
        .sorts()
        .is_subtype(&car_id, &vehicle_id, None)
        .await
        .expect("is_subtype succeeds");
    assert!(is_sub, "expected car ⊆ vehicle after bulk create");

    cleanup(&client, &tenant).await;
}

// ─── Scenario 6: Tenant isolation — separate tenants don't see each other ─────

#[tokio::test]
#[ignore = "requires a running backend"]
async fn scenario_tenant_isolation() {
    let tenant_a = fresh_tenant();
    let tenant_b = fresh_tenant();
    let client_a = build_client(&tenant_a);
    let client_b = build_client(&tenant_b);
    require_backend(&client_a).await;

    // Tenant A creates a sort.
    client_a
        .sorts()
        .create_sort(CreateSortRequest::with_name("only_in_a"), None)
        .await
        .expect("create_sort in tenant A");

    // Tenant B should not see it.
    let in_b = client_b
        .sorts()
        .list_sorts(None)
        .await
        .expect("list_sorts in tenant B");
    assert!(
        in_b.iter().all(|s| s.name != "only_in_a"),
        "tenant B sees tenant A's sort — isolation broken"
    );

    cleanup(&client_a, &tenant_a).await;
    cleanup(&client_b, &tenant_b).await;
}

// ─── Smoke test: builders produce the right TermInputDto shape ────────────────
// (Local to scenarios because it depends on the live backend rejecting bad
// shapes — moves the contract test off the wiremock harness.)

#[tokio::test]
#[ignore = "requires a running backend"]
async fn scenario_constrained_variable_round_trips_through_backend() {
    let tenant = fresh_tenant();
    let client = build_client(&tenant);
    require_backend(&client).await;

    client
        .sorts()
        .create_sort(CreateSortRequest::with_name("number_holder"), None)
        .await
        .expect("create sort");

    // Fact with an integer feature.
    client
        .inference()
        .add_fact(
            AddFactRequest {
                term: psi(
                    "number_holder",
                    [("value", FeatureInputValueDto::Integer(42))],
                ),
            },
            None,
        )
        .await
        .expect("add fact");

    // Goal: number_holder(value=?V where ?V < 100). The backend must accept
    // the constrained-variable shape we serialize.
    let goal = psi(
        "number_holder",
        [(
            "value",
            constrained("?V", guard(GuardOp::Lt, 100_i64)),
        )],
    );
    let resp = client
        .inference()
        .backward_chain(
            BackwardChainRequest {
                goal: Some(goal),
                max_solutions: Some(1),
                ..Default::default()
            },
            None,
        )
        .await
        .expect("backward_chain with constrained var succeeds");
    assert!(
        !resp.solutions.is_empty(),
        "expected at least one solution for value < 100"
    );

    cleanup(&client, &tenant).await;
}

// ─── Helper to pin trait imports (for scoped use macros) ──────────────────────

fn _silence_unused_imports() {
    let _: Option<Uuid> = None;
}