telltale-runtime 17.0.0

Choreographic programming for Telltale - effect-based distributed protocols
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
#![allow(clippy::unwrap_used)]
#![allow(clippy::expect_used)]

//! Integration tests for enhanced choreography features
//!
//! This module tests the integration of enhanced features:
//! - Namespaces with dynamic roles and choices
//! - Complex multi-feature protocols
//! - End-to-end compilation and generation

use telltale_runtime::{
    ast::{LocalType, Role},
    compiler::{
        codegen::{generate_choreography_code_with_dynamic_roles, generate_dynamic_role_support},
        parser::parse_choreography_str,
        projection::project,
    },
};

#[test]
fn test_namespaced_choreographies() {
    // Test combining namespaces with basic message flows
    let protocol1 = r#"
        module secure_messaging exposing (EncryptedChat)
        protocol EncryptedChat =
            roles Client, Server

            Client -> Server : SecureMessage
            Server -> Client : Acknowledgment
    "#;

    let protocol2 = r#"
        module file_transfer exposing (SecureFileTransfer)
        protocol SecureFileTransfer =
            roles Sender, Receiver

            Sender -> Receiver : FileChunk
            Receiver -> Sender : ChunkAck
    "#;

    // Both protocols should parse successfully
    let choreo1 = parse_choreography_str(protocol1).expect("Protocol 1 should parse");
    let choreo2 = parse_choreography_str(protocol2).expect("Protocol 2 should parse");

    // Verify namespaces are different
    assert_eq!(choreo1.namespace.as_ref().unwrap(), "secure_messaging");
    assert_eq!(choreo2.namespace.as_ref().unwrap(), "file_transfer");

    // Verify role counts
    assert_eq!(choreo1.roles.len(), 2);
    assert_eq!(choreo2.roles.len(), 2);

    // Test projection for both
    for role in &choreo1.roles {
        let local_type = project(&choreo1, role).expect("Projection should succeed");
        assert_ne!(local_type, LocalType::End); // Should have meaningful projections
    }

    for role in &choreo2.roles {
        let local_type = project(&choreo2, role).expect("Projection should succeed");
        assert_ne!(local_type, LocalType::End);
    }
}

#[test]
fn test_dynamic_roles() {
    // Test dynamic roles combined with branching and ranges
    let protocol = r#"
        module threshold_consensus exposing (AnnotatedThreshold)
        protocol AnnotatedThreshold =
            roles Leader, Followers[*]

            Leader -> Followers[*] : PrepareRequest
            Followers[0..quorum] -> Leader : PrepareResponse
            Leader -> Followers[*] : CommitRequest
            Followers[0..quorum] -> Leader : CommitResponse
    "#;

    let choreo = parse_choreography_str(protocol).expect("Dynamic annotated protocol should parse");

    // Verify namespace
    assert_eq!(choreo.namespace.as_ref().unwrap(), "threshold_consensus");

    // Verify roles
    assert_eq!(choreo.roles.len(), 2);
    let leader = &choreo.roles[0];
    let followers = &choreo.roles[1];

    assert_eq!(leader.name().to_string(), "Leader");
    assert_eq!(followers.name().to_string(), "Followers");
    assert!(followers.is_dynamic());

    // Test code generation with dynamic support
    let local_types = vec![
        (leader.clone(), LocalType::End),
        (followers.clone(), LocalType::End),
    ];
    let generated_code = generate_choreography_code_with_dynamic_roles(&choreo, &local_types);
    let code_str = generated_code.to_string();

    // Verify dynamic support is generated
    assert!(code_str.contains("AnnotatedThresholdRuntime"));
    assert!(code_str.contains("dynamic"));
    assert!(code_str.contains("bind_role_count"));
}

#[test]
fn test_complex_multi_feature_protocol() {
    // Test protocol using all enhanced features together
    let protocol = r#"
        module advanced_example exposing (ComplexProtocol)
        protocol ComplexProtocol =
            roles Coordinator, Workers[N], Database

            Coordinator -> Workers[*] : InitRequest
            Workers[i] -> Database : DataQuery
            Database -> Workers[i] : QueryResult
            Workers[0..majority] -> Coordinator : WorkResult

            choice Coordinator at
                | success =>
                    Coordinator -> Workers[*] : SuccessNotification
                    Coordinator -> Database : FinalizeTransaction
                | retry =>
                    Coordinator -> Workers[*] : RetryRequest
                | abort =>
                    Coordinator -> Database : AbortTransaction
                    Coordinator -> Workers[*] : AbortNotification
    "#;

    let choreo = parse_choreography_str(protocol).expect("Complex protocol should parse");

    // Verify all features are present
    assert_eq!(choreo.namespace.as_ref().unwrap(), "advanced_example");
    assert_eq!(choreo.roles.len(), 3);

    // Check role types
    let coordinator = &choreo.roles[0];
    let workers = &choreo.roles[1];
    let database = &choreo.roles[2];

    assert_eq!(coordinator.name().to_string(), "Coordinator");
    assert_eq!(workers.name().to_string(), "Workers");
    assert_eq!(database.name().to_string(), "Database");

    assert!(!coordinator.is_parameterized());
    assert!(workers.is_symbolic()); // Workers[N]
    assert!(!database.is_parameterized());

    // Test projection works for all roles
    for role in &choreo.roles {
        let result = project(&choreo, role);
        // Some projections may fail due to dynamic roles without bindings, but structure should be valid
        match result {
            Ok(local_type) => {
                // Projection succeeded - for complex protocols with dynamic roles,
                // End might be a valid result if the role doesn't participate
                println!("Projection succeeded for {}: {:?}", role.name(), local_type);
            }
            Err(projection_error) => {
                // Expected for dynamic roles without runtime bindings
                println!(
                    "Expected projection error for {}: {:?}",
                    role.name(),
                    projection_error
                );
            }
        }
    }

    // Test code generation
    let local_types = vec![
        (coordinator.clone(), LocalType::End),
        (workers.clone(), LocalType::End),
        (database.clone(), LocalType::End),
    ];

    let generated_code = generate_choreography_code_with_dynamic_roles(&choreo, &local_types);
    let code_str = generated_code.to_string();

    // Verify all components are generated
    assert!(code_str.contains("ComplexProtocolRuntime"));
    assert!(code_str.contains("validate_workers_count"));
    assert!(code_str.contains("bind_role_count"));
}

#[test]
fn test_multiple_dynamic_role_types() {
    // Test protocol with multiple types of dynamic roles
    let protocol = r#"
        module multi_dynamic exposing (MultiDynamicRoles)
        protocol MultiDynamicRoles =
            roles Controller, StaticWorkers[3], DynamicWorkers[*], SymbolicWorkers[M]

            Controller -> StaticWorkers[0] : StaticTask
            Controller -> DynamicWorkers[*] : DynamicTask
            Controller -> SymbolicWorkers[*] : SymbolicTask

            StaticWorkers[0] -> Controller : StaticResult
            DynamicWorkers[0..response_count] -> Controller : DynamicResult
            SymbolicWorkers[i] -> Controller : SymbolicResult
    "#;

    let choreo = parse_choreography_str(protocol).expect("Multi-dynamic protocol should parse");

    assert_eq!(choreo.roles.len(), 4);

    let controller = &choreo.roles[0];
    let static_workers = &choreo.roles[1];
    let dynamic_workers = &choreo.roles[2];
    let symbolic_workers = &choreo.roles[3];

    // Verify role characteristics
    assert!(!controller.is_parameterized());
    assert!(
        static_workers.is_parameterized()
            && !static_workers.is_dynamic()
            && !static_workers.is_symbolic()
    );
    assert!(dynamic_workers.is_dynamic());
    assert!(symbolic_workers.is_symbolic());

    // Test validation
    assert!(controller.validate().is_ok());
    assert!(static_workers.validate().is_ok());
    assert!(dynamic_workers.validate().is_ok());
    assert!(symbolic_workers.validate().is_ok());

    // Test dynamic support generation
    let dynamic_support = generate_dynamic_role_support(&choreo);
    let code_str = dynamic_support.to_string();

    // Should generate support for dynamic and symbolic roles
    assert!(code_str.contains("validate_dynamicworkers_count"));
    assert!(code_str.contains("validate_symbolicworkers_count"));
    // Should NOT generate for static roles
    assert!(!code_str.contains("validate_staticworkers_count"));
}

#[test]
fn test_nested_choices() {
    // Test complex nested structures without annotations
    let protocol = r#"
        module nested_complex exposing (NestedProtocol)
        protocol NestedProtocol =
            roles Client, Server, Database

            Client -> Server : StartSession

            choice Server at
                | authenticate =>
                    Server -> Database : AuthQuery

                    choice Database at
                        | success =>
                            Database -> Server : AuthSuccess
                            Server -> Client : AuthToken
                        | failure =>
                            Database -> Server : AuthFailure
                            Server -> Client : AuthDenied
                | reject =>
                    Server -> Client : Rejected
    "#;

    let choreo = parse_choreography_str(protocol).expect("Nested protocol should parse");

    // Basic structure verification
    assert_eq!(choreo.namespace.as_ref().unwrap(), "nested_complex");
    assert_eq!(choreo.roles.len(), 3);

    // Test projection handles complex structure
    for role in &choreo.roles {
        let local_type = project(&choreo, role).expect("Projection should handle nested choices");

        // Verify we get meaningful local types
        match local_type {
            LocalType::End => panic!("Should not get End for complex protocol"),
            LocalType::Send { .. }
            | LocalType::Receive { .. }
            | LocalType::Select { .. }
            | LocalType::Branch { .. } => {
                // Expected complex types
            }
            _ => {
                // Other types are also valid
            }
        }
    }
}

#[test]
fn test_error_handling_integration() {
    // Test that enhanced features maintain good error reporting

    // Test undefined role in dynamic context
    let invalid_protocol1 = r#"
        module error_test exposing (InvalidProtocol)
        protocol InvalidProtocol =
            roles A, B[*]
            A -> UndefinedRole : Message
    "#;

    let result1 = parse_choreography_str(invalid_protocol1);
    assert!(result1.is_err());

    // Test invalid dynamic role syntax
    let invalid_protocol3 = r#"
        protocol InvalidDynamic =
            roles A, B[invalid]
            A -> B[999999999] : Message
    "#;

    let result2 = parse_choreography_str(invalid_protocol3);
    assert!(result2.is_err());
}

#[test]
fn test_performance_characteristics() {
    // Test that enhanced features don't significantly impact performance
    use std::time::Instant;

    let complex_protocol = r#"
        module performance_test exposing (PerformanceTest)
        protocol PerformanceTest =
            roles Controller, Workers[*]

            Controller -> Workers[*] : StartWork
            Workers[0..batch_size] -> Controller : WorkComplete

            choice Controller at
                | continue =>
                    Controller -> Workers[*] : ContinueWork
                | stop =>
                    Controller -> Workers[*] : StopWork
    "#;

    let start = Instant::now();

    // Parse multiple times to test performance
    for _ in 0..100 {
        let choreo = parse_choreography_str(complex_protocol).expect("Should parse quickly");

        // Quick validation
        assert_eq!(choreo.namespace.as_ref().unwrap(), "performance_test");
        assert_eq!(choreo.roles.len(), 2);

        // Test projection performance
        for role in &choreo.roles {
            drop(project(&choreo, role)); // May fail for dynamic roles, but should be fast
        }
    }

    let duration = start.elapsed();

    // Log timing for observability but do not assert on wall-clock duration.
    // Wall-clock budgets are inherently non-deterministic and belong in
    // dedicated benchmark lanes (`just bench-check`), not in the workspace
    // test suite where debug-mode variance and CI load cause flaky failures.
    println!(
        "Performance test completed 100 iterations in {:?}",
        duration
    );
}

#[test]
fn test_full_compilation_pipeline() {
    // Test end-to-end compilation of enhanced features
    let protocol = r#"
        module compilation_test exposing (CompilationTest)
        protocol CompilationTest =
            roles Client, Servers[*], Database

            Client -> Servers[*] : Request
            Servers[i] -> Database : Query
            Database -> Servers[i] : Response
            Servers[0..quorum] -> Client : AggregatedResponse
    "#;

    let choreo = parse_choreography_str(protocol).expect("Protocol should parse");

    // Create local types (simplified for test)
    let local_types: Vec<(Role, LocalType)> = choreo
        .roles
        .iter()
        .map(|role| (role.clone(), LocalType::End))
        .collect();

    // Test full code generation
    let generated_code = generate_choreography_code_with_dynamic_roles(&choreo, &local_types);
    let code_str = generated_code.to_string();

    // Verify comprehensive code generation
    assert!(code_str.contains("CompilationTestRuntime"));
    assert!(code_str.contains("bind_role_count"));
    assert!(code_str.contains("validate_servers_count"));

    // Test that generated code is syntactically valid Rust
    // (This would require syn crate for full parsing, but we can check basic structure)
    assert!(code_str.contains("impl"));
    assert!(code_str.contains("pub struct"));
    assert!(code_str.contains("pub fn"));

    println!("Full compilation pipeline test completed successfully");
    println!("Generated code length: {} characters", code_str.len());
}