PABCD Initiative Documentation Hub pabcd_initiative codexclaw cli-jaw

dev-data

Source: skills/dev-data/SKILL.md

Data pipelines, ETL/ELT design, quality validation, SQL optimization, and analysis.

왜 별도 모듈인가
데이터 파이프라인은 앱 CRUD와 근본적으로 다른 관심사를 가진다: 멱등성, 체크포인트 재시작, 데이터 품질 검증, 배치/스트리밍 선택. 이걸 dev-backend에 포함시키면 일반 API 작업에도 불필요한 ETL 문맥이 로드되고, 파이프라인 작업 시에는 정작 필요한 가이드가 묻힌다. 별도 모듈로 분리해서 데이터 작업의 고유한 원칙을 전면에 놓는다.
LLM 단독 사용 시 발생하는 문제

LLM은 데이터 처리 코드를 작성할 때 해피 패스만 구현한다. CSV 파일에 빈 행이 있거나, JSON에 예상 못한 null이 있거나, 인코딩이 UTF-8이 아닌 경우를 고려하지 않는다. 이건 LLM이 학습 데이터에서 '깨끗한 예시'를 주로 봤기 때문이다. 실제 데이터는 항상 더럽다. Defensive Parsing 원칙은 '외부 데이터는 null, 잘못된 타입, 추가 컬럼, 누락 컬럼, 인코딩 문제가 전부 있다고 가정하라'고 명시한다.

이 스킬이 해결하는 실제 문제

비멱등 파이프라인의 중복 데이터

에이전트가 만드는 파이프라인은 보통 INSERT만 하고 upsert를 안 쓴다. 파이프라인이 실패 후 재시작하면 같은 데이터가 두 번 들어간다. Idempotent Operations 원칙은 모든 파이프라인에 upsert 패턴을 강제한다.

스키마 없는 변환의 런타임 폭발

CSV나 JSON을 그냥 읽어서 바로 변환하면, 예상 못한 null, 잘못된 타입, 추가 컬럼이 있을 때 런타임에서 터진다. Schema-First 원칙은 변환 로직 전에 스키마를 먼저 정의하게 한다.

도구 선택의 지식 컷오프

Polars 1.x, DuckDB 1.x가 2024-2025에 크게 바뀌었고, Spark Connect가 등장했다. 에이전트가 2023년 기준으로 pandas만 추천하거나 deprecated API를 쓰는 문제가 있다. tools.md는 현재 도구 비교를 제공하고, 외부 검증을 요구한다.

Triggers: ETL, ELT, pipeline, data quality, SQL optimization, backfill, migration, schema drift

Key Concepts

  • Pipeline Thinking (Extract-Transform-Load)
  • Schema-First Design
  • Defensive Parsing
  • Idempotent Operations
  • Data Quality Gates
  • Batch vs Streaming Architecture

Reference Documents

DocumentDescription
Data Governance — PII, Masking, CompliancePII 분류, 데이터 거버넌스 정책, 규정 준수 가이드
ML Pipeline EngineeringML 파이프라인 설계, 피처 엔지니어링, 모델 평가
Streaming & Event-Driven Data Patterns실시간 스트리밍 아키텍처, Kafka/Flink/Spark Streaming 패턴
Data Processing Tools — pandas vs Polars vs DuckDB데이터 도구 비교: pandas, Polars, DuckDB, Spark, dbt

Sections Overview

SectionSummary
Data Processing Principles파이프라인 사고, 스키마 우선, 방어적 파싱, 멱등성, 빠른 실패 원칙.
Data IngestionCSV/JSON/Parquet/Excel 포맷별 가이드와 증분 로딩 패턴.
Data Qualitynull/유일성/범위/신선도/행 수 검증과 Dead Letter Queue.
SQL Optimization인덱스 전략, 쿼리 플랜 분석, N+1 방지, 파티셔닝.

Academic References

PaperYearRelevance
Designing Data-Intensive Applications (Kleppmann)
book
2017exactly-once 시맨틱스, 멱등 쓰기, Avro/Protobuf 스키마 진화의 표준 참고서.

Official Guides

Full Specification

Show full SKILL.md content

Dev-Data — Data Engineering & Analysis Guide

Production-grade data engineering patterns for building reliable data systems.

Activates by change surface for data pipelines, analytics, SQL-heavy work, schema evolution, backfills, and reporting.

> C0/C1 work (small local patches): See dev §0.0 Work Classifier + §0.1 Patch Fast-Path before reading references.

When to Activate

  • Building data pipelines or ETL/ELT processes
  • Processing CSV, JSON, Parquet, or Excel files
  • Writing analytical SQL, warehouse/lakehouse queries, or transformation models
  • Setting up data quality checks or validation
  • Performing data analysis, aggregation, or reporting
  • Choosing between batch and streaming architectures

Do not activate for plain app CRUD SQL, OLTP query tuning, or transactional schema design. Route those to dev-backend/references/stacks/database.md. This skill owns analytics, ETL/ELT, pipelines, data quality, and reporting.

External/current data evidence

For current external dataset contracts, source freshness, pipeline/tool version

behavior, provider data API changes, or public benchmark/source claims, read the

active search skill and follow its query-rewrite, source-fetch, and

evidence-status rules. Use browser fetch/open/text/get-dom/snapshot only after

candidate URLs exist and the claim needs browser-verifiable source evidence.

---

Pre-Flight Checklist

Before delivering:

  • [ ] Input contract defined: source, schema, expected columns/types, and owner
  • [ ] Pipeline is idempotent and restartable from the last successful checkpoint
  • [ ] Data-quality checks cover nulls, uniqueness, ranges, freshness, and row counts
  • [ ] Volume and latency justify the chosen engine: pandas, Polars, DuckDB, SQL warehouse, Spark/Flink
  • [ ] Invalid records have a dead-letter/quarantine path with enough context to debug
  • [ ] PII/governance classification is complete or delegated to dev-security/§7
  • [ ] Output format and downstream contract are explicit

---

1. Data Processing Principles

Five rules that apply to every data task:

PrincipleWhat It Means
Pipeline thinkingEvery pipeline is Extract → Transform → Load. Keep each stage as an independent, testable function.
Schema-firstDefine expected columns, types, and constraints BEFORE writing transformation logic.
Defensive parsingExternal data will have nulls, wrong types, extra columns, missing columns, and encoding issues. Assume all of these.
Idempotent operationsRunning the same pipeline twice on the same input must produce the same output. Use upsert patterns, not blind inserts.
Fail fast, fail loudRaise errors at pipeline boundaries immediately. Internal transforms propagate errors; dead-letter queues handle row-level quarantine at the boundary (see §3).

---

2. Data Ingestion Patterns

Format-Specific Guidance

FormatBest ForWatch Out For
CSVSimple tabular data, human-readableEncoding (UTF-8 BOM), delimiter ambiguity, multiline values, inconsistent quoting
JSONNested structures, API responsesLarge files (stream, don't load all at once), deeply nested objects, encoding
ParquetLarge analytical datasets, columnar queriesRequires library support, not human-readable, schema evolution
ExcelBusiness user handoffsMultiple sheets, merged cells, formulas vs. values, date formatting
DatabaseProduction system accessConnection pooling, query timeouts, use read replicas for analytics

Incremental Loading

For large or frequently updated data sources:

  1. Use a watermark column (e.g., updated_at, id) to track the last processed record.
  2. Store the watermark after successful load. On failure, restart from the last saved watermark.
  3. Process in batches (tune based on source limits and memory), not all-at-once.
  4. Validate row counts: loaded_rows should equal source_rows_since_watermark.

Schema Validation on Ingest

Before any transformation, validate incoming data:

✅ Check: Expected columns exist
✅ Check: Data types match (string, number, date, boolean)
✅ Check: Required fields are not null
✅ Check: Values are within expected ranges
✅ Check: No unexpected duplicate keys
❌ Fail: If any check fails, write to error log with row details. Don't silently drop.

---

3. ETL/ELT Pipeline Design

Layer Architecture

Rules:

  • Keep staging immutable. Copy first, transform in a separate step — this enables replay and debugging.
  • One transformation per step. Don't combine cleaning + joining + aggregating in one function. Chain separate steps.
  • Incremental processing. Process only new/changed records when possible. Full reloads only when schema changes.

dbt Integration Patterns

Engine landscape (verified 2026-07-02): dbt Core remains the default; dbt Fusion

is the separately-documented/licensed current engine (check its feature matrix and

license before adopting); SQLMesh is a credible active alternative with plan/apply

workflows. Choose per license posture and team workflow — do not assume Fusion pricing

without a primary source.

When using dbt for transformations, follow the staging → intermediate → mart layer architecture:

Rules:

  • Staging models: rename, cast, filter NULLs — no joins, no business logic
  • Intermediate models: joins across staging, deduplication, business transforms
  • Mart models: aggregations, final business entities consumed by BI/analytics
  • Every model has a schema.yml with tests (not_null, unique, relationships, custom SQL).
  • Run validation tests in CI and after significant changes — treat test failures as pipeline failures.
  • Use dbt source freshness to monitor upstream data staleness

Error Handling in Pipelines

ScenarioPattern
Invalid recordsWrite to dead-letter table/file for manual review. Preserve every record for debugging.
Source unavailableRetry with exponential backoff (1s, 2s, 4s). Alert after 3 failures.
Schema mismatchHalt pipeline. Log expected vs. actual schema. Don't attempt partial loads.
Duplicate recordsUse upsert (INSERT ON CONFLICT UPDATE) or deduplicate with window functions.

Orchestration Basics

When pipelines have multiple steps with dependencies:

  • Define tasks as a DAG (Directed Acyclic Graph). Each task depends on its upstream tasks.
  • Each task must be independently retryable. If step 3 fails, you restart step 3, not step 1.
  • Set reasonable retries (2-3) with delay (5 min between attempts).
  • Add timeout per task to prevent hung pipelines.
  • Alert on failure: email, Slack, or monitoring dashboard.

---

4. Data Quality

Validation Checks

Run these after every pipeline step, not just at the end:

CheckWhat It ValidatesExample
Not nullRequired fields have valuesWHERE order_id IS NULL → 0 rows
UniqueNo duplicates on key columnsCOUNT(*) = COUNT(DISTINCT id)
RangeNumeric values within boundsamount BETWEEN 0 AND 1,000,000
CategoricalValues in allowed setstatus IN ('pending', 'active', 'closed')
FreshnessData is recent enoughMAX(updated_at) > NOW() - INTERVAL '24 hours'
Row countNo unexpected data loss or explosionWithin ±10% of previous run
ReferentialForeign keys point to existing recordscustomer_id EXISTS IN customers

Quality Tool Integration

Use a layered quality strategy — different tools at different pipeline stages:

StageToolPurpose
IngestGreat ExpectationsValidate raw data against expectations before staging
Transformdbt testsAssert model-level quality (not_null, unique, relationships, custom SQL)
ProductionSoda / Monte CarloReal-time monitoring, anomaly detection, SLA enforcement

Validate data dimensions: completeness, uniqueness, range, format, referential integrity, freshness.

Rule: Run validation on every pipeline step — skipping "because the data looks fine" leads to silent downstream corruption.

Data Contracts

For datasets shared between teams, define a contract:

A data contract must include:

  • name, owner, version
  • schema: column name, type, nullability, uniqueness, allowed values
  • SLA: freshness threshold, minimum completeness percentage
  • consumers: list of downstream teams/systems

Changes to a contracted schema require versioning and consumer notification.

---

5. Analysis & Reporting

Always Start with Summary Statistics

Before any deep analysis, provide:

MetricWhat to Report
Row countTotal records in dataset
Column inventoryName, type, null count per column
Numeric summarymin, max, mean, median, std dev
Categorical summaryUnique values, top 5 most frequent
Time rangeEarliest and latest timestamp
Data qualityNull percentage, duplicate percentage

Output Formats

FormatWhen to Use Markdown tablesInline reports, ≤50 rows, quick summaries JSONProgrammatic consumption, API responses
CSV exportHandoff to spreadsheet users, large datasets
HTML + chartsDashboards, visual reports (Chart.js, Mermaid diagrams)

Statistical Reporting

When analysis involves statistics:

  • State the method used and its assumptions.
  • Report confidence intervals, not just point estimates.
  • Visualize distributions (histograms, box plots), not just averages.
  • Distinguish correlation from causation explicitly.

---

6. Architecture Decisions

Batch vs. Streaming

ConditionChoose
Real-time insight required (sub-minute latency)Streaming (Kafka + Flink, Spark Structured Streaming, or Kafka Streams depending on complexity)
Exactly-once semantics neededKafka transactional producers + Flink/Spark
Latency >1 min acceptable, volume >1TB/dayDistributed batch (Spark, Databricks)
Latency >1 min acceptable, volume <1TB/daySingle-node batch (SQL, Python, dbt)

Default to batch. Streaming adds significant complexity in error handling, state management, and debugging. Only use streaming when latency requirements genuinely demand it.

Streaming Decision Tiers (heuristic guidance)

Latency RequirementFrameworkComplexity
Sub-100ms, complex statefulApache FlinkHigh (dedicated cluster)
Sub-second, existing Spark infraSpark Structured StreamingMedium
Sub-second, Kafka-centricKafka Streams (embedded library)Low-Medium
Minutes acceptableBatch with frequent schedulingLow

Kafka essentials for data engineers (Kafka 4.x / KRaft era — no ZooKeeper):

  • Partition by expected throughput — avoid excessive partitions
  • Use Schema Registry for backwards-compatible evolution
  • Default to at-least-once delivery + idempotent consumers
  • Use exactly-once only for financial/billing (transactional producers + consumers)
  • Monitor consumer lag via Prometheus/Grafana

See references/streaming.md for Kafka configuration, CDC patterns, and windowing.

Storage Selection

NeedChoose
SQL analytics, BI dashboards, structured queriesData warehouse (Snowflake, BigQuery, PostgreSQL)
ML training, unstructured data, large-scale storageData lake (S3/GCS + Parquet or Delta format)
Both SQL and ML needsLakehouse (Delta Lake, Apache Iceberg)
Real-time key-value lookups, cachingRedis, DynamoDB
Graph relationshipsNeo4j, Neptune

Tool Selection

CategoryOptions (verified 2026-07-02)
OrchestrationAirflow 3.x (standalone DAG processor; SequentialExecutor removed), Prefect 3, Dagster
Transformationdbt Core / dbt Fusion / SQLMesh, Spark, plain SQL
StreamingKafka 4.x (KRaft), Kinesis, Pub/Sub
QualityGX Core (Great Expectations' OSS library), dbt tests, Soda Core (data contracts), custom validators
MonitoringPrometheus, Grafana, Datadog, Monte Carlo (data observability)
Local analysisDuckDB (in-process SQL), Polars (fast DataFrame), pandas 3.x (exploration/ML)

Lakehouse format: do NOT assume "Iceberg won" — Delta Lake and Apache Iceberg are both

active; choose by ecosystem (engine/vendor support, catalog, existing stack), not by

mindshare claims.

Tool Decision Matrix

FactorpandasPolarsDuckDB
Best for<100MB, exploration, ML prep>100MB, batch ETL, performanceSQL analytics, ad-hoc queries
ExecutionSingle-threaded, eagerMulti-threaded Rust, lazy evalVectorized, auto disk spill
Speed (groupby/join)Baseline5-10x fasterMatches Polars on SQL-native
MemoryFull load into RAMStreaming, lazy chainsSpill-to-disk for out-of-core
API styleDataFrame (imperative)DataFrame (expression-based)SQL-first
ML interopExcellent (scikit-learn, etc.)Good (.to_pandas())Good (.fetchdf())
File formatCSV, JSON, ExcelCSV, Parquet, Arrow-nativeCSV, Parquet, JSON, S3 direct

Decision rule (HEURISTIC — size bands are guidance, not hard cutoffs):

Data size / workflowRecommended tool Small (<100MB), interactive explorationpandas
Medium (100MB-10GB), batch transformsPolars
SQL-first analytics, any sizeDuckDB
Blended workflowPolars transforms, DuckDB aggregations (zero-copy via Arrow)

See references/tools.md for full patterns and code examples.

See references/ml-pipeline.md for ML training pipelines, experiment tracking (MLflow 3.x), feature stores (Feast), and data versioning (DVC/Delta Lake).

---

7. Data Governance & PII

Data Classification

LevelExamplesHandling
PublicAggregated metrics, public reportsNo restrictions
InternalBusiness KPIs, operational dataAccess controls, no external sharing
ConfidentialCustomer data, financial recordsEncryption at rest, column-level masking
RestrictedSSN, payment data, health recordsTokenization, row-level security, audit logging

PII Handling Checklist

Before building any pipeline that touches PII:

  • [ ] Classify all columns by sensitivity level
  • [ ] Apply masking/tokenization for non-production environments (static masking)
  • [ ] Implement dynamic masking for production queries (role-based)
  • [ ] Set data retention TTL — don't keep PII longer than needed
  • [ ] Support right-to-erasure (GDPR Article 17): cascading delete across all pipeline stages
  • [ ] Log all PII access for audit trail
  • [ ] Mask raw PII values before logs and traces — use structured logging with redaction

GDPR/CCPA Quick Reference

RequirementEngineering Pattern
Right to erasureSoft delete → batch purge → propagate to downstream stores including data lake
Data minimizationCollect only necessary fields; TTL on non-essential data
Consent trackingConsent event store with versioned preferences; consent-aware pipeline branches
Data portabilityStandardized export endpoint (JSON/CSV) per user request

See references/governance.md for detailed implementation patterns, row-level security, and retention policies.

---

8. Query Performance Guidelines

Ownership note: this section covers analytical SQL, warehouse/lakehouse queries, and pipeline transforms. Plain app CRUD SQL, OLTP schema design, and transactional query tuning belong to dev-backend/references/stacks/database.md.

  • Every query that runs in production: EXPLAIN ANALYZE before deploy
  • Slow query threshold: > 100ms for OLTP, > 5s for OLAP/analytics
  • Index strategy: B-tree for equality/range, GIN for array/JSONB, GiST for geo
  • Missing index detection: pg_stat_user_tables → seq_scan / idx_scan ratio
  • Partition tables > 10M rows if query patterns allow time-range or hash partitioning
  • Never SELECT * in production code — specify columns

For pipeline observability, follow the OpenTelemetry patterns in dev-backend/references/core/observability.md. Instrument pipeline stages as spans, data quality checks as events.

When pipeline errors surface through APIs, use the AppError taxonomy from dev-backend/SKILL.md §3. Map pipeline failures to appropriate HTTP status codes (422 for validation, 502 for upstream failures, 503 for capacity).

For data API patterns (pagination of large datasets, cursor-based access, streaming responses), see dev-backend/references/core/api-design.md.

---

9. Companion Skills

Data engineering does not exist in isolation. Cross-reference these skills when your pipeline connects to other systems:

CompanionWhen to ConsultKey Sections
dev-backendExposing data via API, response envelope shape, pagination§5 API Response Contract, §2 Layered Architecture
dev-securityPII handling, data classification, access controls, audit logging, input validation policy (per dev-security §10 ownership matrix)§1 Input Validation, §4 Secrets, §8 Pre-Flight
dev-testingPipeline validation, contract tests for data APIs, CI gates§2 Backend & API Testing, §3 Contract Testing
dev-frontendDownstream reporting/dashboard consumers, data format expectations§15 Backend Contract & Security Alignment

Integration patterns:

  • Data APIs serving frontend dashboards must use the standard response envelope (dev-backend §5)
  • PII pipelines must classify columns and apply masking per dev-security guidance before this skill's §7 rules
  • Data contract changes (§4 Data Contracts) must notify downstream consumers including frontend teams

---