Data Engineering أساس AI موثوق
النموذج لا يصلح بيانات رديئة. Data Engineering يضمن أن البيانات تصل صحيحة، كاملة، قابلة للتتبع، ومحدثة في الوقت المطلوب. ابدأ بعقد لكل dataset: owner، schema، grain، primary key، freshness، retention، PII classification، lineage، quality rules، و consumer expectations.
ETL يحول قبل التحميل إلى target، و ELT يحمل raw ثم يحول داخل platform. الاختيار يعتمد على compute، governance، latency، حجم البيانات، والتكلفة. احتفظ بطبقة raw immutable نسبيًا، وطبقة cleaned، ثم curated/features.
Data platform للـ AI في رسمة
Batch و Streaming و Event-Driven Pipelines
Batch مناسب للملفات اليومية وإعادة المعالجة، و streaming للـ events المتدفقة بزمن أقل. Event-driven pipeline يربط producer و broker و consumer، لكن لازم تفهم delivery semantics: at-most-once، at-least-once، وعمليًا duplicates واردة. صمم idempotent consumers و deduplication keys.
لا تختَر Spark أو Kafka تلقائيًا. ابدأ بـ Python batch أو scheduled job عندما يكفي. استخدم distributed processing عندما حجم البيانات أو throughput أو latency يبرر التعقيد. Backpressure و retry و dead-letter queues جزء من التصميم.
# Batch transform with explicit input/output boundaries
from pathlib import Path
import pandas as pd
source = Path("data/raw/events.csv")
target = Path("data/curated/events.parquet")
df = pd.read_csv(source)
df["event_time"] = pd.to_datetime(df["event_time"], utc=True, errors="coerce")
df = df.dropna(subset=["event_id", "event_time"])
df = df.drop_duplicates(subset=["event_id"])
target.parent.mkdir(parents=True, exist_ok=True)
df.to_parquet(target, index=False)Data Quality و Validation و Schema Evolution
Quality dimensions: completeness، validity، uniqueness، consistency، timeliness، accuracy. اختبر null ratios، ranges، referential integrity، duplicates، distribution shifts، و freshness. استخدم schema validation عند ingestion؛ لا تسمح لعمود تغير نوعه بصمت أن يمر إلى model training.
Schema evolution يحتاج سياسة للـ backward/forward compatibility. أضف fields اختيارية بحذر، ولا تغير معنى field موجود دون versioning. اجعل invalid records quarantine مع سبب واضح بدل إسقاطها بصمت.
def validate_events(df):
required = {"event_id", "event_time", "customer_id"}
missing = required - set(df.columns)
if missing:
raise ValueError(f"Missing columns: {sorted(missing)}")
if df["event_id"].isna().any():
raise ValueError("event_id cannot be null")
if df["event_id"].duplicated().any():
raise ValueError("event_id must be unique")
if df["event_time"].isna().any():
raise ValueError("event_time must parse as UTC timestamp")Data Contracts و Idempotent Backfills
كل dataset contract يحدد schema، primary key، event time، nullability، allowed values، freshness SLA، owner، PII policy، و schema evolution rules. Backfill يجب أن يكون deterministic و idempotent: إعادة تشغيل نفس partition لا تضاعف records. استخدم partition keys و watermarks و upsert/merge strategy.
عند late-arriving events، حدد allowed lateness وكيف تعيد فتح partitions. لا تستخدم ingestion timestamp بدل event timestamp في تحليل زمني دون توضيح. احتفظ raw data لإعادة المعالجة وفق retention/privacy policy.
def partition_path(event_time):
return event_time.strftime("year=%Y/month=%m/day=%d")
# Stable event_id enables deduplication on replay.
# Write to a staging partition, validate, then atomically publish/replace.ما الذي يجعل backfill آمنًا؟
Data Contracts, Schemas and Schema Evolution
Data contract يحدد schema، semantics، units، nullability، keys، freshness، quality expectations، owner، و change policy. Schema validation وحده لا يكفي: عمود amount قد يكون numeric لكن وحدته cents بدل dollars. ضمّن semantic constraints مثل allowed range، timezone، currency، و uniqueness.
Backward-compatible evolution غالبًا تضيف nullable field أو توسع enum بحذر؛ rename/type narrowing/removal breaking changes. استخدم expand-migrate-contract: أضف الجديد، حدّث producers/consumers، راقب adoption، ثم أزل القديم بعد فترة. لا تفترض أن كل consumers تحدثوا في نفس اللحظة.
from pydantic import BaseModel, Field
from datetime import datetime
class Event(BaseModel):
event_id: str = Field(min_length=1)
tenant_id: str = Field(min_length=1)
amount_minor: int = Field(ge=0)
currency: str = Field(pattern=r'^[A-Z]{3}$')
occurred_at: datetime
# Validate at ingestion boundary; retain source schema/version with the record.Pandas و Polars و Spark
Pandas ممتاز للبيانات التي تناسب RAM وسير العمل المحلي. Polars يقدم lazy execution و parallelism في كثير من transforms. Spark للـ distributed datasets والـ cluster execution، لكنه يحتاج partition planning و shuffle awareness وتكلفة تشغيل أعلى. لا تقفز إلى Spark لملف CSV صغير.
Data warehouse يخدم analytical queries، و OLTP database يخدم transactions؛ لا تخلط workloads. Feature store قد يساعد على consistency بين offline training و online serving، لكنه ليس prerequisite لكل مشروع.
# Polars lazy query: push filters/projections toward the scan
import polars as pl
result = (
pl.scan_parquet("data/raw/*.parquet")
.filter(pl.col("event_date") >= pl.date(2026, 1, 1))
.group_by("customer_id")
.agg(pl.len().alias("event_count"))
.collect()
)Orchestration و Data Versioning
Orchestrator مثل Airflow أو Prefect أو Dagster يدير dependencies، retries، schedules، backfills، observability. لا تجعل DAG يخفي business logic؛ اجعل tasks صغيرة idempotent وتملك inputs/outputs واضحة. Data versioning بأدوات مثل DVC أو immutable object paths يربط dataset revision بالتجربة.
كل pipeline يحتاج checkpoints، retry policy، dead-letter/quarantine، lineage، alerting، SLA freshness، وإمكانية rerun دون duplicate writes. لا تسجل PII في logs.
Dataset Lineage, Versioning and Point-in-Time Correctness
Lineage تربط raw source بال transforms وال curated tables وال features وال model run. عند incident يجب أن تعرف أي source partitions دخلت في model version بعينه. Versioning قد يكون snapshot ID أو immutable object paths أو table time-travel. لا تعتمد على mutable latest.csv كمرجع reproducible.
Point-in-time correctness مهمة في ML: كل feature يجب أن تكون متاحة في وقت prediction. عند بناء historical training data، استخدم event time و ingestion time و valid-from/valid-to حسب semantics. Join على latest customer state قد يسرّب معلومات مستقبلية إلى historical rows.
# Point-in-time join concept (SQL-style pseudocode)
# prediction_time = 2026-01-10T12:00Z
# Select feature versions where valid_from <= prediction_time
# AND (valid_to IS NULL OR prediction_time < valid_to)
# AND event_time <= prediction_time.
# Keep source_snapshot_id and transformation_version in the training manifest.مشروع Data Pipeline للـ RAG و ML
ابنِ pipeline يقرأ CSV و JSON و PDF metadata، يتحقق من schema، ينظف الحقول، يزيل duplicates، يصنف PII، ويكتب Parquet مع manifest يضم source hash و ingestion time و pipeline version. بعد ذلك أرسل document records إلى RAG ingestion أو features إلى ML training.
اختبر corrupted files، duplicate events، late arrivals، schema change، partial failure، retry، و replay. احسب throughput والـ cost لكل 1,000 documents أو million rows. ده يربط data engineering مباشرة بالـ RAG و ML lifecycle.
Pipeline كامل: Validate ثم Quarantine ثم Idempotent Load
الموديل مش بيقول «البيانات دي غلط» — بيتدرّب عليها ويطلّع توقعات غلط بثقة. عشان كده أول واجب على الـ pipeline إنه يرفض: كل batch يتفحص بقواعد صريحة، الصفوف البايظة تتعزل مع سبب الرفض، ولو نسبة الرفض عدّت حد معيّن الـ batch كله يقف. والواجب التاني إنه يكون idempotent: تشغيله مرتين على نفس الملف ما يكررش ولا يبوّظ حاجة.
import io, sqlite3
import numpy as np, pandas as pd
RAW_DAY_1 = """order_id,customer_id,amount,currency,created_at
1001,C-17,250.00,EGP,2026-10-01T09:15:00
1002,C-03,89.50,EGP,2026-10-01T09:40:00
1003,C-17,-40.00,EGP,2026-10-01T10:02:00
1004,,120.00,EGP,2026-10-01T10:30:00
1005,C-22,75.00,USD,2026-10-01T11:00:00
1006,C-09,1e9,EGP,2026-10-01T11:20:00
1002,C-03,89.50,EGP,2026-10-01T09:40:00
1007,C-31,310.00,EGP,not-a-date
1009,C-40,60.00,EGP,2026-10-01T12:10:00
1010,C-41,145.00,EGP,2026-10-01T12:45:00
1011,C-03,22.00,EGP,2026-10-01T13:05:00
1012,C-55,480.00,EGP,2026-10-01T13:30:00
"""
# day 2 re-delivers two day-1 rows (one corrected) plus a new one — a very common upstream behaviour
RAW_DAY_2 = """order_id,customer_id,amount,currency,created_at
1002,C-03,89.50,EGP,2026-10-01T09:40:00
1003,C-17,40.00,EGP,2026-10-01T10:02:00
1008,C-17,55.00,EGP,2026-10-02T08:05:00
"""
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE orders (order_id INTEGER PRIMARY KEY, customer_id TEXT NOT NULL, amount REAL NOT NULL,
currency TEXT NOT NULL, created_at TEXT NOT NULL, batch TEXT NOT NULL);
CREATE TABLE quarantine (batch TEXT, order_id TEXT, reason TEXT, raw TEXT);
""")
def validate(df):
"""Returns a Series: empty string = valid, otherwise the first reason the row was rejected."""
amount = pd.to_numeric(df["amount"], errors="coerce")
created = pd.to_datetime(df["created_at"], errors="coerce", format="ISO8601")
checks = [
(df["customer_id"].isna() | (df["customer_id"].astype(str).str.strip() == ""), "missing customer_id"),
(amount.isna(), "amount is not a number"),
(amount <= 0, "amount must be positive"),
(amount > 1_000_000, "amount above plausible maximum"),
(~df["currency"].isin(["EGP", "USD"]), "unknown currency"),
(created.isna(), "created_at is not an ISO timestamp"),
(df.duplicated("order_id", keep="first"), "duplicate order_id inside the batch"),
]
reason = pd.Series("", index=df.index)
for mask, text in checks:
reason = reason.mask((reason == "") & mask.fillna(False), text)
return reason
def ingest(batch, raw, max_reject_rate=0.5):
df = pd.read_csv(io.StringIO(raw), dtype=str) # read everything as text first: no silent coercion
reason = validate(df)
good, bad = df[reason == ""], df[reason != ""]
rate = len(bad) / len(df)
if rate > max_reject_rate: # the gate: refuse a batch that is mostly broken
print(f"{batch}: REJECTED WHOLE BATCH — {rate:.0%} of rows failed validation"); return
with db: # one transaction per batch: all or nothing
db.execute("DELETE FROM quarantine WHERE batch = ?", (batch,)) # re-runs replace, never append
db.executemany("INSERT INTO quarantine VALUES (?,?,?,?)",
[(batch, r.order_id, reason[i], ",".join(map(str, r))) for i, r in bad.iterrows()])
db.executemany("""INSERT INTO orders VALUES (?,?,?,?,?,?)
ON CONFLICT(order_id) DO UPDATE SET customer_id=excluded.customer_id, amount=excluded.amount,
currency=excluded.currency, created_at=excluded.created_at, batch=excluded.batch""",
[(int(r.order_id), r.customer_id, float(r.amount), r.currency, r.created_at, batch) for r in good.itertuples()])
print(f"{batch}: read={len(df)} loaded={len(good)} quarantined={len(bad)} ({rate:.0%}) -> orders table now has {db.execute('SELECT COUNT(*) FROM orders').fetchone()[0]} rows")
ingest("2026-10-01", RAW_DAY_1)
ingest("2026-10-01", RAW_DAY_1) # the scheduler retried the same file
ingest("2026-10-02", RAW_DAY_2)
print("\nquarantine:")
for row in db.execute("SELECT batch, order_id, reason FROM quarantine ORDER BY batch, order_id"):
print(" ", row)
print("\norder 1003 after the corrected re-delivery:", db.execute("SELECT amount, batch FROM orders WHERE order_id=1003").fetchone())
print("total loaded amount in EGP:", db.execute("SELECT SUM(amount) FROM orders WHERE currency='EGP'").fetchone()[0])
ingest("2026-10-03", "order_id,customer_id,amount,currency,created_at\n2001,,x,EGP,bad\n2002,,y,EGP,bad\n2003,C-1,10,EGP,2026-10-03T08:00:00\n")2026-10-01: read=12 loaded=7 quarantined=5 (42%) -> orders table now has 7 rows
2026-10-01: read=12 loaded=7 quarantined=5 (42%) -> orders table now has 7 rows
2026-10-02: read=3 loaded=3 quarantined=0 (0%) -> orders table now has 9 rows
quarantine:
('2026-10-01', '1002', 'duplicate order_id inside the batch')
('2026-10-01', '1003', 'amount must be positive')
('2026-10-01', '1004', 'missing customer_id')
('2026-10-01', '1006', 'amount above plausible maximum')
('2026-10-01', '1007', 'created_at is not an ISO timestamp')
order 1003 after the corrected re-delivery: (40.0, '2026-10-02')
total loaded amount in EGP: 1141.5
2026-10-03: REJECTED WHOLE BATCH — 67% of rows failed validationالتشغيل التاني لنفس الملف ما غيّرش حاجة: عدد الصفوف زي ما هو، والـ quarantine ما اتكررش. ده بييجي من حاجتين: ON CONFLICT … DO UPDATE (upsert بالـ business key) ومسح quarantine الـ batch قبل إعادة كتابته. من غير ده، كل retry من الـ scheduler كان هيضاعف الإيرادات في الـ dashboard.
الصف 1003: رُفض في اليوم الأول (مبلغ سالب)، واتصحح في إعادة التسليم في اليوم التاني واتحمّل. الـ quarantine مش سلة مهملات — هو قائمة شغل: كل صف معاه السبب والنص الأصلي عشان يتصلّح من المصدر.
dtype=str الأول: لو سبت pandas يخمّن الأنواع، 1e9 هتتقرا رقم عادي والتاريخ البايظ هيخلي العمود كله object في صمت. اقرأ نص، وحوّل بنفسك بـ errors="coerce"، واعتبر الـ NaN الناتج سبب رفض.
الـ gate: الـ batch الأخير أغلبه بايظ فاترفض كله. batch نصه غلط غالبًا معناه إن المصدر نفسه اتغيّر (عمود اتحرك، encoding، وحدة) — تحميل النص «السليم» منه بيدخّل بيانات مشكوك فيها. الأفضل يقف وحد يبص.
اللي يتفحص، بالترتيب
| البُعد | السؤال | مثال check |
|---|---|---|
| Schema | الأعمدة والأنواع زي المتفق عليه؟ | الأعمدة المطلوبة موجودة؛ amount رقم |
| Validity | القيم في النطاق المنطقي؟ | مبلغ موجب وتحت حد أقصى؛ عملة من قائمة |
| Completeness | فيه حقول إلزامية فاضية؟ | customer_id مش null |
| Uniqueness | الـ key متكرر؟ | order_id فريد جوه الـ batch |
| Freshness / volume | الـ batch وصل في ميعاده وبحجمه الطبيعي؟ | عدد الصفوف في حدود ±50% من المتوسط |
| Distribution | الشكل الإحصائي اتغيّر؟ | PSI على الـ features المهمة (شوف درس الـ drift) |
الـ job بتاع التحميل اتعاد تشغيله بعد timeout، والتقرير بقى فيه مبيعات اليوم مضروبة في 2. إيه اللي ناقص في التصميم؟
Data Lineage و Cost و Operational SLOs
Lineage يربط source → transformations → curated dataset → model feature → prediction. عند اكتشاف bug تستطيع تحديد أي models و reports تأثرت. سجل code version و input snapshot و pipeline run ID و quality results. راقب freshness lag، records processed، rejected rows، retry count، duration، compute cost، و data volume.
ضع SLO للـ freshness والـ completeness، alert عند تأخر pipeline، و runbook للـ replay أو quarantine. لا تسجل raw PII في logs. احسب تكلفة كل million rows أو thousand documents لتعرف أثر نمو الاستخدام.
Streaming Semantics و Late Events
في streaming فرّق بين event time (متى حدث الحدث) و processing time (متى وصل/عولج). Late events قد تصل بعد watermark؛ حدد allowed lateness و window correction policy. Exactly-once غالبًا خاص بحدود معينة داخل engine ولا يعني end-to-end exactly-once مع external side effects. استخدم idempotency و transactional/outbox patterns.
راقب consumer lag، partition skew، hot keys، backpressure، DLQ growth، و replay volume. عند poison message لا تجعلها تعطل partition للأبد؛ اعزلها مع metadata كافية للتحقيق.
Data Quality Incident Runbook
عند اكتشاف schema break أو bad batch: أوقف publish للـ curated dataset، حدد partitions المتأثرة، احتفظ بال raw snapshot، أخطر consumers، أصلح transform، أعد backfill في staging، قارن quality metrics، ثم انشر version جديدة. لا تكتب فوق البيانات الصحيحة قبل التحقق.
حدد owner و severity و freshness impact و downstream models/reports affected. بعد الحادث أضف regression fixture تمنع تكرار المشكلة، وحدّث contract أو alert threshold. Data incident قد يتحول إلى model incident إذا لم تُعرف lineage.
Data Quality Dimensions and Statistical Monitoring
Data quality تشمل completeness، validity، uniqueness، consistency، timeliness، و accuracy. اكتب expectations قابلة للقياس: null rate أقل من حد، key uniqueness=100%، freshness أقل من ساعتين، category values ضمن set، row count ضمن range موسمي. لا تستخدم thresholds جامدة دون فهم seasonality؛ استخدم baseline windows و alert severity.
Distribution monitoring يمكن أن يستخدم PSI أو KS أو Jensen-Shannon أو summary stats، لكن أي drift signal يحتاج diagnosis. لا تعتبر drift تلقائيًا تدهورًا؛ وقد يحدث performance degradation دون drift واضح. اربط monitoring بـ labels المتأخرة والـ business outcomes.
import numpy as np
reference = np.array([10, 11, 12, 10, 9, 11, 12, 10])
current = np.array([10, 10, 11, 12, 10, 9, 11, 80])
print('null rate:', 0.0) # example placeholder for a validated batch
print('reference/current means:', reference.mean(), current.mean())
print('reference/current p95:', np.percentile(reference,95), np.percentile(current,95))Point-in-Time Correctness: لب فكرة الـ Feature Store
عايز feature اسمها «عدد شكاوى العميل». السؤال اللي بيفرّق: لحد إمتى؟ وقت التوقع الحقيقي إنت عارف الشكاوى اللي حصلت قبل اللحظة دي بس. لو حسبتها من جدول النهارده (كل الشكاوى)، التدريب بيشوف شكاوى حصلت بعد الحدث اللي بتتوقعه. ده أخبث نوع leakage: الكود شكله طبيعي تمامًا (join عادي)، والأرقام الـ offline بتطلع ممتازة.
import numpy as np, pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(5)
n_customers = 3000
start = pd.Timestamp("2026-01-01")
# each customer has ONE prediction moment (e.g. the day we must decide on a retention offer)
labels = pd.DataFrame({"customer_id": np.arange(n_customers),
"as_of": start + pd.to_timedelta(rng.integers(60, 240, n_customers), unit="D")})
risk = rng.normal(0, 1, n_customers) # hidden propensity to churn
labels["churned"] = (rng.random(n_customers) < 1 / (1 + np.exp(-(risk - 1)))).astype(int)
# complaints over the year: a few BEFORE the decision (weak signal), many AFTER it for churners (they complain while leaving)
rows = []
for cid, as_of, churned, r in zip(labels.customer_id, labels.as_of, labels.churned, risk):
for _ in range(rng.poisson(1.0 + 0.4 * max(r, 0))):
rows.append((cid, as_of - pd.Timedelta(days=int(rng.integers(1, 60)))))
for _ in range(rng.poisson(4.0) if churned else rng.poisson(0.3)):
rows.append((cid, as_of + pd.Timedelta(days=int(rng.integers(1, 30)))))
complaints = pd.DataFrame(rows, columns=["customer_id", "at"])
# ---- WRONG: aggregate the whole table, then join. Looks perfectly reasonable. ----
naive = labels.merge(complaints.groupby("customer_id").size().rename("complaints").reset_index(), how="left").fillna({"complaints": 0})
# ---- RIGHT: only events strictly before each row's own as_of timestamp ----
joined = labels.merge(complaints, on="customer_id", how="left")
before = joined[joined["at"] < joined["as_of"]]
pit = labels.merge(before.groupby("customer_id").size().rename("complaints").reset_index(), how="left").fillna({"complaints": 0})
def offline_auc(df):
X_tr, X_te, y_tr, y_te = train_test_split(df[["complaints"]], df["churned"], random_state=0, stratify=df["churned"])
return roc_auc_score(y_te, LogisticRegression().fit(X_tr, y_tr).predict_proba(X_te)[:, 1])
print(f"complaint events: {len(complaints):,} ({(joined['at'] >= joined['as_of']).sum():,} of them happened AFTER the prediction moment)")
print(f"offline ROC-AUC with the naive join : {offline_auc(naive):.3f} <- what the notebook reports")
print(f"offline ROC-AUC with the point-in-time join: {offline_auc(pit):.3f} <- what production will actually deliver")
row = labels.iloc[0]
c = complaints[complaints.customer_id == row.customer_id]
print(f"\ncustomer 0, decision date {row.as_of.date()}: naive feature = {len(c)}, point-in-time feature = {(c['at'] < row.as_of).sum()}")complaint events: 7,754 (4,224 of them happened AFTER the prediction moment)
offline ROC-AUC with the naive join : 0.946 <- what the notebook reports
offline ROC-AUC with the point-in-time join: 0.545 <- what production will actually deliver
customer 0, decision date 2026-06-30: naive feature = 3, point-in-time feature = 2نفس الـ feature، نفس الموديل، والفرق في الـ join بس. النسخة الـ naive بتدّي AUC شبه مثالي لأنها بتعدّ شكاوى العميل وهو بيسيب — معلومة مش هتبقى عندك لحظة القرار. النسخة الصح بتدّي الرقم الحقيقي: الإشارة ضعيفة. لو كنت نشرت الموديل الأول، الأداء في الإنتاج كان هيبقى زي الرقم التاني بالظبط، وكنت هتقعد تدوّر على «bug في الـ serving».
القاعدة: كل صف تدريب له as_of timestamp، وكل feature بتتحسب من الأحداث اللي قبله فقط. ده اسمه point-in-time (أو as-of) join.
الـ feature store بيحل تلات مشاكل، وده أولها:
- Point-in-time retrieval للتدريب: «اديني قيمة الـ feature دي زي ما كانت يوم كذا».
- نفس التعريف للتدريب والـ serving: الـ feature بتتعرّف مرة واحدة، فمفيش نسختين (SQL للتدريب وكود للخدمة) بيختلفوا في صمت — training/serving skew.
- Online store بيرجّع أحدث قيمة في milliseconds وقت الـ inference.
هل محتاج feature store؟ لفريق صغير بموديل أو اتنين: لأ — جدول events بـ timestamps + as-of join مكتوب صح + test بيتأكد إن مفيش حدث بعد الـ as_of يكفوا. الـ feature store يتبرر لما features كتير بتتشارك بين موديلات وفرق، أو محتاج serving بـ latency منخفض.
موديل churn: offline AUC = 0.97، وفي الإنتاج 0.62. الـ features فيها «إجمالي تذاكر الدعم للعميل» محسوبة من جدول التذاكر الحالي. التشخيص؟
Feature Store Concepts and Offline/Online Consistency
Feature store يفصل feature definitions عن consumers، وقد يوفر offline historical store للتدريب و online low-latency store للـ inference. التحدي الأساسي هو consistency: نفس transformation وال entity keys و point-in-time semantics يجب أن تنطبق في training و serving. اختلاف timezone أو null handling أو default values يصنع training-serving skew.
لا تحتاج feature store لكل مشروع. ابدأ ب shared feature library + versioned pipelines إذا الفريق صغير. عندما تتكرر features بين models أو تحتاج online retrieval منخفض latency و governance، قيّم feature store. راقب freshness و write/read consistency و entity coverage و fallback behavior.
def safe_ratio(numerator: float, denominator: float) -> float | None:
if denominator == 0:
return None # same null semantics in offline and online paths
return numerator / denominator
# Put transformations in one tested module used by batch and online serving.
print(safe_ratio(12, 4), safe_ratio(2, 0))Airflow و dbt: الـ orchestration والـ transformations بقرارات واضحة
Airflow و dbt بيتذكروا مع بعض كتير لكن بيحلوا مشكلتين مختلفتين: Airflow بيقرر إمتى وبأي ترتيب الشغل يتنفذ (orchestration)، وdbt بيعرّف إيه التحويلات اللي بتحصل جوه الـ warehouse بـ SQL مختبر وموثق (transformation).
from airflow.decorators import dag, task
from datetime import datetime, timedelta
@dag(schedule="0 2 * * *", start_date=datetime(2026, 1, 1), catchup=False,
default_args={"retries": 2, "retry_delay": timedelta(minutes=10)}, tags=["ai", "rag"])
def nightly_knowledge_refresh():
@task
def extract() -> str:
return copy_changed_rows_since_watermark() # idempotent: watermark per table
@task
def dbt_build(_: str):
run(["dbt", "build", "--select", "staging+ marts.usage_daily marts.documents_current"]) # run + test
@task
def reindex(_: None) -> int:
return enqueue_reindex_for_changed_documents() # the RAG ingestion pipeline consumes this queue
reindex(dbt_build(extract()))
nightly_knowledge_refresh(){{ config(materialized='incremental', unique_key=['tenant_id', 'day']) }}
select tenant_id,
cast(occurred_at as date) as day,
sum(input_tokens + output_tokens) as tokens,
count(*) as requests
from {{ ref('stg_ai_requests') }}
{% if is_incremental() %}
where occurred_at >= (select max(day) from {{ this }}) - interval '2 days' -- reprocess a small window for late events
{% endif %}
group by 1, 2models:
- name: usage_daily
columns:
- name: tenant_id
tests: [not_null, relationships: { to: ref('dim_tenants'), field: tenant_id }]
- name: tokens
tests: [not_null, dbt_utils.accepted_range: { min_value: 0 }]
tests:
- dbt_utils.unique_combination_of_columns: { combination_of_columns: [tenant_id, day] }| السؤال | الإجابة العملية |
|---|---|
| محتاج Airflow ولا Hangfire يكفي؟ | شوية jobs مرتبطة بتطبيق .NET ← Hangfire/Quartz. DAGs بيانات كتير، backfills، اعتماديات بين فرق، وفريق data ← Airflow (أو Dagster/Prefect). |
| محتاج dbt؟ | لو التحويلات SQL في warehouse/Postgres وعايز tests و lineage و docs و incremental models ← نعم. لو تحويلات قليلة في كود التطبيق ← لا. |
| فين الـ Python transformations التقيلة (embeddings)؟ | tasks في Airflow (أو workers) — مش في dbt؛ dbt لـ SQL. |
| الأخطاء الشائعة؟ | tasks مش idempotent (backfill بيكرر)، business logic في الـ DAG نفسه، dbt models من غير tests، و secrets في الـ DAG code. |
الربط: الـ marts زي usage_daily هي اللي بتغذي الـ billing والـ forecasting في Time Series، والـ window functions اللي جواها في SQL Window Functions.
اختبر فهمك
لماذا at-least-once delivery يحتاج idempotent consumer؟
ما الفرق بين event time و processing time؟
اختبار الإتقان المهني
ما المقصود بـ point-in-time correctness؟
هل data drift يعني بالضرورة أن model performance انخفض؟
ما فائدة data contract؟
المراجع والقراءة الإضافية
الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)
التوثيق الرسمي — Official documentation
مصادر تعليمية ومتقدمة — Third-party & advanced reading
خريطة التغطية: 22 عنصر من الـ Roadmap ومكان شرحه في الدرس
خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.