Skip to content

Operational Runbook: Transaction Ledger Reconciliation and Recovery

This operational runbook provides authoritative standard operating procedures (SOP) for system administrators and operators managing Sortify (smart-autosorter) in headless batch processing and daemon environments.

When headless sorting jobs or background daemon tasks are interrupted—due to system restarts, process termination, hardware faults, or out-of-memory events—uncommitted file transitions may remain in the transaction ledger. This runbook details how to inspect ledger state, execute automated headless reconciliation, resolve conflicts across all terminal transaction statuses, and safely clean up stale lock files.


Table of Contents

  1. Architectural Overview
  2. Transaction Lifecycle and State Transitions
  3. CLI Reference and Practical Invocations
  4. Common Flags
  5. Inspecting Incomplete Transactions (status)
  6. Executing Automated Reconciliation (reconcile)
  7. Purging Ledger Records (purge)
  8. Exporting Audit Logs (export)
  9. Step-by-Step Resolution Paths for Failure Reasons
  10. RECONCILED_SUCCESS
  11. ABORTED
  12. FAILED_CONFLICT
  13. FAILED_MISSING
  14. Stale Daemon Lock and IPC Socket Recovery
  15. Lock Mechanics & File Locations
  16. CRITICAL WARNING: Active Process Safety
  17. Safe Verification & Cleanup Procedure
  18. Cross-References

Architectural Overview

Sortify implements an append-only canonical move ledger (moves table, ADR 0006) in the unified application store (sortify.db, ADR 0008) to guarantee filesystem integrity and prevent data loss during moves:

  • Unified Application Store: By default, the moves table lives inside ~/.autosorter/sortify.db (or $AUTOSORTER_APP_DIR/sortify.db). Existing historical records from older step_ledger, transaction_ledger, and sidecar transaction_ledger.db stores are automatically imported into moves during store migrations (app/core/store.py, app/core/moves.py).
  • Two-Phase Commit:
  • Intent Logging: Before moving any physical bytes on disk, Sortify commits an intent row (reported by CLI status as PENDING) via MoveLedger.record_intent in app/core/moves.py.
  • Physical Move & Verification: Any preexisting destination file is safely displaced before overwrite (ADR 0005), the file is moved on disk, and the row transitions to done and verified once content hashes match.
  • Failure & Interruption Handling: If a process crashes while a row is in intent (PENDING), the next startup or operator ledger reconcile command evaluates physical disk state against the recorded SHA-256 hash to roll forward (done) or record a structured terminal failure (ABORTED, FAILED_CONFLICT, or FAILED_MISSING).

Transaction Lifecycle and State Transitions

Defined in app/core/moves.py, MoveLedger persists four canonical states (intent, done, verified, failed) and surfaces operator-facing status codes in smart-autosorter ledger:

                  +-------------------------+
                  |    intent (PENDING)     |
                  +-------------------------+
                     /       |           \
                    /        |            \
                   v         |             v
      +----------------+     |       +-------------------+
      |      done      |     |       |      ABORTED      | (failed)
      +----------------+     |       +-------------------+
              |              |
              v              +------------------+
      +----------------+     |                  |
      |    verified    |     v                  v
      +----------------+ +-------------------+ +-------------------+
       (Completed)       |  FAILED_CONFLICT  | |  FAILED_MISSING   |
                         +-------------------+ +-------------------+

Status Definitions

Status Underlying moves.state Description
PENDING intent Move intent committed to moves prior to completing physical disk relocation.
COMPLETED / RECONCILED_SUCCESS done / verified File physically relocated on disk (and hash-verified or rolled forward during reconciliation) with document metadata updated.
ABORTED failed Move cancelled prior to physical transfer, or identical duplicate destination removed and source preserved.
FAILED_CONFLICT failed Reconciliation encountered both source and destination files with differing contents; both preserved to avoid loss.
FAILED_MISSING failed Reconciliation found that neither the source file nor destination file exists on disk.

Allowed State Transitions

Transitions are strictly validated by _ALLOWED_FROM in app/core/moves.py:

  • From intent (PENDING): Allowed to transition to done (including reconciled roll-forward) or failed (ABORTED, FAILED_CONFLICT, FAILED_MISSING, or move error).
  • From done: Allowed to transition to verified once destination SHA-256 matches src_sha256.
  • Terminal States: verified and failed allow no further state transitions. Records remain auditable in moves until explicitly purged.

CLI Reference and Practical Invocations

The smart-autosorter ledger command group is defined in app/cli/ledger_cli.py. Operators use these subcommands for non-interactive maintenance and batch session recovery.

Common Flags

These flags apply to smart-autosorter ledger and all its subcommands:

  • --ledger-db PATH: Optional path to a standalone SQLite database file containing a moves table. Defaults to the unified application store (~/.autosorter/sortify.db or $AUTOSORTER_APP_DIR/sortify.db).
  • -q, --quiet: Suppress human-readable informational banners and status summaries.
  • --no-color: Disable ANSI color escape codes (recommended for cron and headless log collection).
  • --json: Output response payloads in structured, machine-parseable JSON format on standard output.

Inspecting Incomplete Transactions (status)

Inspect pending, interrupted, or failed transaction entries currently recorded in the ledger.

Flags for status

  • --session-id SESSION_ID: Filter results to entries associated with a specific batch session identifier.
  • --failed: Filter exclusively for failed and aborted transaction records (FAILED_CONFLICT, FAILED_MISSING, ABORTED).
  • --aborted: Filter exclusively for aborted transaction records (ABORTED).
  • --json: Return structured JSON array of pending entries.
  • --ledger-db PATH: Target an alternate ledger database file.
  • -q, --quiet: Omit the header summary line.
  • --no-color: Suppress ANSI color codes.

Practical Examples

  1. Check all incomplete, pending, or failed entries across all sessions:

    smart-autosorter ledger status
    
    Example Output:
    Transaction Ledger Status: 2 pending, incomplete, or failed entry(ies).
      [PENDING] sess_9a8b1c:docs/invoices/inv_101.pdf | Source: /data/staging/inv_101.pdf -> Dest: /data/sorted/Finance/inv_101.pdf
      [FAILED_CONFLICT] sess_9a8b1c:docs/reports/annual.pdf | Source: /data/staging/annual.pdf -> Dest: /data/sorted/Reports/annual.pdf | Reason: Destination file exists and content differs from source; both files preserved.
    

  2. Filter by specific session ID:

    smart-autosorter ledger status --session-id "sess_9a8b1c"
    

  3. Filter exclusively for failed or conflicted records:

    smart-autosorter ledger status --failed
    

  4. Structured JSON output for pipeline automation:

    smart-autosorter ledger status --json
    
    Example JSON Output:
    {
      "status": "success",
      "count": 1,
      "pending_entries": [
        {
          "entry_id": "sess_9a8b1c:docs/reports/annual.pdf",
          "session_id": "sess_9a8b1c",
          "base_dir": "/data/staging",
          "source_path": "/data/staging/annual.pdf",
          "dest_path": "/data/sorted/Reports/annual.pdf",
          "source_rel_path": "docs/reports/annual.pdf",
          "dest_rel_path": "Reports/annual.pdf",
          "current_dest": "Reports/annual.pdf",
          "file_hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
          "status": "FAILED_CONFLICT",
          "created_at": 1731715200.0,
          "updated_at": 1731715205.0,
          "failure_reason": "Destination file exists and content differs from source; both files preserved."
        }
      ]
    }
    


Executing Automated Reconciliation (reconcile)

Reconciliation scans all non-terminal transactions (PENDING and MOVED_PHYSICAL), queries actual physical filesystem state, aligns database records, updates terminal statuses, and purges completed entries.

Flags for reconcile

  • --ledger-db PATH: Target a custom ledger database file.
  • --json: Output result as a JSON dictionary {"status": "success", "reconciled_count": <int>}.
  • -q, --quiet: Suppress confirmation prints to stderr.
  • --no-color: Disable color output.

Practical Examples

  1. Standard headless reconciliation:

    smart-autosorter ledger reconcile
    
    Example Output:
    Transaction ledger reconciliation completed. Reconciled 2 entry(ies).
    

  2. Headless cron execution with JSON telemetry:

    smart-autosorter ledger reconcile --json --quiet
    
    Example JSON Output:
    {
      "status": "success",
      "reconciled_count": 2
    }
    


Purging Ledger Records (purge)

Remove finalized, completed, aborted, or failed transaction entries from the sidecar database once operational review or audits are complete.

Flags for purge

  • --session-id SESSION_ID: Limit purge to records belonging to a specific session ID.
  • --completed: Purge all entries with status COMPLETED and RECONCILED_SUCCESS.
  • --failed: Purge all entries with status FAILED_CONFLICT, FAILED_MISSING, and ABORTED.
  • --aborted: Purge specifically entries with status ABORTED.
  • --force: Bypass the interactive confirmation prompt (Are you sure you want to purge transaction ledger records? [y/N]). Mandatory for scripts, CI, and non-interactive environments without a TTY.
  • --json: Output JSON confirmation payload.
  • --ledger-db PATH: Target custom ledger database.
  • -q, --quiet: Suppress informational messages.
  • --no-color: Disable color output.

Practical Examples

  1. Purge all completed records across all sessions:

    smart-autosorter ledger purge --completed
    

  2. Non-interactive batch script purge with --force:

    smart-autosorter ledger purge --session-id "sess_9a8b1c" --failed --force --json
    
    Example JSON Output:
    {
      "status": "success",
      "message": "Transaction ledger records purged successfully.",
      "session_id": "sess_9a8b1c",
      "completed_only": false,
      "failed_only": true,
      "aborted_only": false
    }
    

  3. Purge all aborted transactions without touching conflicted or missing records:

    smart-autosorter ledger purge --aborted --force
    


Exporting Audit Logs (export)

Export session history and transaction audit logs from the application database for compliance, auditing, or forensic analysis.

Flags for export

  • --session-id SESSION_ID: Export records for a specific session ID (exports all historical records if omitted).
  • -o, --output PATH: Specify output file path (defaults to audit_log_<session_id or 'all'>.csv or .json).
  • -f, --format {csv,json}: Explicit export format.
  • --csv: Shorthand convenience flag to export in CSV format.
  • --json: Output execution summary in JSON format to stdout.
  • --ledger-db PATH: Target custom ledger database.
  • -q, --quiet: Suppress informational prints to stderr.
  • --no-color: Disable color output.

Practical Examples

  1. Export session audit trail to CSV:

    smart-autosorter ledger export --session-id "sess_9a8b1c" --csv -o /var/log/sortify/audit_sess_9a8b1c.csv
    
    Example Output:
    Audit log exported (CSV) to '/var/log/sortify/audit_sess_9a8b1c.csv'. 48 record(s) written.
    

  2. Export all sessions to JSON formatted audit report:

    smart-autosorter ledger export --format json -o /var/log/sortify/full_audit.json --json
    


Step-by-Step Resolution Paths for Failure Reasons

When reconciliation executes, transactions evaluate to one of four terminal outcomes. Follow these procedures to resolve each case safely.

                    Reconciliation Evaluation
                                |
             +------------------+------------------+
             |                                     |
    Source missing?                       Source exists?
             |                                     |
     +-------+-------+                     +-------+-------+
     |               |                     |               |
Destination     Destination           Destination     Destination
  exists?         missing?              missing?        exists?
     |               |                     |               |
     v               v                     v               v
RECONCILED_     FAILED_MISSING          ABORTED        Check Content
 SUCCESS     (Files disappeared)    (Move aborted;        Match?
(Roll forward                         Source kept)         |
  database)                                        +-------+-------+
                                                   |               |
                                              Identical?       Different?
                                                   |               |
                                                   v               v
                                                ABORTED     FAILED_CONFLICT
                                              (Duplicate    (Both files kept;
                                               removed)     operator triage)

RECONCILED_SUCCESS

  • Condition: Physical move completed (MOVED_PHYSICAL or destination file exists on disk while source file is gone).
  • Automated Action: Reconciliation automatically rolls forward the main application database record (update_document_path and set_user_verified_target) to point to the destination path.
  • Operator Action Required: None. The move succeeded on disk, and the database now reflects the new location. Completed entries are purged automatically by reconcile.

ABORTED

An aborted state occurs under two distinct scenarios:

Scenario A: Move aborted prior to physical move

  • Reason String: "Move aborted prior to physical file move; source file preserved at origin."
  • Condition: Status was PENDING. Source file exists at its original path; destination file does not exist.
  • Cause: Daemon process was terminated before filesystem operations commenced.
  • Resolution Path:
  • Confirm source file presence:
    ls -la "/data/staging/file.pdf"
    
  • The database retains the source file path. The source file is completely intact.
  • Re-queue or re-run sorting on the source directory:
    smart-autosorter sort /data/staging
    
  • Purge the aborted ledger entry:
    smart-autosorter ledger purge --aborted --force
    

Scenario B: Duplicate destination safely removed

  • Reason String: "Incomplete move left duplicate destination; duplicate removed and source preserved."
  • Condition: Both source and destination files existed, and same_file_content confirmed they were byte-identical (or hard-linked).
  • Automated Action: Reconciliation safely deleted the duplicate file at destination and preserved the source file at origin. Database was kept pointing to the source.
  • Resolution Path: Verify source file integrity and re-sort when ready.

FAILED_CONFLICT

A conflict failure indicates that Sortify prevented silent data overwrite or data loss.

Scenario A: Destination file exists with differing content

  • Reason String: "Destination file exists and content differs from source; both files preserved."
  • Condition: Both source and destination files exist on disk, but their byte contents or checksums differ.
  • Cause: A preexisting or independently generated file exists at the target destination path with identical naming.
  • Resolution Path:
  • Identify the conflicting paths from ledger status:
    smart-autosorter ledger status --failed --json
    
  • Inspect and compare both files manually using checksums or diff tools:
    sha256sum "/data/staging/report.pdf" "/data/sorted/Reports/report.pdf"
    
  • Determine the correct canonical version:
    • If the destination file is valid and should not be replaced: Rename the source file or move it to a dedicated manual triage folder:
      mv "/data/staging/report.pdf" "/data/staging/report_v2.pdf"
      
    • If the source file should overwrite the destination file: Back up or remove the conflicting destination file manually:
      mv "/data/sorted/Reports/report.pdf" "/data/sorted/Reports/report_archive.pdf"
      
  • Re-run reconciliation to update the ledger:
    smart-autosorter ledger reconcile
    
  • Once resolved, purge failed entries from the ledger:
    smart-autosorter ledger purge --failed --force
    

Scenario B: Duplicate destination could not be removed

  • Reason String: "Reconciliation conflict for <entry_id>: duplicate destination could not be removed: <error>"
  • Condition: Destination was identical to source, but filesystem permissions or file locks prevented deleting the duplicate destination.
  • Resolution Path:
  • Inspect file permissions and open handles on the destination file:
    lsof "/data/sorted/Reports/report.pdf"
    ls -la "/data/sorted/Reports/report.pdf"
    
  • Release any locking processes or adjust permissions (chmod +w /data/sorted/Reports/report.pdf).
  • Remove the duplicate destination file manually.
  • Run smart-autosorter ledger reconcile again.

FAILED_MISSING

  • Reason String: "Neither source nor destination file exists."
  • Condition: The ledger logged intent to move a file, but neither the source path nor the destination path exists on the filesystem.
  • Cause:
  • Monitored network share, NAS, or removable volume was unmounted.
  • An external script or operator deleted or moved the file out-of-band while Sortify was running.
  • Resolution Path:
  • Verify mount points and volume availability:
    df -h
    mount | grep -i "/data"
    
  • If the volume was detached, remount the volume and re-run reconciliation:
    mount -a
    smart-autosorter ledger reconcile
    
  • If the file was intentionally deleted out-of-band:
    • Export an audit record of the event:
      smart-autosorter ledger export --csv -o /var/log/sortify/missing_files_audit.csv
      
    • Purge the missing record from the ledger:
      smart-autosorter ledger purge --failed --force
      

Stale Daemon Lock and IPC Socket Recovery

Background directory watching daemons (smart-autosorter daemon start) manage an IPC server and write lock files to prevent duplicate daemon processes on the same directory tree.

Lock Mechanics & File Locations

Referencing app/core/ipc.py:L83-L110: - Lock Files: - .autosorter.pid: Written to the base directory of the watched folder. Contains a JSON payload with pid, socket_path, auth_token, and creation timestamp. - .autosorter.sock: Unix domain socket file created in the base directory (on Linux/macOS) or a loopback TCP listener on 127.0.0.1 (on Windows). - Stale Lock Contention: Occurs when a daemon process was abruptly halted (e.g., kill -9, power outage, kernel OOM) and was unable to execute shutdown hooks to unlink .autosorter.pid and .autosorter.sock.


CRITICAL WARNING: Active Process Safety

DANGER: NEVER UNLINK LOCK FILES FOR AN ACTIVE PROCESS

Deleting .autosorter.pid or .autosorter.sock while a daemon process is actively running will break process coordination and may result in: - Multiple concurrent sorting daemons operating on identical directories (split-brain). - Concurrent file moves causing collision errors and data corruption. - Broken IPC telemetry and client communication failure.

Always verify process liveness before removing any lock or socket files.


Safe Verification & Cleanup Procedure

Follow this strict three-step procedure to resolve lock contention safely:

Step 1: Inspect the PID File

Locate the .autosorter.pid file in the base watched directory and read the recorded process ID:

cat /data/staging/.autosorter.pid

Example Output:

{"pid": 48219, "socket_path": "/data/staging/.autosorter.sock", "auth_token": "a1b2c3d4..."}

Step 2: Verify Process Liveness

Verify whether the process ID is actively executing on the system.

On Linux / macOS:

# Check if process exists and is active
kill -0 48219 2>/dev/null && echo "ACTIVE PROCESS DETECTED" || echo "PROCESS NOT RUNNING (STALE)"

# Inspect process details if alive
ps -fp 48219

On Windows (PowerShell / Command Prompt):

Get-Process -Id 48219 -ErrorAction SilentlyContinue
# Or via cmd.exe:
tasklist /FI "PID eq 48219"

  • If the process IS alive (ACTIVE PROCESS DETECTED):
  • DO NOT delete the lock files.
  • If you need to stop the daemon, send a graceful shutdown signal:
    smart-autosorter daemon stop --target /data/staging
    # Or send SIGTERM:
    kill -15 48219
    
  • Wait for the process to exit cleanly and remove its own lock files.

  • If the process is NOT running (PROCESS NOT RUNNING (STALE)):

  • The process died abruptly; the lock files are stale and safe to clean. Proceed to Step 3.

Step 3: Remove Stale Lock Files

Once process termination is verified:

# Remove socket file first if present
rm -f /data/staging/.autosorter.sock

# Remove pid file
rm -f /data/staging/.autosorter.pid

(Note: Starting the daemon via smart-autosorter daemon start /data/staging also checks process liveness automatically using is_process_alive() in app/core/ipc.py:L20-L53 and will automatically clean stale lock files if the previous process is dead).


Cross-References

  • Interactive Session Recovery Guide: Troubleshooting Guide
  • Configuration & Maintenance Reference: Administrator Guide
  • Canonical Move Ledger Implementation: app/core/moves.py
  • Key Lifecycle Audit Ledger: app/core/ledger.py
  • CLI Ledger Command Implementation: app/cli/ledger_cli.py
  • IPC Server & Lock Management: app/core/ipc.py