dk-engine 0.2.80

dkod code analysis engine — semantic parsing, indexing, and search
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use dk_core::SymbolKind;

/// A claim that a particular session has touched a symbol.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SymbolClaim {
    pub session_id: Uuid,
    pub agent_name: String,
    pub qualified_name: String,
    pub kind: SymbolKind,
    pub first_touched_at: DateTime<Utc>,
}

/// Information about a detected conflict: another session already claims
/// ownership of a symbol that the current session wants to modify.
#[derive(Debug, Clone)]
pub struct ConflictInfo {
    pub qualified_name: String,
    pub kind: SymbolKind,
    pub conflicting_session: Uuid,
    pub conflicting_agent: String,
    pub first_touched_at: DateTime<Utc>,
}

/// Information about a symbol lock held by another session.
/// Returned when `acquire_lock` finds the symbol is already locked.
#[derive(Debug, Clone)]
pub struct SymbolLocked {
    pub qualified_name: String,
    pub kind: SymbolKind,
    pub locked_by_session: Uuid,
    pub locked_by_agent: String,
    pub locked_since: DateTime<Utc>,
    pub file_path: String,
}

/// Outcome of a successful `acquire_lock` call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AcquireOutcome {
    /// Lock freshly acquired — include in rollback list.
    Fresh,
    /// Session already held this lock — exclude from rollback.
    ReAcquired,
}

/// Result of releasing locks for a session. Contains the symbols that
/// were released, so callers can emit `symbol.lock.released` events.
#[derive(Debug, Clone)]
pub struct ReleasedLock {
    pub file_path: String,
    pub qualified_name: String,
    pub kind: SymbolKind,
    pub agent_name: String,
}

// ---------------------------------------------------------------------------
// ClaimTracker trait
// ---------------------------------------------------------------------------

/// Async trait for symbol-level claim tracking across sessions.
///
/// Implementations:
/// - [`LocalClaimTracker`] — in-memory DashMap (single-pod / tests)
/// - `ValkeyClaimTracker` — Valkey/Redis-backed (multi-pod, behind `valkey` feature)
#[async_trait]
pub trait ClaimTracker: Send + Sync {
    /// Record a symbol claim (non-blocking — does not reject on conflict).
    async fn record_claim(&self, repo_id: Uuid, file_path: &str, claim: SymbolClaim);

    /// Attempt to acquire a symbol lock. Returns `Err(SymbolLocked)` if
    /// another session already holds the symbol.
    async fn acquire_lock(
        &self,
        repo_id: Uuid,
        file_path: &str,
        claim: SymbolClaim,
    ) -> Result<AcquireOutcome, SymbolLocked>;

    /// Release a single symbol lock for a session in a specific file.
    async fn release_lock(
        &self,
        repo_id: Uuid,
        file_path: &str,
        session_id: Uuid,
        qualified_name: &str,
    );

    /// Release all locks held by a session for a specific repo.
    async fn release_locks(&self, repo_id: Uuid, session_id: Uuid) -> Vec<ReleasedLock>;

    /// Check whether any of the given symbols conflict with another session.
    async fn check_conflicts(
        &self,
        repo_id: Uuid,
        file_path: &str,
        session_id: Uuid,
        qualified_names: &[String],
    ) -> Vec<ConflictInfo>;

    /// Return all conflicts for a session across all file paths.
    ///
    /// This method is only meaningful for the non-blocking `record_claim` path
    /// where multiple sessions can record overlapping claims without rejection.
    /// Backends that use exclusive locking (e.g. `ValkeyClaimTracker`) may
    /// return an empty list since cross-session conflicts are prevented at
    /// write time by `acquire_lock`.
    async fn get_all_conflicts_for_session(
        &self,
        repo_id: Uuid,
        session_id: Uuid,
    ) -> Vec<(String, ConflictInfo)>;

    /// Remove all claims belonging to a session across ALL repos.
    async fn clear_session(&self, session_id: Uuid) -> Vec<ReleasedLock>;
}

// ---------------------------------------------------------------------------
// LocalClaimTracker — in-memory DashMap implementation
// ---------------------------------------------------------------------------

/// Thread-safe, lock-free tracker for symbol-level claims across sessions.
///
/// Key insight: two sessions modifying DIFFERENT symbols in the same file is
/// NOT a conflict. Only same-symbol modifications across sessions are TRUE
/// conflicts. This is dkod's core differentiator over line-based VCS.
///
/// The tracker is keyed by `(repo_id, file_path)` and stores a `Vec<SymbolClaim>`
/// for each file. DashMap provides fine-grained per-shard locking so reads are
/// effectively lock-free when not contending on the same shard.
pub struct LocalClaimTracker {
    /// Map from (repo_id, file_path) to the list of claims on that file.
    claims: DashMap<(Uuid, String), Vec<SymbolClaim>>,
}

impl LocalClaimTracker {
    pub fn new() -> Self {
        Self {
            claims: DashMap::new(),
        }
    }
}

impl Default for LocalClaimTracker {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl ClaimTracker for LocalClaimTracker {
    async fn record_claim(&self, repo_id: Uuid, file_path: &str, claim: SymbolClaim) {
        let key = (repo_id, file_path.to_string());
        let mut entry = self.claims.entry(key).or_default();
        let claims = entry.value_mut();

        if let Some(existing) = claims.iter_mut().find(|c| {
            c.session_id == claim.session_id && c.qualified_name == claim.qualified_name
        }) {
            existing.kind = claim.kind;
            existing.agent_name = claim.agent_name;
        } else {
            claims.push(claim);
        }
    }

    async fn acquire_lock(
        &self,
        repo_id: Uuid,
        file_path: &str,
        claim: SymbolClaim,
    ) -> Result<AcquireOutcome, SymbolLocked> {
        let key = (repo_id, file_path.to_string());
        let mut entry = self.claims.entry(key).or_default();
        let claims = entry.value_mut();

        if let Some(existing) = claims.iter().find(|c| {
            c.qualified_name == claim.qualified_name && c.session_id != claim.session_id
        }) {
            return Err(SymbolLocked {
                qualified_name: claim.qualified_name,
                kind: existing.kind.clone(),
                locked_by_session: existing.session_id,
                locked_by_agent: existing.agent_name.clone(),
                locked_since: existing.first_touched_at,
                file_path: file_path.to_string(),
            });
        }

        if let Some(existing) = claims.iter_mut().find(|c| {
            c.session_id == claim.session_id && c.qualified_name == claim.qualified_name
        }) {
            existing.kind = claim.kind;
            existing.agent_name = claim.agent_name;
            return Ok(AcquireOutcome::ReAcquired);
        }

        claims.push(claim);
        Ok(AcquireOutcome::Fresh)
    }

    async fn release_lock(
        &self,
        repo_id: Uuid,
        file_path: &str,
        session_id: Uuid,
        qualified_name: &str,
    ) {
        let key = (repo_id, file_path.to_string());
        if let Some(mut entry) = self.claims.get_mut(&key) {
            entry.value_mut().retain(|c| {
                !(c.session_id == session_id && c.qualified_name == qualified_name)
            });
        }
        self.claims.remove_if(&key, |_, v| v.is_empty());
    }

    async fn release_locks(&self, repo_id: Uuid, session_id: Uuid) -> Vec<ReleasedLock> {
        let mut released = Vec::new();
        let mut empty_keys = Vec::new();

        for mut entry in self.claims.iter_mut() {
            let key = entry.key().clone();
            if key.0 != repo_id {
                continue;
            }
            let file_path = &key.1;
            let claims = entry.value_mut();

            for claim in claims.iter().filter(|c| c.session_id == session_id) {
                released.push(ReleasedLock {
                    file_path: file_path.clone(),
                    qualified_name: claim.qualified_name.clone(),
                    kind: claim.kind.clone(),
                    agent_name: claim.agent_name.clone(),
                });
            }

            claims.retain(|c| c.session_id != session_id);
            if claims.is_empty() {
                empty_keys.push(key);
            }
        }

        for key in empty_keys {
            self.claims.remove_if(&key, |_, v| v.is_empty());
        }

        released
    }

    async fn check_conflicts(
        &self,
        repo_id: Uuid,
        file_path: &str,
        session_id: Uuid,
        qualified_names: &[String],
    ) -> Vec<ConflictInfo> {
        let key = (repo_id, file_path.to_string());
        let Some(entry) = self.claims.get(&key) else {
            return Vec::new();
        };

        let mut conflicts = Vec::new();
        for name in qualified_names {
            for claim in entry.value() {
                if claim.qualified_name == *name && claim.session_id != session_id {
                    conflicts.push(ConflictInfo {
                        qualified_name: name.clone(),
                        kind: claim.kind.clone(),
                        conflicting_session: claim.session_id,
                        conflicting_agent: claim.agent_name.clone(),
                        first_touched_at: claim.first_touched_at,
                    });
                    break;
                }
            }
        }
        conflicts
    }

    async fn get_all_conflicts_for_session(
        &self,
        repo_id: Uuid,
        session_id: Uuid,
    ) -> Vec<(String, ConflictInfo)> {
        let mut results = Vec::new();
        for entry in self.claims.iter() {
            let (entry_repo_id, file_path) = entry.key();
            if *entry_repo_id != repo_id {
                continue;
            }
            let claims = entry.value();

            let my_symbols: Vec<&SymbolClaim> = claims
                .iter()
                .filter(|c| c.session_id == session_id)
                .collect();

            for my_claim in &my_symbols {
                for other_claim in claims {
                    if other_claim.session_id != session_id
                        && other_claim.qualified_name == my_claim.qualified_name
                    {
                        results.push((
                            file_path.clone(),
                            ConflictInfo {
                                qualified_name: my_claim.qualified_name.clone(),
                                kind: my_claim.kind.clone(),
                                conflicting_session: other_claim.session_id,
                                conflicting_agent: other_claim.agent_name.clone(),
                                first_touched_at: other_claim.first_touched_at,
                            },
                        ));
                        break;
                    }
                }
            }
        }
        results
    }

    async fn clear_session(&self, session_id: Uuid) -> Vec<ReleasedLock> {
        let mut released = Vec::new();
        let mut empty_keys = Vec::new();
        for mut entry in self.claims.iter_mut() {
            let key = entry.key().clone();
            let file_path = &key.1;
            let claims = entry.value_mut();

            for claim in claims.iter().filter(|c| c.session_id == session_id) {
                released.push(ReleasedLock {
                    file_path: file_path.clone(),
                    qualified_name: claim.qualified_name.clone(),
                    kind: claim.kind.clone(),
                    agent_name: claim.agent_name.clone(),
                });
            }

            claims.retain(|c| c.session_id != session_id);
            if claims.is_empty() {
                empty_keys.push(key);
            }
        }
        for key in empty_keys {
            self.claims.remove_if(&key, |_, v| v.is_empty());
        }
        released
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_claim(session_id: Uuid, agent: &str, name: &str, kind: SymbolKind) -> SymbolClaim {
        SymbolClaim {
            session_id,
            agent_name: agent.to_string(),
            qualified_name: name.to_string(),
            kind,
            first_touched_at: Utc::now(),
        }
    }

    #[tokio::test]
    async fn no_conflict_different_symbols_same_file() {
        let tracker = LocalClaimTracker::new();
        let repo = Uuid::new_v4();
        let session_a = Uuid::new_v4();
        let session_b = Uuid::new_v4();

        tracker
            .record_claim(
                repo,
                "src/lib.rs",
                make_claim(session_a, "agent-1", "fn_a", SymbolKind::Function),
            )
            .await;

        let conflicts = tracker
            .check_conflicts(repo, "src/lib.rs", session_b, &["fn_b".to_string()])
            .await;
        assert!(conflicts.is_empty(), "different symbols should not conflict");
    }

    #[tokio::test]
    async fn conflict_same_symbol() {
        let tracker = LocalClaimTracker::new();
        let repo = Uuid::new_v4();
        let session_a = Uuid::new_v4();
        let session_b = Uuid::new_v4();

        tracker
            .record_claim(
                repo,
                "src/lib.rs",
                make_claim(session_a, "agent-1", "fn_a", SymbolKind::Function),
            )
            .await;

        let conflicts = tracker
            .check_conflicts(repo, "src/lib.rs", session_b, &["fn_a".to_string()])
            .await;
        assert_eq!(conflicts.len(), 1);
        assert_eq!(conflicts[0].qualified_name, "fn_a");
        assert_eq!(conflicts[0].conflicting_session, session_a);
        assert_eq!(conflicts[0].conflicting_agent, "agent-1");
    }

    #[tokio::test]
    async fn claims_cleared_on_session_destroy() {
        let tracker = LocalClaimTracker::new();
        let repo = Uuid::new_v4();
        let session_a = Uuid::new_v4();
        let session_b = Uuid::new_v4();

        tracker
            .record_claim(
                repo,
                "src/lib.rs",
                make_claim(session_a, "agent-1", "fn_a", SymbolKind::Function),
            )
            .await;

        tracker.clear_session(session_a).await;

        let conflicts = tracker
            .check_conflicts(repo, "src/lib.rs", session_b, &["fn_a".to_string()])
            .await;
        assert!(
            conflicts.is_empty(),
            "cleared session should not cause conflicts"
        );
    }

    #[tokio::test]
    async fn same_session_no_self_conflict() {
        let tracker = LocalClaimTracker::new();
        let repo = Uuid::new_v4();
        let session_a = Uuid::new_v4();

        tracker
            .record_claim(
                repo,
                "src/lib.rs",
                make_claim(session_a, "agent-1", "fn_a", SymbolKind::Function),
            )
            .await;
        tracker
            .record_claim(
                repo,
                "src/lib.rs",
                make_claim(session_a, "agent-1", "fn_a", SymbolKind::Function),
            )
            .await;

        let conflicts = tracker
            .check_conflicts(repo, "src/lib.rs", session_a, &["fn_a".to_string()])
            .await;
        assert!(
            conflicts.is_empty(),
            "same session should not conflict with itself"
        );
    }

    #[tokio::test]
    async fn multiple_conflicts() {
        let tracker = LocalClaimTracker::new();
        let repo = Uuid::new_v4();
        let session_a = Uuid::new_v4();
        let session_b = Uuid::new_v4();

        tracker
            .record_claim(
                repo,
                "src/lib.rs",
                make_claim(session_a, "agent-1", "fn_a", SymbolKind::Function),
            )
            .await;
        tracker
            .record_claim(
                repo,
                "src/lib.rs",
                make_claim(session_a, "agent-1", "fn_b", SymbolKind::Function),
            )
            .await;

        let conflicts = tracker
            .check_conflicts(
                repo,
                "src/lib.rs",
                session_b,
                &["fn_a".to_string(), "fn_b".to_string()],
            )
            .await;
        assert_eq!(conflicts.len(), 2);

        let names: Vec<&str> = conflicts.iter().map(|c| c.qualified_name.as_str()).collect();
        assert!(names.contains(&"fn_a"));
        assert!(names.contains(&"fn_b"));
    }

    #[tokio::test]
    async fn acquire_lock_unclaimed_succeeds() {
        let tracker = LocalClaimTracker::new();
        let repo = Uuid::new_v4();
        let session = Uuid::new_v4();

        let result = tracker
            .acquire_lock(
                repo,
                "src/lib.rs",
                make_claim(session, "agent-1", "fn_a", SymbolKind::Function),
            )
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn acquire_lock_same_session_succeeds() {
        let tracker = LocalClaimTracker::new();
        let repo = Uuid::new_v4();
        let session = Uuid::new_v4();

        tracker
            .acquire_lock(
                repo,
                "src/lib.rs",
                make_claim(session, "agent-1", "fn_a", SymbolKind::Function),
            )
            .await
            .unwrap();

        let result = tracker
            .acquire_lock(
                repo,
                "src/lib.rs",
                make_claim(session, "agent-1", "fn_a", SymbolKind::Function),
            )
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn acquire_lock_cross_session_blocked() {
        let tracker = LocalClaimTracker::new();
        let repo = Uuid::new_v4();
        let session_a = Uuid::new_v4();
        let session_b = Uuid::new_v4();

        tracker
            .acquire_lock(
                repo,
                "src/lib.rs",
                make_claim(session_a, "agent-1", "fn_a", SymbolKind::Function),
            )
            .await
            .unwrap();

        let result = tracker
            .acquire_lock(
                repo,
                "src/lib.rs",
                make_claim(session_b, "agent-2", "fn_a", SymbolKind::Function),
            )
            .await;
        assert!(result.is_err());
        let locked = result.unwrap_err();
        assert_eq!(locked.qualified_name, "fn_a");
        assert_eq!(locked.locked_by_session, session_a);
        assert_eq!(locked.locked_by_agent, "agent-1");
    }

    #[tokio::test]
    async fn acquire_lock_different_symbols_same_file() {
        let tracker = LocalClaimTracker::new();
        let repo = Uuid::new_v4();
        let session_a = Uuid::new_v4();
        let session_b = Uuid::new_v4();

        tracker
            .acquire_lock(
                repo,
                "src/lib.rs",
                make_claim(session_a, "agent-1", "fn_a", SymbolKind::Function),
            )
            .await
            .unwrap();

        let result = tracker
            .acquire_lock(
                repo,
                "src/lib.rs",
                make_claim(session_b, "agent-2", "fn_b", SymbolKind::Function),
            )
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn release_lock_single_symbol() {
        let tracker = LocalClaimTracker::new();
        let repo = Uuid::new_v4();
        let session_a = Uuid::new_v4();
        let session_b = Uuid::new_v4();

        tracker
            .acquire_lock(
                repo,
                "src/lib.rs",
                make_claim(session_a, "agent-1", "fn_a", SymbolKind::Function),
            )
            .await
            .unwrap();

        tracker
            .release_lock(repo, "src/lib.rs", session_a, "fn_a")
            .await;

        let result = tracker
            .acquire_lock(
                repo,
                "src/lib.rs",
                make_claim(session_b, "agent-2", "fn_a", SymbolKind::Function),
            )
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn release_lock_cleans_empty_entries() {
        let tracker = LocalClaimTracker::new();
        let repo = Uuid::new_v4();
        let session = Uuid::new_v4();

        tracker
            .acquire_lock(
                repo,
                "src/lib.rs",
                make_claim(session, "agent-1", "fn_a", SymbolKind::Function),
            )
            .await
            .unwrap();

        tracker
            .release_lock(repo, "src/lib.rs", session, "fn_a")
            .await;

        let key = (repo, "src/lib.rs".to_string());
        assert!(tracker.claims.get(&key).is_none());
    }

    #[tokio::test]
    async fn release_locks_returns_released_entries() {
        let tracker = LocalClaimTracker::new();
        let repo = Uuid::new_v4();
        let session = Uuid::new_v4();

        tracker
            .acquire_lock(
                repo,
                "src/lib.rs",
                make_claim(session, "agent-1", "fn_a", SymbolKind::Function),
            )
            .await
            .unwrap();
        tracker
            .acquire_lock(
                repo,
                "src/api.rs",
                make_claim(session, "agent-1", "handler", SymbolKind::Function),
            )
            .await
            .unwrap();

        let released = tracker.release_locks(repo, session).await;
        assert_eq!(released.len(), 2);

        let names: Vec<&str> = released.iter().map(|r| r.qualified_name.as_str()).collect();
        assert!(names.contains(&"fn_a"));
        assert!(names.contains(&"handler"));
    }

    #[tokio::test]
    async fn release_locks_unblocks_other_session() {
        let tracker = LocalClaimTracker::new();
        let repo = Uuid::new_v4();
        let session_a = Uuid::new_v4();
        let session_b = Uuid::new_v4();

        tracker
            .acquire_lock(
                repo,
                "src/lib.rs",
                make_claim(session_a, "agent-1", "fn_a", SymbolKind::Function),
            )
            .await
            .unwrap();

        assert!(tracker
            .acquire_lock(
                repo,
                "src/lib.rs",
                make_claim(session_b, "agent-2", "fn_a", SymbolKind::Function),
            )
            .await
            .is_err());

        tracker.release_locks(repo, session_a).await;

        assert!(tracker
            .acquire_lock(
                repo,
                "src/lib.rs",
                make_claim(session_b, "agent-2", "fn_a", SymbolKind::Function),
            )
            .await
            .is_ok());
    }
}