# Implementation Plan: Versioned JSON Artifact Importer

## 1. Goal Description
Build a robust, domain-agnostic, and versioned JSON artifact importer for the **Lead Generation (LEAD-GEN)** engine. The importer consumes structured artifact files generated by upstream Factory pipelines and ingests them into the local LEAD-GEN data store.

### Core Objectives:
1. **Zero External DB Writes**: Strictly read-only access to Factory inputs; no writes to Factory databases.
2. **Schema & Version Validation**: Strict validation against versioned schemas (e.g., v1.0).
3. **Integrity & Checksum Verification**: Cryptographic hashing (SHA-256) of input artifacts to detect modifications and guarantee deduplication/idempotency.
4. **Provenance Tracking**: Preserves source metadata (source URI, extraction timestamp, campaign ID, evidence chain).
5. **Atomic Transactions**: Ingestion occurs within an atomic transaction or staging workflow—all records succeed or none are committed on fatal failure.
6. **Detailed Error Reporting**: Comprehensive reporting of structural, schema, and reference errors.
7. **Idempotency (Repeat Import Guarantee)**: Re-importing identical or already-ingested artifacts produces identical entity counts without creating duplicates.

---

## 2. Architecture & Data Flow

```
[Factory Output (.json)]
       │
       ▼
[1. File Loader & Checksum] ──► Verify SHA-256 & Artifact Version
       │
       ▼
[2. Schema Validator]       ──► Validate Payload Structure & Evidence Fields
       │
       ▼
[3. Ingestion Engine]       ──► In-Memory Transform & Entity Resolution
       │
       ▼
[4. Atomic Writer]          ──► Transactional DB Commit / Rollback on Error
       │
       ▼
[5. Ingest Audit & Metrics] ──► Return Ingest Report (Total, Added, Updated, Skipped)
```

---

## 3. Data Specification & Provenance Model

### 3.1 Artifact JSON Structure (`artifact_v1.json`)
The imported artifact must adhere to a domain-agnostic format:
```json
{
  "artifact_version": "1.0.0",
  "artifact_id": "art-20261009-001",
  "generated_at": "2026-10-09T08:00:00Z",
  "campaign_id": "PILOT-COST-OPT-EU",
  "checksum": "sha256-hash-value-here",
  "source_provenance": {
    "pipeline_run_id": "run-xyz-42",
    "generator": "factory-extract-worker",
    "source_environment": "production"
  },
  "data": {
    "companies": [
      {
        "external_id": "comp-001",
        "name": "Enterprise Example AG",
        "domain": "example.de",
        "country": "DE",
        "metadata": { ... }
      }
    ],
    "leads": [
      {
        "external_id": "lead-001",
        "company_external_id": "comp-001",
        "target_role": "Head of IT Procurement",
        "evidence_signals": [
          {
            "signal_type": "contract_renewal_cycle",
            "source_url": "https://example.de/press/annual-report-2025.pdf",
            "source_date": "2025-11-15",
            "extracted_text": "Enterprise agreement renewal pending Q1 2026."
          }
        ],
        "metadata": { ... }
      }
    ]
  }
}
```

---

## 4. Proposed Implementation Modules

### Module 1: `ArtifactValidator`
- **Checksum Verification**: Computes SHA-256 over raw file bytes or payload data and cross-checks provided checksum or registers new checksum in an `ingested_artifacts` tracking table.
- **Version Compatibility**: Enforces semantic version checks (rejects incompatible major versions; permits non-breaking minor versions).
- **Pydantic / Typed Validation**: Validates existence and typing of required fields:
  - Canonical domain / company identifiers.
  - Linked foreign references (`company_external_id` matches a valid company in the payload or store).
  - Explicit evidence provenance (`source_url`, `source_date`, `extracted_text`).

### Module 2: `AtomicWriter` & Transaction Management
- Executes ingestion using atomic database transactions (e.g., SQLite/PostgreSQL `BEGIN TRANSACTION ... COMMIT` or atomic temp-file staging if document-based).
- **On Exception**: Automatically executes a full transaction rollback. No partial or corrupt state is left behind.

### Module 3: Idempotency & Upsert Strategy
- **Companies**: Keyed on unique canonical identifiers (`canonical_domain` or `company_external_id`).
  - If existing: Updates timestamps and supplementary metadata without incrementing distinct company count.
  - If new: Inserts company record.
- **Leads**: Keyed on a deterministic natural/composite key:
  `lead_key = hash(canonical_company_id + target_role + primary_evidence_signal_hash)`.
  - Re-importing identical payloads triggers an idempotent `ON CONFLICT DO UPDATE` or `SKIP`, keeping the distinct lead count identical.
- **Artifact Registry**: Records `(artifact_id, checksum, ingested_at, status)` to prevent duplicate redundant processing while allowing idempotent re-runs.

### Module 4: Error Reporting (`ImportReport`)
Structured reporting returning:
```json
{
  "status": "SUCCESS" | "FAILED" | "PARTIAL_REJECTED",
  "artifact_id": "art-20261009-001",
  "counts": {
    "companies_processed": 10,
    "companies_created": 10,
    "companies_updated": 0,
    "leads_processed": 15,
    "leads_created": 15,
    "leads_updated": 0
  },
  "errors": [],
  "warnings": []
}
```

---

## 5. Acceptance & Verification Plan

### Test 1: Repeat Import Idempotency Test (Primary Acceptance Criterion)
1. **Initial Run**: Import valid `artifact_sample_v1.json` into a clean test database.
   - Record `count(companies)` and `count(leads)`.
   - Verify all provenance fields and signals are populated.
2. **Second Run**: Immediately execute the importer on the exact same `artifact_sample_v1.json`.
3. **Verification**:
   - Assert `count(companies)_run1 == count(companies)_run2`.
   - Assert `count(leads)_run1 == count(leads)_run2`.
   - Assert no duplicate primary or foreign keys exist.

### Test 2: Checksum & Tamper Detection Test
1. Alter a single byte inside the data payload of `artifact_sample_v1.json`.
2. Execute importer.
3. Assert import fails with `ChecksumMismatchError` before any database operations occur.

### Test 3: Atomic Rollback on Invalid Lead / Missing Reference
1. Construct an artifact with 5 valid companies and 5 valid leads, plus 1 malformed lead (e.g., missing evidence provenance or referencing non-existent company).
2. Execute importer under atomic mode.
3. Assert import terminates with `ValidationError`.
4. Assert database remains in its pre-run state (0 companies and 0 leads committed).

### Test 4: Upstream Factory DB Read-Only Guarantee
1. Verify database connection configs: connection credentials strictly bind to the local LEAD-GEN repository.
2. Factory artifacts are read via file system streams or read-only S3/blob mounts with no database write handles passed to the importer.