Skip to main content
    Ivy Biosciences Docs/Call the platform/API/Sessions API/Sync protocol

    Sync protocol

    Version vectors, conflict resolution, and offline-first sync for sessions

    sessionssyncversion-vectors

    This endpoint reconciles changes made to the same session from more than one place — for example an offline client that edited messages while the server moved on. Reach for it when you support offline-first or multi-device editing and need to push accumulated changes, pull what you missed, and let the server detect and resolve any conflicts. It builds on the sessions you create in Manage sessions; if a sync goes the wrong way, Checkpoints let you roll back.

    Difficulty

    advanced

    Time

    15 min

    Sync Protocol


    Request

    POST /api/v1/sessions/:sessionId/sync.

    clientIdstringrequired

    Client identifier for version vector attribution

    localVersionnumberrequired

    The session version the client last saw

    localVectorVersionVectorrequired

    The client's current version vector

    localChangesSessionChange[]

    Changes made on the client since the last sync

    modestringdefault: merge

    Sync strategy: merge (default), force_local, or force_remote

    A request missing clientId, localVersion or localVector returns 400.

    Example Request

    curl -X POST "https://www.ivybiosciences.com/api/v1/sessions/$SESSION_ID/sync" \
      -H "Authorization: Bearer ivy_your_key" \
      -H "Content-Type: application/json" \
      -d '{
        "mode": "merge",
        "clientId": "web_1709856000000",
        "localVersion": 3,
        "localVector": {"web_1709856000000": 3},
        "localChanges": [
          {
            "id": "msg_003",
            "type": "message",
            "operation": "add",
            "path": "messages",
            "value": {
              "id": "msg_003",
              "role": "user",
              "content": [{"type": "text", "text": "Follow up question"}]
            },
            "timestamp": {"wallTime": 1709856400000, "logical": 0, "clientId": "web_1709856000000"}
          }
        ]
      }'

    Response

    Every successful call returns 200 with a SyncResponse:

    FieldMeaning
    statussuccess or conflict
    newVersionThe session version after the sync
    newVectorThe server's version vector after the sync
    remoteChangesChanges for the client to apply (currently always [])
    conflictsPresent when status is conflict
    fullStateThe server's full SessionState when the client should replace its copy
    {
      "status": "success",
      "newVersion": 4,
      "newVector": { "web_1709856000000": 4, "api_1709856100000": 2 },
      "remoteChanges": []
    }

    Version Vectors

    Each session carries a version vector: a map from clientId to the latest version that client wrote. Comparing two vectors shows whether one side has changes the other has not seen.

    type VersionVector = Record<string, number>
    
    interface HybridTimestamp {
      wallTime: number   // Milliseconds since epoch
      logical: number    // Counter for same-millisecond ordering
      clientId: string   // Client that produced the timestamp
    }

    Comparison

    compareVectors returns the relationship between two vectors, and the route branches on it:

    import { compareVectors } from "@pleach/core/sync"
    
    const result = compareVectors(localVector, serverVector)
    // Returns: "equal" | "a_dominates" | "b_dominates" | "concurrent"
    ResultMeaningWhat the route does
    equalNeither side has unseen changesReturns success with no changes
    a_dominatesThe client is aheadApplies localChanges
    b_dominatesThe server is aheadReturns fullState for the client to adopt
    concurrentBoth sides have unseen changesChecks for conflicts, then applies last-writer-wins

    Available Sync Functions

    import {
      compareVectors,    // Compare two version vectors
      mergeVectors,      // Merge two vectors (max of each component)
      incrementVersion,  // Increment a client's entry
      hasSeen,           // Has vector A seen everything in vector B?
      getMissing,        // Entries B has that A lacks
      emptyVector,       // An empty vector
      createVector,      // An initial vector for a new client
      HybridLogicalClock,
      SyncCoordinator,   // Client-side sync loop with an outbox
    } from "@pleach/core/sync"

    SessionChange

    Changes are the units of sync. Each change targets one entity type with one operation.

    interface SessionChange {
      id?: string
      type: "message" | "tool_call" | "job" | "artifact" | "config"
      operation: "add" | "update" | "delete"
      path: string
      value?: unknown
      timestamp: HybridTimestamp
    }

    Conflict Resolution

    Conflict detection covers message changes with operation: "update" only, and runs when the vectors are concurrent.

    • If an updated message differs between client and server, the route returns status: "conflict" with the conflicting paths and applies nothing. Resolve on the client and sync again.
    • Otherwise the route applies last-writer-wins on time: if the client's first change is newer than the session's updatedAt, the client's changes are applied and the vectors merged; if not, the server wins and the response carries fullState.

    Sync Modes

    ModeBehavior
    mergeDefault. Compare vectors and act as described above
    force_localApply the client's changes over the server state
    force_remoteDiscard the client's changes and return the server state

    Offline Workflow

    1. The client works offline, recording changes with local timestamps.
    2. On reconnect, it calls POST /sync with localVector and localChanges.
    3. The server compares vectors to find concurrent edits.
    4. A conflicting message edit comes back as status: "conflict"; otherwise the newer side wins.
    5. The client adopts newVector, and fullState when it is present.

    Was this page helpful?

    On this page

    On this page

    Loading...