Skip to content

Add Temporal Snapshot Conflict Resolution with HLC Integration for RPC Framework - #108

Merged
makr-code merged 4 commits into
mainfrom
copilot/add-hlc-integration-rpc-snapshot
Dec 18, 2025
Merged

makr-code merged 4 commits into
mainfrom
copilot/add-hlc-integration-rpc-snapshot

Conversation

Copilot AI commented Dec 17, 2025 •

Copy link
Copy Markdown
Contributor

RPC snapshot transfers lack conflict resolution when concurrent writes occur across nodes, leading to potential data loss (10-50% probability in high-throughput scenarios). This adds HLC-based temporal conflict resolution with pluggable strategies.

Implementation

Core Conflict Resolver

  • 5 resolution policies: LAST_WRITE_WINS (default), FIRST_WRITE_WINS, NODE_PRIORITY, MANUAL, CRDT_MERGE
  • Thread-safe with atomic statistics, mutex-protected conflict history
  • O(1) detection and resolution via three-tier HLC comparison (physical → logical → node_id)

HLC Comparison Operators

Implemented missing operator<, operator==, and toString() for HybridLogicalClock::Timestamp:

bool HybridLogicalClock::Timestamp::operator<(const Timestamp& other) const {
    if (physical != other.physical) return physical < other.physical;
    if (logical != other.logical) return logical < other.logical;
    return node_id < other.node_id;
}

Usage

#include "temporal/temporal_conflict_resolver.h"

TemporalConflictResolver resolver(ConflictPolicy::LAST_WRITE_WINS);

TemporalSnapshot local  = {.hlc = {1000, 5, "node_a"}, .data = {...}};
TemporalSnapshot remote = {.hlc = {1001, 3, "node_b"}, .data = {...}};

auto winner = resolver.resolve(local, remote);  // remote wins (newer)

// Manual resolution for critical data
resolver.setPolicy(ConflictPolicy::MANUAL);
auto conflicts = resolver.getUnresolvedConflicts();
resolver.resolveManually(conflicts[0].conflict_id, "remote");

Files

  • include/temporal/temporal_conflict_resolver.h - Policy enum, TemporalSnapshot, ConflictRecord, resolver class
  • src/temporal/temporal_conflict_resolver.cpp - All 5 policies, JSON serialization, statistics
  • src/replication/replication_manager.cpp - HLC operators implementation
  • tests/temporal/test_temporal_conflict_resolver.cpp - 14 test cases covering all policies
  • docs/plugins/TEMPORAL_SNAPSHOTS_CONSISTENCY.md - Integration guide, risk matrix, config examples

Notes

  • CRDT_MERGE currently falls back to LAST_WRITE_WINS (placeholder for future CRDT implementation)
  • Statistics use lock-free atomics; conflict history/manual queue use mutex
  • Memory: ~500 bytes per conflict record, 40 bytes statistics overhead
Original prompt

Temporal Snapshot Conflict Resolution mit HLC für RPC Framework

Hintergrund

ThemisDB hat bereits eine Hybrid Logical Clock (HLC) Implementierung in include/replication/multi_master_replication.h für Multi-Master Replikation. Allerdings fehlt die HLC-Integration im RPC Snapshot Transfer Framework (PR #104), was zu Kollisionen bei gleichzeitigen Datenänderungen führen kann.

Problem-Szenario (Ei-Henne-Problem):

// DB A sendet Snapshot an DB B
Thread 1 (DB A): sendSnapshot(entity_123, diff={field: "old" → "new_A"}) @ T=1000
Thread 2 (DB B): UPDATE entity_123 SET field="new_B" @ T=1000  // Gleichzeitig!

// DB B empfängt Snapshot kurz nach lokaler Änderung
// ❌ KONFLIKT: Welche Version gewinnt?

Risikomatrix - Eintrittswahrscheinlichkeit

Konflikt-Typ Wahrscheinlichkeit Impact Status
Multi-Master Concurrent Writes 10-40% 🔴 Datenverlust ✅ Gelöst (HLC+CRDT)
RPC Snapshot Transfer 10-50% 🔴 Inkonsistenz ❌ UNGEFIXED
Temporal Snapshot Merge 5-20% 🟡 Stale Reads ❌ UNGEFIXED
Cross-Shard 2PC 1-20% 🟡 Abort Rate ✅ Gelöst (TrueTime)

Anforderungen

1. HLC Integration in RPC Framework

Erweitere Protobuf Messages (falls vorhanden, sonst erstelle MessagePack-basierte Struktur):

message HybridLogicalClock {
    uint64 physical_time = 1;  // Milliseconds since epoch
    uint32 logical_counter = 2;
    string node_id = 3;
}

message SnapshotTransferRequest {
    bytes snapshot_data = 1;
    string source_shard_id = 2;
    string target_shard_id = 3;
    HybridLogicalClock source_hlc = 4;  // ✅ NEU
    optional VectorClock vector_clock = 5;  // ✅ Optional für Multi-Master
}

message VectorClock {
    map<string, uint64> clocks = 1;  // node_id → timestamp
}

Falls kein Protobuf vorhanden: Verwende MessagePack-Struktur ähnlich zu src/server/buffer_binary_protocol.cpp.

2. Temporal Conflict Resolver

Neue Dateien:

include/temporal/temporal_conflict_resolver.h

#pragma once

#include <chrono>
#include <string>
#include <vector>
#include <nlohmann/json.hpp>
#include "replication/multi_master_replication.h"  // Für HybridLogicalClock

namespace themis::temporal {

/**
 * Conflict Resolution Policy
 */
enum class ConflictPolicy {
    LAST_WRITE_WINS,      // Default: Höchste HLC gewinnt
    FIRST_WRITE_WINS,     // Niedrigste HLC gewinnt
    NODE_PRIORITY,        // Konfigurierte Node-Priorität (z.B. Node ID Tiebreaker)
    MANUAL,               // Conflict in Queue für manuelle Auflösung
    CRDT_MERGE            // Automatischer Merge via CRDT (falls unterstützt)
};

/**
 * Temporal Snapshot mit HLC-Versionierung
 */
struct TemporalSnapshot {
    std::string snapshot_id;
    replication::HybridLogicalClock::Timestamp hlc;
    std::string source_node_id;
    nlohmann::json data;
    std::string checksum;  // SHA-256
    
    nlohmann::json toJson() const;
    static std::optional<TemporalSnapshot> fromJson(const nlohmann::json& j);
};

/**
 * Conflict Record für Logging/Monitoring
 */
struct ConflictRecord {
    std::string conflict_id;
    std::string entity_id;
    TemporalSnapshot local_version;
    TemporalSnapshot remote_version;
    ConflictPolicy resolution_policy;
    std::string winner;  // "local" | "remote" | "merged"
    std::chrono::system_clock::time_point detected_at;
    bool resolved;
};

/**
 * Temporal Conflict Resolver
 * 
 * Löst Konflikte bei temporalen Snapshots basierend auf HLC-Timestamps.
 */
class TemporalConflictResolver {
public:
    explicit TemporalConflictResolver(ConflictPolicy default_policy = ConflictPolicy::LAST_WRITE_WINS);
    
    /**
     * Resolve conflict between local and remote snapshot
     * 
     * @param local Local snapshot version
     * @param remote Remote snapshot version
     * @param policy Override default policy (optional)
     * @return Winning snapshot (merged or selected)
     */
    TemporalSnapshot resolve(
        const TemporalSnapshot& local,
        const TemporalSnapshot& remote,
        std::optional<ConflictPolicy> policy = std::nullopt
    );
    
    /**
     * Get all unresolved conflicts (for MANUAL policy)
     */
    std::vector<ConflictRecord> getUnresolvedConflicts() const;
    
    /**
     * Manually resolve a conflict
     */
    void resolveManually(const std::string& conflict_id, const std::string& winner);
    
    /**
     * Get conflict statistics
     */
    nlohmann::json getStatistics() const;
    
private:
    ConflictPolicy default_policy_;
    std::vector<ConflictRecord> conflict_history_;
    std::map<std::string, ConflictRecord> unresolved_conflicts_;
    
    // Statistics
    std::atomic<uint64_t> total_conflicts_{0};
    std::atomic<uint64_t> lww_resolutions_{0};
    std::atomic<uint64_t> fww_resolutions_{0};
    std::atomic<uint64_t> manual_resolutions_{0};
    std::atomic<uint...

</details>



<!-- START COPILOT CODING AGENT SUFFIX -->

*This pull request was created from Copilot chat.*
>

<!-- START COPILOT CODING AGENT TIPS -->
---

💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more [Copilot coding agent tips](https://gh.io/copilot-coding-agent-tips) in the docs.

Copilot AI changed the title [WIP] Add HLC integration for RPC snapshot transfer Add Temporal Snapshot Conflict Resolution with HLC Integration for RPC Framework Dec 17, 2025
Copilot AI requested a review from makr-code December 17, 2025 21:13
@makr-code
makr-code marked this pull request as ready for review December 18, 2025 05:54
@makr-code
makr-code merged commit 866d17c into main Dec 18, 2025
@makr-code makr-code added this to the v1.0.2 milestone Mar 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants