<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Data Do GmbH on Medium]]></title>
        <description><![CDATA[Stories by Data Do GmbH on Medium]]></description>
        <link>https://medium.com/@DataDo?source=rss-cf37407d7ba7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8yID2vXmIh1d4KERjeTX0w.jpeg</url>
            <title>Stories by Data Do GmbH on Medium</title>
            <link>https://medium.com/@DataDo?source=rss-cf37407d7ba7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:32:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@DataDo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[CI/CD Data Testing with dbt and DuckDB: Pre-Flight Assertions for Analytics Pipelines]]></title>
            <link>https://medium.com/@DataDo/ci-cd-data-testing-with-dbt-and-duckdb-pre-flight-assertions-for-analytics-pipelines-655249de138f?source=rss-cf37407d7ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/655249de138f</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[duckdb]]></category>
            <category><![CDATA[analytics-platforms]]></category>
            <dc:creator><![CDATA[Data Do GmbH]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 12:30:30 GMT</pubDate>
            <atom:updated>2026-11-19T12:30:30.832Z</atom:updated>
            <content:encoded><![CDATA[<p>Testing dbt models in continuous integration typically involves triggering a staging run on a remote cloud data warehouse such as Snowflake, BigQuery, or Databricks. While thorough, this approach introduces operational friction: warehouse spin-up delays, queueing, credit consumption, and multi-minute pipeline runs for even minor SQL modifications.</p><p>By using the dbt-duckdb adapter, analytics teams can execute standard dbt tests (unique, not_null, relationships, and custom singular assertions) directly inside an ephemeral CI runner against local Parquet snapshots or seed files.</p><p>This shifts assertion testing left: models and contracts are validated within the pipeline runner before triggering downstream runs on target warehouses.</p><h3>Architecture Overview</h3><p>A dedicated CI profile directs dbt to compile and execute against an in-memory or temporary file-based DuckDB instance. Upstream sources map to lightweight Parquet fixtures stored in the repository, pulled from an artifact registry, or fetched from object storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/0*cGe5-Kn93G_-GHcl.png" /></figure><h3>1. Project Configuration</h3><h3>profiles.yml</h3><p>Define a ci_duckdb target alongside production and development targets. Using an environment variable or setting a local file path (target/ci_duckdb.db) isolates test artifacts within the current runner:</p><pre>jaffle_shop:<br>  target: dev<br>  outputs:<br>    dev:<br>      type: snowflake  # or bigquery / databricks / postgres<br>      account: &quot;{{ env_var(&#39;DBT_ACCOUNT&#39;) }}&quot;<br>      user: &quot;{{ env_var(&#39;DBT_USER&#39;) }}&quot;<br>      # ... warehouse credentials<br>    <br>    ci_duckdb:<br>      type: duckdb<br>      path: &#39;target/ci_duckdb.db&#39;<br>      threads: 4<br>      extensions:<br>        - parquet<br>        - httpfs</pre><h3>Source Mapping (models/staging/sources.yml)</h3><p>Configure sources to resolve to Parquet files during CI execution, while defaulting to warehouse tables in standard environments:</p><pre>version: 2<br><br>sources:<br>  - name: raw_data<br>    schema: &quot;{{ &#39;main&#39; if target.name == &#39;ci_duckdb&#39; else &#39;raw_production&#39; }}&quot;<br>    tables:<br>      - name: orders<br>        meta:<br>          external_location: &quot;{{ &#39;fixtures/raw_orders.parquet&#39; if target.name == &#39;ci_duckdb&#39; else none }}&quot;<br>      - name: customers<br>        meta:<br>          external_location: &quot;{{ &#39;fixtures/raw_customers.parquet&#39; if target.name == &#39;ci_duckdb&#39; else none }}&quot;</pre><p>Inside model definitions, conditionally route inputs based on the active target:</p><pre>-- models/staging/stg_orders.sql<br>{{ config(materialized=&#39;view&#39;) }}<br><br>WITH source AS (<br>    {% if target.name == &#39;ci_duckdb&#39; %}<br>    SELECT * FROM read_parquet(&#39;fixtures/raw_orders.parquet&#39;)<br>    {% else %}<br>    SELECT * FROM {{ source(&#39;raw_data&#39;, &#39;orders&#39;) }}<br>    {% endif %}<br>)<br><br>SELECT<br>    order_id::VARCHAR AS order_id,<br>    customer_id::VARCHAR AS customer_id,<br>    net_amount::DOUBLE AS net_amount,<br>    tax_amount::DOUBLE AS tax_amount,<br>    gross_amount::DOUBLE AS gross_amount<br>FROM source</pre><h3>Assertion Definitions</h3><p>All native dbt tests function without modification under the dbt-duckdb adapter.</p><h3>Generic Tests (models/staging/schema.yml)</h3><pre>version: 2<br><br>models:<br>  - name: stg_orders<br>    columns:<br>      - name: order_id<br>        tests:<br>          - unique<br>          - not_null<br>      - name: customer_id<br>        tests:<br>          - not_null<br>          - relationships:<br>              to: ref(&#39;stg_customers&#39;)<br>              field: customer_id<br>      - name: net_amount<br>        tests:<br>          - not_null</pre><h3>Singular Business Assertions (tests/assert_net_plus_tax_equals_gross.sql)</h3><p>Singular tests query compiled models directly, raising a failure if any offending rows return:</p><pre>SELECT<br>    order_id,<br>    net_amount,<br>    tax_amount,<br>    gross_amount,<br>    ROUND(ABS((net_amount + tax_amount) - gross_amount), 4) AS delta<br>FROM {{ ref(&#39;stg_orders&#39;) }}<br>WHERE ROUND(ABS((net_amount + tax_amount) - gross_amount), 4) &gt; 0.01</pre><h3>Platform-Agnostic CI Implementation</h3><p>To keep the pipeline portable across GitLab CI, Jenkins, Tekton, or GitHub Actions, test orchestration and reporting are handled by a standard shell script and a small parser script rather than vendor-specific plugins.</p><h3>Artifact Parser (scripts/parse_dbt_results.py)</h3><p>This script reads target/run_results.json and outputs a standardized Markdown report while returning a non-zero exit code on failures:</p><pre>#!/usr/bin/env python3<br>import json<br>import sys<br>from pathlib import Path<br><br>results_file = Path(&quot;target/run_results.json&quot;)<br>if not results_file.exists():<br>    print(&quot;Error: target/run_results.json not found.&quot;, file=sys.stderr)<br>    sys.exit(1)<br><br>with open(results_file) as f:<br>    data = json.load(f)<br><br>results = data.get(&quot;results&quot;, [])<br>total = len(results)<br>passed = sum(1 for r in results if r[&quot;status&quot;] in (&quot;pass&quot;, &quot;success&quot;))<br>failed = total - passed<br>status_text = &quot;PASSED&quot; if failed == 0 else &quot;FAILED&quot;<br><br>lines = [<br>    f&quot;## dbt Pre-Flight Quality Check: {status_text}&quot;,<br>    f&quot;**Summary:** {passed}/{total} nodes passed ({failed} failures).\n&quot;,<br>    &quot;| Node Name | Type | Status | Execution Time | Message |&quot;,<br>    &quot;| :--- | :--- | :---: | :---: | :--- |&quot;<br>]<br><br>for r in results:<br>    node_id = r[&quot;unique_id&quot;]<br>    node_type = node_id.split(&quot;.&quot;)[0]<br>    name = node_id.split(&quot;.&quot;)[-1]<br>    status = &quot;PASS&quot; if r[&quot;status&quot;] in (&quot;pass&quot;, &quot;success&quot;) else &quot;FAIL&quot;<br>    duration = f&quot;{r.get(&#39;execution_time&#39;, 0):.2f}s&quot;<br>    msg = (r.get(&quot;message&quot;) or &quot;&quot;).replace(&quot;\n&quot;, &quot; &quot;).strip()<br>    lines.append(f&quot;| `{name}` | `{node_type}` | {status} | {duration} | {msg} |&quot;)<br><br>report_content = &quot;\n&quot;.join(lines)<br>Path(&quot;dbt_report.md&quot;).write_text(report_content)<br>print(report_content)<br><br>sys.exit(0 if failed == 0 else 1)</pre><h3>GitLab CI Pipeline Configuration</h3><p>The pipeline runs the pre-flight suite inside standard Python container runners. Using GitLab’s native API integration or merge request description updates, the generated report attaches directly to the MR.</p><pre># .gitlab-ci.yml<br>stages:<br>  - preflight<br>  - deploy_staging<br><br>default:<br>  image: python:3.11-slim<br><br>variables:<br>  PIP_CACHE_DIR: &quot;$CI_PROJECT_DIR/.cache/pip&quot;<br><br>cache:<br>  paths:<br>    - .cache/pip/<br><br>dbt_preflight_assertions:<br>  stage: preflight<br>  rules:<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;merge_request_event&quot;&#39;<br>      changes:<br>        - &quot;models/**/*&quot;<br>        - &quot;seeds/**/*&quot;<br>        - &quot;tests/**/*&quot;<br>        - &quot;dbt_project.yml&quot;<br>  before_script:<br>    - apt-get update &amp;&amp; apt-get install -y --no-install-recommends curl jq<br>    - pip install dbt-core dbt-duckdb duckdb<br>    - mkdir -p fixtures<br>    # Fetch sanitized test datasets (e.g. from internal S3, MinIO, or generic package registry)<br>    # Mock data generation for illustration:<br>    - python3 -c &quot;<br>      import duckdb;<br>      con = duckdb.connect();<br>      con.execute(\&quot;COPY (SELECT &#39;CUST_&#39; || lpad(i::VARCHAR, 3, &#39;0&#39;) AS customer_id FROM generate_series(1, 50) t(i)) TO &#39;fixtures/raw_customers.parquet&#39; (FORMAT PARQUET);\&quot;);<br>      con.execute(\&quot;COPY (SELECT &#39;ORD_&#39; || lpad(i::VARCHAR, 6, &#39;0&#39;) AS order_id, &#39;CUST_&#39; || lpad(((i % 50) + 1)::VARCHAR, 3, &#39;0&#39;) AS customer_id, ROUND(random() * 200 + 10, 2) AS net_amount, ROUND((random() * 200 + 10) * 0.19, 2) AS tax_amount, 0.0 AS gross_amount FROM generate_series(1, 10000) t(i)) TO &#39;fixtures/temp.parquet&#39; (FORMAT PARQUET);\&quot;);<br>      con.execute(\&quot;COPY (SELECT order_id, customer_id, net_amount, tax_amount, ROUND(net_amount + tax_amount, 2) AS gross_amount FROM &#39;fixtures/temp.parquet&#39;) TO &#39;fixtures/raw_orders.parquet&#39; (FORMAT PARQUET);\&quot;);<br>      &quot;<br>  script:<br>    - dbt deps --target ci_duckdb<br>    # Run transformations and assertions locally in DuckDB<br>    - dbt build --target ci_duckdb --profiles-dir .<br>  after_script:<br>    - python3 scripts/parse_dbt_results.py || true<br>    # Post report back to the GitLab Merge Request using CI_JOB_TOKEN<br>    - |<br>      if [ -n &quot;$CI_MERGE_REQUEST_IID&quot; ] &amp;&amp; [ -f &quot;dbt_report.md&quot; ]; then<br>        REPORT_BODY=$(jq -Rs . &lt; dbt_report.md)<br>        curl --silent --request POST \<br>          --header &quot;JOB-TOKEN: $CI_JOB_TOKEN&quot; \<br>          --header &quot;Content-Type: application/json&quot; \<br>          --data &quot;{\&quot;body\&quot;: $REPORT_BODY}&quot; \<br>          &quot;${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/merge_requests/${CI_MERGE_REQUEST_IID}/notes&quot;<br>      fi<br>  artifacts:<br>    when: always<br>    paths:<br>      - target/run_results.json<br>      - dbt_report.md<br>    expire_in: 7 days</pre><h3>Execution Lifecycle Across Platforms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T3Ra_SIVkiWMOOjK.png" /></figure><h3>Operational Considerations</h3><ol><li><strong>State-Based Testing (</strong><strong>dbt slim CI):</strong> In projects with hundreds of models, test execution can be further restricted by comparing the current branch state against an exported production manifest.json:Bashdbt test --select state:modified+ --state path/to/prod/artifacts --target ci_duckdb</li><li><strong>Deterministic Test Fixtures:</strong> Treat Parquet fixtures as explicit integration contracts. Storing small, anonymized baseline tables (under 50 MB) inside an object storage bucket or a GitLab Generic Package Registry keeps runner setup fast and decoupled from production access controls.</li><li><strong>Cross-Engine Macro Compatibility:</strong> When using dialect-specific syntax (such as Snowflake window framing or date manipulation), isolate them within dbt macros using conditional blocks:SQL{% macro dateadd(datepart, interval, date) %} {% if target.type == &#39;duckdb&#39; %} {{ date }} + INTERVAL &#39;{{ interval }} {{ datepart }}&#39; {% else %} DATEADD({{ datepart }}, {{ interval }}, {{ date }}) {% endif %} {% endmacro %}</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=655249de138f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deterministic Context Triage: Accelerating Production RAG with Fast System 1 Decision Models]]></title>
            <link>https://medium.com/@DataDo/deterministic-context-triage-accelerating-production-rag-with-fast-system-1-decision-models-6d29dfd36393?source=rss-cf37407d7ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d29dfd36393</guid>
            <category><![CDATA[pydantic-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[jevs]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Data Do GmbH]]></dc:creator>
            <pubDate>Wed, 11 Nov 2026 11:38:37 GMT</pubDate>
            <atom:updated>2026-11-11T11:38:37.703Z</atom:updated>
            <content:encoded><![CDATA[<p>Enterprise retrieval-augmented generation (RAG) systems frequently fail not in their ability to generate prose, but in their capacity to triage context under strict operational constraints.</p><p>In high-concurrency production environments, the traditional two-stage RAG setup — dense vector retrieval followed directly by autoregressive LLM synthesis or heavy cross-encoder reranking — introduces severe latency bottlenecks, unpredictable cost variance, and context window pollution.</p><p>To build deterministic, low-latency, and cost-resilient architectures, engineering teams are decoupling context judgment from context synthesis using <strong>System 1 decision models</strong> (such as the <a href="https://typesafe.ai/blog/introducing-system-one-models-and-jev">JEV</a> and <a href="https://github.com/NandhaKishorM/laya">Laya</a> architectures).</p><h3>The Bottleneck of Autoregressive Context Filtering</h3><p>Dense vector retrieval (bi-encoders) excels at global recall over large collections, but cosine similarity alone lacks fine-grained semantic discrimination. Vector search returns false positives: passages that share syntactic patterns or topical overlap with a user prompt, yet provide zero factual utility toward answering the core question.</p><h3>The Trade-off Dilemma</h3><ol><li><strong>Unfiltered Context Flooding:</strong> Injecting top-k raw vector results (e.g., k = 15) directly into a generative frontier model pollutes the prompt. This triggers the <strong>lost-in-the-middle</strong> effect — where LLMs fail to surface facts buried between distractor text — while burning unnecessary input tokens on every turn of a multi-turn conversation.</li><li><strong>Cross-Encoder Reranking Latency:</strong> Running high-parameter cross-encoders or multi-turn autoregressive LLM calls to rank and prune passages introduces hundreds of milliseconds (or multiple seconds) of latency, blocking real-time chat streaming.</li><li><strong>Structured Tool/Query Gating Overhead:</strong> Asking a general-purpose LLM to output a JSON blob just to decide whether context is needed or whether an intent matches a tool schema consumes 50–150 tokens of generation time and risks syntax parsing failures.</li></ol><p>Production systems require an intermediate step: <strong>sub-50ms deterministic context triage</strong>.</p><h3>What Is a JEV-Class Decision Model?</h3><p>Rooted in dual-process cognitive architecture, cognitive scientist Daniel Kahneman framed <strong>System 1</strong> as rapid, intuitive pattern classification and <strong>System 2</strong> as deliberate, compute-heavy reasoning.</p><p>Standard LLMs are treated as System 2 engines: they produce sequential tokens autoregressively. Conversely, <strong>JEV (Judgment Engine for Vectors / Typed Decisions)</strong> and its open-source counterpart <strong>Laya</strong> are <strong>non-autoregressive transformer encoder models</strong> (typically built on backbones like ModernBERT).</p><p>Instead of generating a text stream token-by-token, a JEV-class model evaluates a batch of structured classification criteria across candidate passages in a <strong>single forward pass</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/0*K-KIa1cvKjLDtiau.png" /></figure><h3>Core Primitive Outputs</h3><ul><li><strong>Choice</strong>: Selects discrete categorizations or identifies the optimal retrieval target from an arbitrary set of candidate tools or collections.</li><li><strong>Noul</strong>: A calibrated boolean judgment (True/False) paired with a probability estimate and an explicit epistemic confidence score.</li><li><strong>Score</strong>: An ordinal rating along a defined scale (e.g., [&quot;irrelevant&quot;, &quot;tangential&quot;, &quot;directly_actionable&quot;]) measuring relevance or answer sufficiency.</li></ul><p>Because these primitives do not decode tokens sequentially, their execution time is flat, deterministic, and bounded by transformer encoder matrix multiplication speeds.</p><h3>Engineering Advantages in Production RAG</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/0*jlY4cSW1gVdlrDY1.png" /></figure><h3>Ultra-Low Latency Batch Pre-Filtering</h3><p>Evaluating 20 retrieved chunks using an autoregressive model requires sequential output generation or heavily parallelized concurrent API requests with high jitter. A local JEV model runs all 20 evaluations concurrently as a single batched tensor operation on GPU or fast CPU backbones, typically finishing in under 35 milliseconds.</p><h3>Calibrated Confidence and Safety Thresholding</h3><p>JEV-class models trained with Reinforcement Learning from Calibrated Decision (RLCD) produce strictly proper probabilities. If a candidate chunk receives a high utility score but an epistemic confidence metric below an operational threshold (tau &lt; 0.70), the system can deterministically flag knowledge gaps, skip context injection, or trigger fallbacks without parsing ambiguous natural language refusals.</p><h3>Deterministic Token Economics</h3><p>By scrubbing 80–90% of raw candidate chunks before they reach the synthesis prompt, context windows remain lean. A pipeline that trims 12 irrelevant chunks of 400 tokens each saves ~4,800 input tokens per turn. In enterprise deployments handling tens of thousands of daily interactions, this directly reduces inference expenditure while improving throughput.</p><h3>Model Landscape: Decision Models and High-Speed Rerankers</h3><p>Teams implementing pre-filtering have distinct options spanning hosted APIs, self-hosted open-weights models, and specialized encoder architectures:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*Wh8mfFN87uuy2UxkgEWTHw.png" /></figure><h3>Implementation Guide: Deploying Laya with PydanticAI</h3><p>Laya pairs naturally with <strong>PydanticAI</strong> by acting as a deterministic dependency in RunContext. Rather than giving an agent raw tool access to flood context or asking an LLM to self-evaluate relevance, Laya acts as a type-safe gatekeeper:</p><ol><li>It evaluates whether retrieval is needed via noul before any tool executes.</li><li>It prunes retrieved chunks in parallel in the agent tool body, returning only high-confidence citations.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ER5dASgHjdfddgvZ.png" /></figure><h3>Step 1: Environment Setup</h3><pre> <br>pip install -U pydantic-ai laya torch transformers accelerate</pre><h3>Step 2: Full PydanticAI Production Implementation</h3><pre>from __future__ import annotations<br> <br>import asyncio<br>from dataclasses import dataclass<br>from typing import List<br>from laya import Router<br>from pydantic import BaseModel, Field<br>from pydantic_ai import Agent, RunContext<br> <br> <br># 1. Domain Models for Knowledge Base &amp;amp; Output<br>class RetrievedDoc(BaseModel):<br>    doc_id: str<br>    content: str<br> <br> <br>class VerifiedCitation(BaseModel):<br>    doc_id: str<br>    content: str<br>    relevance_prob: float<br>    confidence: float<br>    rank_score: int<br> <br> <br>class RAGResponse(BaseModel):<br>    answer: str = Field(description=&quot;Direct, factual answer synthesized from verified citations.&quot;)<br>    citations: List[str] = Field(default_factory=list, description=&quot;List of verified document IDs used.&quot;)<br> <br> <br># 2. Agent Dependencies: Injecting Local Laya Router &amp;amp; Mock DB<br>@dataclass<br>class RAGDependencies:<br>    router: Router<br>    raw_database: List[RetrievedDoc]<br> <br> <br># 3. Instantiate PydanticAI Agent<br>rag_agent = Agent(<br>    &quot;openai:gpt-4o-mini&quot;,<br>    deps_type=RAGDependencies,<br>    result_type=RAGResponse,<br>    system_prompt=(<br>        &quot;You are an enterprise technical assistant. Answer the user prompt strictly &quot;<br>        &quot;using the verified documents retrieved by your tools. Do not hallucinate.&quot;<br>    ),<br>)<br> <br> <br># 4. Agent Tool: Context Retrieval with Local Laya Pre-Filtering<br>@rag_agent.tool<br>async def retrieve_verified_knowledge(<br>    ctx: RunContext[RAGDependencies], query: str<br>) -&gt; List[VerifiedCitation]:<br>    &quot;&quot;&quot;Retrieve and deterministically pre-filter knowledge chunks relevant to the query.&quot;&quot;&quot;<br>    router = ctx.deps.router<br>    candidates = ctx.deps.raw_database<br> <br>    decision_spec = {<br>        &quot;is_directly_relevant&quot;: {<br>            &quot;type&quot;: &quot;noul&quot;,<br>            &quot;instructions&quot;: f&quot;Does this document snippet provide factual answers or rules for: &#39;{query}&#39;?&quot;,<br>        },<br>        &quot;actionability&quot;: {<br>            &quot;type&quot;: &quot;score&quot;,<br>            &quot;instructions&quot;: f&quot;Rate technical actionability for: &#39;{query}&#39;&quot;,<br>            &quot;scale&quot;: [&quot;irrelevant&quot;, &quot;supporting_context&quot;, &quot;primary_fact&quot;],<br>        },<br>    }<br> <br>    verified_chunks: List[VerifiedCitation] = []<br> <br>    # Fast non-autoregressive triage across all candidates<br>    for item in candidates:<br>        evaluation_state = f&quot;Query: {query}\nDocument: {item.content}&quot;<br>         <br>        # Executes in ~33ms per check on local GPU/ModernBERT<br>        decision = router.predict(evaluation_state, decision_spec)<br>         <br>        noul_prob = decision[&quot;is_directly_relevant&quot;][&quot;noul&quot;]<br>        confidence = decision[&quot;is_directly_relevant&quot;][&quot;confidence&quot;]<br>        score_val = decision[&quot;actionability&quot;][&quot;value&quot;]<br> <br>        # Calibrated safety threshold: keep only high-confidence factual matches<br>        if noul_prob &gt;= 0.75 and confidence &gt;= 0.70:<br>            verified_chunks.append(<br>                VerifiedCitation(<br>                    doc_id=item.doc_id,<br>                    content=item.content,<br>                    relevance_prob=round(noul_prob, 3),<br>                    confidence=round(confidence, 3),<br>                    rank_score=score_val,<br>                )<br>            )<br> <br>    # Sort deterministically by actionability score<br>    verified_chunks.sort(key=lambda x: x.rank_score, reverse=True)<br>    return verified_chunks[:3]<br> <br> <br># 5. Pipeline Execution<br>async def main():<br>    # Initialize the local Laya engine<br>    local_laya = Router(preload=True)<br> <br>    # Sample corpus simulating a raw vector search return (containing distractors)<br>    mock_vector_results = [<br>        RetrievedDoc(<br>            doc_id=&quot;eu_ai_act_art9&quot;,<br>            content=&quot;High-risk AI systems must establish and maintain a continuous risk management system throughout their lifecycle.&quot;,<br>        ),<br>        RetrievedDoc(<br>            doc_id=&quot;eu_ai_act_art14&quot;,<br>            content=&quot;High-risk AI systems shall be designed to be overseen by natural persons during the period in which they are in use.&quot;,<br>        ),<br>        RetrievedDoc(<br>            doc_id=&quot;aws_s3_standard&quot;,<br>            content=&quot;Amazon S3 Standard offers high durability, availability, and performance object storage for frequently accessed data.&quot;,<br>        ),<br>        RetrievedDoc(<br>            doc_id=&quot;postgres_wal&quot;,<br>            content=&quot;PostgreSQL write-ahead logging guarantees data integrity by logging changes before writing them to data files.&quot;,<br>        ),<br>    ]<br> <br>    deps = RAGDependencies(router=local_laya, raw_database=mock_vector_results)<br> <br>    query = &quot;What operational safeguards are mandated for high-risk AI models under EU regulations?&quot;<br>    print(f&quot;\n[Query]: {query}\n&quot; + &quot;-&quot; * 70)<br> <br>    result = await rag_agent.run(query, deps=deps)<br> <br>    print(&quot;\n[Structured Agent Output]:&quot;)<br>    print(f&quot;Answer: {result.data.answer}&quot;)<br>    print(f&quot;Cited Sources: {result.data.citations}&quot;)<br> <br> <br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(main())</pre><h3>Architectural Summary</h3><p>Treating generative LLMs as universal Swiss Army knives introduces latency and cost vulnerabilities. Embedding non-autoregressive decision models like Laya into RAG pipelines enforces clean separation of concerns:</p><ol><li><strong>Vector Engines</strong> maximize recall over high-dimensional text corpora.</li><li><strong>System 1 Decision Models</strong> deliver sub-40ms deterministic context pruning and intent classification with calibrated confidence.</li><li><strong>Generative LLMs</strong> synthesize verified facts into clear human communication.</li></ol><p>By establishing deterministic triage before generative synthesis, production AI systems maintain speed, lower operational overhead, and prevent hallucinations at scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d29dfd36393" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless Analytics & Vector Search on Kubernetes: Building a Lean Data Warehouse with DuckDB…]]></title>
            <link>https://medium.com/@DataDo/serverless-analytics-vector-search-on-kubernetes-building-a-lean-data-warehouse-with-duckdb-6122307006a0?source=rss-cf37407d7ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6122307006a0</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[duckdb]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-lake]]></category>
            <dc:creator><![CDATA[Data Do GmbH]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 14:07:56 GMT</pubDate>
            <atom:updated>2026-11-05T14:07:56.821Z</atom:updated>
            <content:encoded><![CDATA[<h3>Serverless Analytics &amp; Vector Search on Kubernetes: Building a Lean Data Warehouse with DuckDB, Object Storage, and PostgreSQL / pgvector</h3><p>Cloud data warehouses often present teams with a difficult trade-off: either accept unpredictable SaaS compute bills or take on the operational overhead of running heavy distributed query engines like Trino or Spark. Furthermore, modern analytical platforms increasingly require bridging structured analytical files with operational relational records and vector embeddings for retrieval-augmented generation (RAG) and semantic similarity search.</p><p>By deploying <a href="https://duckdb.org/"><strong>DuckDB</strong></a><strong> </strong>inside Kubernetes<strong>,</strong> you can achieve sub-second analytical queries directly across raw object storage (via httpfs) and transactional/vector data residing in PostgreSQL with <a href="https://github.com/pgvector/pgvector">pgvector</a> (via the postgres_scanner and vss extensions)—combining an in-process vectorized engine with cloud-native scalability, zero vendor lock-in, and native Kubeflow integration.</p><p>Here is an architectural deep dive into how to build this unified analytical and semantic query layer on Kubernetes.</p><h3>Architectural Overview</h3><p>The core design principle is <strong>stateless compute decoupled from durable object storage and operational databases</strong>. The DuckDB engine pods retain no persistent disk state; instead, they execute vectorized SQL queries federating directly across remote Parquet files on S3 and vector tables in PostgreSQL via connection pooling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*UarjXgJeJJ7ZRbktQORqag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/0*7WNk5NjfIH-IyS-S.png" /></figure><h3>Key Components in Detail</h3><h3>Storage Connections: Object Storage &amp; PostgreSQL / pgvector</h3><h4>S3 via httpfs</h4><p>Traditional data processing pipelines download entire dataset dumps to a local volume before executing SQL queries. DuckDB circumvents this via its native <strong>httpfs extension</strong>, which communicates with S3-compatible Object Storage Services (MinIO, Ceph, AWS S3).</p><p>When DuckDB reads a Parquet file over S3:</p><ol><li>It issues targeted HTTP byte-range requests to fetch the <strong>Parquet file footer</strong> (schema, column statistics, dictionary pages).</li><li>It pushes down query projections and filter predicates ($min/max$ metadata checks) to determine which row groups are needed.</li><li>It fetches <strong>only the required byte ranges</strong> directly into memory.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/0*SGD_pjOli94hShId.png" /></figure><h4>PostgreSQL + pgvector via postgres_scanner</h4><p>Using the postgres_scanner extension, DuckDB connects directly to PostgreSQL using the binary protocol to read tables on the fly without staging them to disk. When paired with pgvector, DuckDB can read embeddings (stored as vector or array types) and execute hybrid joins—such as enriching historical parquet transaction logs with live user profile vectors and product similarity scores.</p><pre><br>INSTALL httpfs;<br>LOAD httpfs;<br>INSTALL postgres_scanner;<br>LOAD postgres_scanner;<br> <br>-- Configure S3 credentials<br>SET s3_endpoint = &#39;s3_endpoint_path&#39;;<br>SET s3_url_style = &#39;path&#39;;<br>SET s3_use_ssl = true;<br>SET s3_access_key_id = &#39;${STORAGE_ACCESS_KEY}&#39;;<br>SET s3_secret_access_key = &#39;${STORAGE_SECRET_KEY}&#39;;<br> <br>-- Attach PostgreSQL database dynamically<br>CALL postgres_attach(&#39;dbname=analytics user=postgres host=postgres-service.analytics.svc.cluster.local password=${POSTGRES_PASSWORD} port=5432&#39;, source_schema=&#39;public&#39;);<br> <br>-- Federated Query: Join massive Parquet lakehouse logs with pgvector customer embeddings<br>SELECT <br>    l.customer_id,<br>    p.customer_segment,<br>    p.embedding,<br>    COUNT(DISTINCT l.transaction_id) AS total_orders,<br>    ROUND(SUM(l.sale_amount), 2) AS total_revenue<br>FROM read_parquet(&#39;s3://lakehouse-gold/sales/year=2026/*.parquet&#39;) l<br>JOIN analytics.customer_profiles p ON l.customer_id = p.id<br>WHERE l.status = &#39;COMPLETED&#39;<br>GROUP BY l.customer_id, p.customer_segment, p.embedding<br>ORDER BY total_revenue DESC<br>LIMIT 50;</pre><h3>The Engine Pod: Python Native + FastAPI</h3><p>The engine pod acts as an analytical proxy. Built with FastAPI and native DuckDB bindings, it accepts SQL payloads or structured parameter blocks, runs them against the engine, and returns results in Apache Arrow format or JSON.</p><p>Using <strong>Apache Arrow Flight SQL</strong> or raw Arrow IPC buffers drastically minimizes serialization latency. Unlike traditional JDBC/ODBC connections that incur heavy CPU overhead converting tabular records to JSON/tuples, Arrow retains zero-copy columnar data structures from DuckDB straight to downstream clients.</p><p>A lightweight production wrapper (app.py):</p><pre>import duckdb<br>from fastapi import FastAPI, HTTPException<br>from pydantic import BaseModel<br>import pyarrow as pa<br>import io<br>import os<br> <br>app = FastAPI(title=&quot;DuckDB K8s Federated Engine&quot;)<br> <br>class QueryPayload(BaseModel):<br>    query: str<br> <br>def get_connection():<br>    con = duckdb.connect(database=&quot;:memory:&quot;)<br>     <br>    # Load storage and database extensions<br>    con.execute(&quot;INSTALL httpfs; LOAD httpfs;&quot;)<br>    con.execute(&quot;INSTALL postgres_scanner; LOAD postgres_scanner;&quot;)<br>     <br>    # Object storage configuration<br>    con.execute(f&quot;SET s3_endpoint = &#39;{os.getenv(&#39;S3_ENDPOINT&#39;)}&#39;;&quot;)<br>    con.execute(f&quot;SET s3_access_key_id = &#39;{os.getenv(&#39;S3_ACCESS_KEY&#39;)}&#39;;&quot;)<br>    con.execute(f&quot;SET s3_secret_access_key = &#39;{os.getenv(&#39;S3_SECRET_KEY&#39;)}&#39;;&quot;)<br>     <br>    # Engine limits &amp;amp; concurrency<br>    con.execute(f&quot;SET threads = {os.getenv(&#39;DUCKDB_THREADS&#39;, &#39;4&#39;)};&quot;)<br>    con.execute(f&quot;SET max_memory = &#39;{os.getenv(&#39;DUCKDB_MAX_MEMORY&#39;, &#39;8GB&#39;)}&#39;;&quot;)<br>     <br>    # Attach Postgres &amp;amp; pgvector source<br>    pg_conn = (<br>        f&quot;dbname={os.getenv(&#39;POSTGRES_DB&#39;, &#39;analytics&#39;)} &quot;<br>        f&quot;user={os.getenv(&#39;POSTGRES_USER&#39;, &#39;postgres&#39;)} &quot;<br>        f&quot;host={os.getenv(&#39;POSTGRES_HOST&#39;, &#39;postgres-service.analytics.svc.cluster.local&#39;)} &quot;<br>        f&quot;password={os.getenv(&#39;POSTGRES_PASSWORD&#39;)} &quot;<br>        f&quot;port={os.getenv(&#39;POSTGRES_PORT&#39;, &#39;5432&#39;)}&quot;<br>    )<br>    con.execute(f&quot;CALL postgres_attach(&#39;{pg_conn}&#39;, source_schema=&#39;public&#39;);&quot;)<br>    return con<br> <br>@app.post(&quot;/api/query&quot;)<br>def execute_query(payload: QueryPayload):<br>    try:<br>        con = get_connection()<br>        arrow_table: pa.Table = con.execute(payload.query).arrow()<br>         <br>        # Serialize Arrow table to IPC stream<br>        sink = io.BytesIO()<br>        with pa.ipc.new_stream(sink, arrow_table.schema) as writer:<br>            writer.write_table(arrow_table)<br>             <br>        con.close()<br>        return sink.getvalue()<br>    except Exception as e:<br>        raise HTTPException(status_code=400, detail=str(e))</pre><h3>Visual Exploration: DuckDB Web UI Pod</h3><p>For data scientists and analysts accustomed to browser-based SQL consoles, pairing the stateless engine with a dedicated UI container provides parity with modern cloud data warehouse interfaces.</p><p>The UI container connects to the query engine or mounts identical httpfs and Postgres credentials, allowing users to:</p><ul><li>Inspect remote schemas and explore partitions across S3 paths.</li><li>Inspect PostgreSQL catalog tables, view metadata, and check vector column dimensions directly.</li><li>Interactively test filter predicates, joins, and aggregations before committing code to production DAGs.</li><li>Download ad-hoc result sets directly as Parquet or CSV.</li></ul><h3>Kubernetes Service &amp; Ingress Routing</h3><p>A standard Kubernetes Deployment coupled with a unified Ingress exposes both components under a single domain, isolating operational concerns:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: duckdb-service<br>  namespace: analytics<br>spec:<br>  type: ClusterIP<br>  ports:<br>    - name: http-engine<br>      port: 8000<br>      targetPort: 8000<br>    - name: http-ui<br>      port: 8080<br>      targetPort: 8080<br>  selector:<br>    app: duckdb-warehouse<br>---<br>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: duckdb-ingress<br>  namespace: analytics<br>  annotations:<br>    kubernetes.io/ingress.class: nginx<br>spec:<br>  rules:<br>  - host: warehouse.internal.data-do.de<br>    http:<br>      paths:<br>      - path: /api<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: duckdb-service<br>            port:<br>              number: 8000<br>      - path: /<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: duckdb-service<br>            port:<br>              number: 8080</pre><h3>Operational Advantages</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dVXPRgQd4b23WDyM.png" /></figure><ol><li><strong>Near-Zero Idle Cost:</strong> Unlike multi-node warehouses that require always-on coordinator and worker nodes, DuckDB engine pods can be scaled down to zero or scaled dynamically using the Kubernetes Horizontal Pod Autoscaler (HPA) or KEDA based on HTTP request volume.</li><li><strong>Predictable Memory Footprint:</strong> DuckDB adheres strictly to its configured max_memory boundary, utilizing out-of-core disk spillover (backed by ephemeral K8s emptyDir volumes) to prevent OOMKilled termination during large joins or vector transformations.</li><li><strong>True Hybrid Analytics (Lake + Relational + Vectors):</strong> By federating Parquet lakehouse storage with pgvector inside PostgreSQL, analysts can evaluate vector embeddings alongside historical data without requiring separate vector synchronization pipelines or specialized graph databases.</li><li><strong>Reproducibility with Kubeflow:</strong> Pipeline tasks executed in Kubeflow can call the internal [http://duckdb-service.analytics.svc.cluster.local:8000/api/query](http://duckdb-service.analytics.svc.cluster.local:8000/api/query) endpoint, generating training feature tables directly from raw lakehouse files and live database state without custom driver configurations.</li></ol><p>Running DuckDB on Kubernetes decouples data volume from compute cost, giving engineering teams a high-performance, compliant, and cost-efficient analytical foundation without the overhead of heavy distributed engines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6122307006a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LiquidAI LFM2.5–2.6B: On-Device Reasoning and Native Tool Use Under 2.5 GB]]></title>
            <link>https://medium.com/@DataDo/liquidai-lfm2-5-2-6b-on-device-reasoning-and-native-tool-use-under-2-5-gb-21ae9f17a110?source=rss-cf37407d7ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/21ae9f17a110</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Data Do GmbH]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 13:44:16 GMT</pubDate>
            <atom:updated>2026-10-27T13:44:16.361Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction: The Shift Toward Local, Privacy-First AI</h3><p>For the past three years, the dominant paradigm in artificial intelligence has been cloud-centric: centralize compute in massive data centers, deploy trillion-parameter models behind API gateways, and send proprietary company logs across the internet for analysis. However, enterprise reality is rapidly challenging this approach. Data governance mandates (such as GDPR, HIPAA, and CCPA), proprietary intellectual property considerations, recurring API subscription tolls, and network latency constraints have spurred an architectural counter-revolution: <strong>on-device, edge-native inference</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FcKCtC7wSq-rKcQI.png" /></figure><p>While the industry initially assumed that smaller models (under 3 billion parameters) could only handle elementary summarization, the emergence of <a href="https://huggingface.co/LiquidAI/LFM2.5-2.6B"><strong>LiquidAI’s LFM2.5–2.6B</strong></a> has dramatically disrupted this assumption. By combining non-transformer computational primitives with targeted reinforcement learning for reasoning and native tool invocation, LFM2.5 delivers state-of-the-art agentic capabilities on standard developer workstations, edge gateways, and laptop CPUs — all while consuming less than 2.5 GB of RAM/VRAM.</p><p>In this deep-dive, we explore the architectural innovations behind LFM2.5–2.6B, dissect its native &lt;think&gt; reasoning mechanism and tool-calling protocol, evaluate its performance benchmarks across modern hardware, and build a production-grade, 100% offline desktop data auditor—including critical real-world runtime optimizations to keep memory footprint strictly under 2.5 GB.</p><h3>Architectural Deep Dive: Hybrid Convolution-Attention Design</h3><p>Standard transformer architectures suffer from quadratic time and memory complexity $\mathcal{O}(N²)$ relative to sequence length due to full self-attention key-value (KV) matrices. On resource-constrained edge devices, KV-cache growth frequently causes out-of-memory (OOM) crashes or severely bottlenecks decoding speed when context scales beyond a few thousand tokens.</p><p>LiquidAI resolves this fundamental bottleneck in LFM2.5–2.6B through a <strong>hybrid architecture</strong> that interweaves structured state-space/short-convolution blocks with sparse grouped-query attention (GQA):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/0*0jRR6A4CHXzFxr4T.png" /></figure><h3>Key Architectural Specifications:</h3><ul><li><strong>22 Double-Gated Short Convolution Layers</strong>: These layers handle local context modeling, token mixing, and state propagation in linear time. Because short convolutions do not require unbounded KV caches, memory usage remains strictly bounded during pre-fill and decode steps.</li><li><strong>8 Grouped-Query Attention (GQA) Layers</strong>: Sparse attention layers are strategically interleaved throughout the network to ensure exact associative recall, long-range variable binding, and complex syntactic reasoning.</li><li><strong>128K Token Context Window</strong>: Despite requiring less than 2.5 GB of memory in quantized formats (GGUF Q4_K_M/Q8_0), the hybrid architecture stably processes large context inputs without structural degradation.</li><li><strong>34 Trillion Token Pre-training Corpus</strong>: The model is trained on a curated corpus of 34T tokens encompassing high-density technical literature, structured databases, codebases, and synthetic reasoning trajectories.</li></ul><p>This hybrid synthesis allows LFM2.5–2.6B to maintain the expressive retrieval capacity of traditional transformers while achieving the constant-state throughput of recurrent neural networks and state-space models.</p><h3>Native Reasoning &amp; Tool Capabilities</h3><p>Many lightweight models require external prompting tricks, complex scaffolding (e.g., LangChain or ReAct regex wrappers), or high-overhead teacher fine-tunes to reliably call functions. LFM2.5–2.6B was trained with <strong>native agentic Reinforcement Learning (RL)</strong>, embedding dual-track execution directly into its token vocabulary.</p><h3>1. The &lt;think&gt; Token Parser</h3><p>When faced with ambiguous or multi-step queries, LFM2.5 automatically emits internal deliberation paths inside explicit &lt;think&gt;...&lt;/think&gt; delimiters. This explicit Chain-of-Thought (CoT) phase permits the model to formulate mathematical assertions, plan SQL joins, and verify edge conditions before emitting executable tokens or user-facing text:</p><pre>&lt;|im_start|&gt;user<br>Find all unapproved expenses over $5,000 in Engineering.<br>&lt;|im_end|&gt;<br>&lt;|im_start|&gt;assistant<br>&lt;think&gt;<br>The user wants to identify unapproved corporate expenses in the Engineering department where amount &gt; 5000.<br>I have access to the SQLite table `expenses` with schema (id, department, vendor, amount, date, status).<br>Conditions:<br>1. department = &#39;Engineering&#39;<br>2. amount &gt; 5000<br>3. status = &#39;Unapproved&#39; (or status != &#39;Approved&#39;)<br>Let&#39;s construct the SQL tool call.<br>&lt;/think&gt;<br>&lt;|tool_call_start|&gt;[run_sql_query(query=&quot;SELECT * FROM expenses WHERE department = &#39;Engineering&#39; AND amount &gt; 5000 AND status != &#39;Approved&#39;&quot;)]&lt;|tool_call_end|&gt;<br>&lt;|im_end|&gt;</pre><h3>2. Native Tool Invocation Tokens</h3><p>The tokenizer defines first-class control tokens:</p><ul><li>&lt;|tool_call_start|&gt;: Denotes the commencement of a structured tool request.</li><li>&lt;|tool_call_end|&gt;: Demarcates the end of the invocation payload.</li></ul><p>When our execution environment detects these tokens, it intercepts the query, dispatches it to the local SQLite database engine, and injects the raw result back into the prompt stream under the &lt;|im_start|&gt;tool context role. LFM2.5 then ingests the database output and synthesizes a natural-language report in the subsequent decoding pass.</p><h3>Hands-on Walkthrough: Zero-Cloud Desktop Data Auditor</h3><p>To demonstrate LFM2.5–2.6B in action, we build the <strong>Zero-Cloud Desktop Data Auditor</strong> — a desktop application combining Streamlit, SQLite, and uv package management.</p><h3>Project Layout</h3><pre>.<br>├── article.md          # Technical analysis<br>├── app.py              # Streamlit dashboard interface<br>├── agent_engine.py     # LFM2.5 inference, tool execution, and token parser<br>├── db_setup.py         # SQLite seed script with financial logs<br>├── pyproject.toml      # Dependency specification (uv managed)<br>└── README.md           # Quickstart instructions</pre><h3>1. Database Schema &amp; Anomalies (db_setup.py)</h3><p>Our mock corporate database tracks sensitive expenses and access logs:</p><ul><li>expenses: Tracks department spending, vendors, invoice amounts, and approval statuses.</li><li>access_logs: Tracks employee timestamps, systems accessed, and flagged anomalous IPs.</li></ul><p>Running python db_setup.py seeds records containing suspicious unapproved transactions (such as shadow AI compute clusters and unverified vendor payments) and off-hours access attempts to customer PII archives.</p><h3>2. Optimized Engine &amp; Tool Orchestrator (agent_engine.py)</h3><p>To keep RAM under 2.5 GB and prevent thread contention on CPU, agent_engine.py leverages llama-cpp-python targeting the official LFM2.5-2.6B-Q4_K_M.gguf quantization:</p><pre>class AuditAgent:<br>    &quot;&quot;&quot;<br>    Agent orchestrator integrating Pydantic Settings, Pydantic AI agent tools,<br>    and LiquidAI/LFM2.5-2.6B local inference with native &amp;lt;think&gt; parsing.<br>    &quot;&quot;&quot;<br> <br>    def __init__(<br>        self,<br>        settings: Optional[Settings] = None,<br>        model_id: Optional[str] = None,<br>        db_path: Optional[str] = None,<br>    ):<br>        self.settings = settings or get_settings()<br>        if model_id:<br>            self.settings.model.model_id = model_id<br>        if db_path:<br>            self.settings.db.db_path = db_path<br> <br>        self.model_id = self.settings.model.model_id<br>        self.db_path = self.settings.db.db_path<br>        self.tokenizer = None<br>        self.model = None<br>        self.llm = None<br> <br>        if self.settings.model.device != &quot;auto&quot;:<br>            self.device = self.settings.model.device<br>        else:<br>            self.device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br> <br>        # Initialize Pydantic AI agent<br>        self.pydantic_ai_agent = create_pydantic_ai_agent(self.settings)<br> <br>    def load_model(self) -&gt; None:<br>        &quot;&quot;&quot;Loads model using llama-cpp-python (quantized GGUF) or transformers.&quot;&quot;&quot;<br>        if self.settings.model.provider == &quot;transformers&quot;:<br>            if self.model is None or self.tokenizer is None:<br>                self.tokenizer = AutoTokenizer.from_pretrained(<br>                    self.model_id,<br>                    trust_remote_code=True,<br>                )<br>                torch_dtype = (<br>                    torch.bfloat16<br>                    if torch.cuda.is_available() and torch.cuda.is_bf16_supported()<br>                    else torch.float16<br>                )<br>                if not torch.cuda.is_available():<br>                    torch_dtype = torch.float32<br>                    num_cores = os.cpu_count() or 4<br>                    torch.set_num_threads(max(1, min(num_cores, 8)))<br> <br>                self.model = AutoModelForCausalLM.from_pretrained(<br>                    self.model_id,<br>                    dtype=torch_dtype,<br>                    device_map=&quot;auto&quot; if torch.cuda.is_available() else None,<br>                    trust_remote_code=True,<br>                    low_cpu_mem_usage=True,<br>                )<br>                if not torch.cuda.is_available() and self.device:<br>                    self.model.to(self.device)<br>                self.model.eval()<br>            return</pre><h3>3. Application State Management (app.py)</h3><p>To prevent Streamlit from reloading duplicate model instances into RAM on every button click or prompt submission, we wrap the agent instantiation with @st.cache_resource:</p><pre>import streamlit as st<br>from agent_engine import AuditAgent<br># Single model instance cached globally across user sessions<br>@st.cache_resource<br>def get_agent():<br>return AuditAgent()<br>agent = get_agent()<br>st.title(&quot;<br>Zero-Cloud Desktop Data Auditor&quot;)<br># Chat logic and expander UI for &amp;lt;think&gt; tags...</pre><h3>Production Engineering Pitfalls: Avoiding Memory Bloat &amp; Swap Bottlenecks</h3><p>During empirical testing on x86 and ARM desktop systems, running LLMs locally can run into performance issues if the runtime environment is misconfigured. Below are three critical pitfalls observed in default Python deployments and their solutions:</p><h3>Pitfall 1: PyTorch / Hugging Face CPU Memory Bloat</h3><ul><li><strong>Symptom:</strong> Memory consumption rapidly inflates to <strong>22–26 GB RAM</strong>, forcing system memory into disk swap (1.5+ GB Swap), driving per-query execution times past <strong>2 minutes</strong>, and spiking CPU load averages over 9.0.</li><li><strong>Root Cause:</strong> Standard PyTorch transformers on CPU loads full floating-point weights, expands uncompressed intermediate activation buffers, and initializes heavy C++ CUDA/CPU background thread pools.</li><li><strong>Solution:</strong> Replace PyTorch with <strong>llama-cpp-python</strong> or <strong>Ollama</strong> using GGUF quantizations (Q4_K_M or Q8_0). Remove torch, transformers, and accelerate from your pyproject.toml dependencies when targeting CPU-only edge deployments.</li></ul><h3>Pitfall 2: Streamlit Model Instance Stacking</h3><ul><li><strong>Symptom:</strong> RAM consumption starts around ~2 GB but grows by +2 GB every time a user submits a query or clicks a UI button, eventually causing system crash or swap thrashing.</li><li><strong>Root Cause:</strong> Streamlit reruns the entire Python script top-to-bottom on state changes. Without explicit caching, every execution instantiates a new copy of the model in memory.</li><li><strong>Solution:</strong> Wrap model initialization logic inside @st.cache_resource. This guarantees exactly <strong>one instance</strong> remains resident in RAM (~1.8 GB footprint).</li></ul><h3>Pitfall 3: Unconstrained KV-Cache Context Pre-Allocation</h3><ul><li><strong>Symptom:</strong> Setting n_ctx=131072 (128K) on startup causes llama.cpp to instantly allocate 4–8 GB of RAM purely for the Key-Value (KV) cache matrix before generating a single token.</li><li><strong>Root Cause:</strong> C++ inference engines pre-allocate contiguous memory arrays based on max context parameters.</li><li><strong>Solution:</strong> Match n_ctx to the expected task context (e.g., n_ctx=4096 or n_ctx=8192 for desktop SQL auditing). This caps total process RAM strictly below <strong>2.3 GB</strong>.</li></ul><h3>Key Takeaways &amp; Recommendations</h3><p>LiquidAI’s LFM2.5–2.6B redefines the efficiency frontier for small, specialized language models.</p><h3>Recommended Edge Use Cases:</h3><ul><li><strong>On-Device Data Extraction &amp; Auditing</strong>: Querying local SQLite, DuckDB, or Parquet files with zero cloud telemetry.</li><li><strong>Local Retrieval-Augmented Generation (RAG)</strong>: Processing local PDF contracts, internal documentation, and code repositories within a targeted context budget.</li><li><strong>Structured JSON &amp; Agent Tool Execution</strong>: Reliable function calling for edge IoT devices, terminal automations, and desktop assistants.</li><li><strong>Privacy-Constrained Workflows</strong>: Legal, healthcare, and financial audits where data cannot leave the local machine perimeter.</li></ul><h3>When to Consider Larger Cloud Models:</h3><ul><li><strong>Complex Multi-File Software Engineering</strong>: Multi-step code refactoring across massive repositories still benefits from 70B+ or frontier reasoning models.</li><li><strong>Broad Knowledge Trivia &amp; Open-Ended Synthesis</strong>: Open-domain world knowledge without local document retrieval is naturally constrained by a 2.6B parameter footprint.</li></ul><p>By deploying LFM2.5-2.6B with uv, llama-cpp-python (GGUF), and proper application caching, developers can build responsive, intelligent, and completely private desktop agent systems operating reliably under a <strong>2.5 GB RAM cap</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21ae9f17a110" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deterministic Control Over Non-Deterministic AI: Why Production Agents Demand PydanticAI and…]]></title>
            <link>https://medium.com/@DataDo/deterministic-control-over-non-deterministic-ai-why-production-agents-demand-pydanticai-and-b31a3048b297?source=rss-cf37407d7ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b31a3048b297</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[pydantic-ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Data Do GmbH]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 12:11:39 GMT</pubDate>
            <atom:updated>2026-10-12T12:11:39.668Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deterministic Control Over Non-Deterministic AI: Why Production Agents Demand PydanticAI and LangGraph</h3><p>In production services relying on raw string interpolation, unhandled execution faults stem directly from four output failure modes: dropped mandatory payload keys, string-to-float coercion failures, malformed JSON due to unescaped control characters, and hallucinated object keys. Parsing unstructured model outputs with standard string loaders guarantees runtime crashes downstream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*i0j-wGHNboI5GJxzw-uKjg.png" /></figure><p>Large language models (LLMs) operate as probabilistic prediction engines and fail to adhere to API contracts by default. When an LLM alters a payload schema, standard application stacks fail without explicit deterministic boundaries. To isolate non-deterministic model outputs inside core services, we enforce four operational constraints:</p><ul><li>Strict input and output runtime contracts guaranteed by memory-level type validation.</li><li>Bounded cyclic state graphs that enforce hard step ceilings to eliminate infinite recursion.</li><li>Full OpenTelemetry trace visibility across model calls, schema validation checks, and graph state transitions.</li><li>Deterministic dependency injection to isolate network, database, and infrastructure calls during testing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*nXvQQPizhMRIePQICks4nQ.png" /></figure><h3>1. Structural Schema Enforcement via PydanticAI</h3><p>String-in and string-out execution paradigms shift data validation downstream, delegating error handling to runtime application code. We eliminate this vulnerability by embedding Python typing contracts directly into the LLM execution pipeline via <a href="https://pydantic.dev/pydantic-ai">PydanticAI</a>.</p><p>By defining outputs as standard pydantic.BaseModel objects, we force model responses into typed schemas governed by runtime coercion, numerical range constraints, and field-level validators.</p><p>When an LLM response violates schema parameters, PydanticAI intercepts the validation failure at the framework layer, extracts the precise exception traceback, and appends that structural failure log into a reflection prompt context. The model then executes a self-correction pass before execution returns to the host application logic.</p><pre>from typing import List<br>from pydantic import BaseModel, Field, field_validator<br>from pydantic_ai import Agent, RunContext<br> <br>class RiskAssessment(BaseModel):<br>    account_id: str<br>    risk_score: float = Field(ge=0.0, le=1.0, description=&quot;Normalized risk score between 0.0 and 1.0&quot;)<br>    flagged_categories: List[str]<br>    action_required: bool<br> <br>    @field_validator(&#39;flagged_categories&#39;)<br>    def validate_categories(cls, value: List[str]) -&gt; List[str]:<br>        allowed = {&#39;SUSPICIOUS_IP&#39;, &#39;VELOCITY_EXCEEDED&#39;, &#39;LARGE_TRANSFER&#39;, &#39;NEW_DEVICE&#39;}<br>        invalid = set(value) - allowed<br>        if invalid:<br>            raise ValueError(f&quot;Invalid categories detected: {invalid}. Must be subset of {allowed}&quot;)<br>        return value<br> <br>risk_agent = Agent(<br>    &#39;openai:gpt-4o&#39;,<br>    result_type=RiskAssessment,<br>    system_prompt=&quot;Analyze provided telemetry objects. Classify risk parameters and return structural JSON.&quot;<br>)</pre><p>We encountered a significant framework defect during automated load testing: when an LLM repeatedly fails schema validation, appending multi-line tracebacks into message history causes context length to explode exponentially. At retry counts above 3, context inflation degrades inference latency from 850ms to over 4,200ms per call, while inducing attention drift where the model continuously repeats the identical validation error. We currently hack around this behavior by hard-capping model reflection at max_retries=3, forcing an execution abort and offloading the unparsed payload directly to an async dead-letter queue for offline analysis.</p><h3>2. Deterministic State Machines and Control Flow via LangGraph</h3><p>Managing multi-agent execution using imperative while loops or unstructured chaining creates unmaintainable software architectures. Imperative control loops obfuscate branching logic, conceal state mutations, complicate error recovery, and risk infinite recursive loops that consume compute budget.</p><p>We enforce execution bounds by shifting orchestration into explicit state graphs managed by <a href="https://www.langchain.com/langgraph">LangGraph</a>. By modeling agent interactions as state machines with defined nodes and edges, we maintain explicit control over cyclic execution, step limits, and state transitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*rN_9ncxyoH5xsWkTD90bzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*d9Ja3fCHEL7Yi-JgsB5mhA.png" /></figure><p>We configure LangGraph execution pipelines by defining explicit state schemas and conditional routing logic across graph nodes:</p><pre>from typing import TypedDict, Annotated, Sequence<br>import operator<br>from langchain_core.messages import BaseMessage<br>from langgraph.graph import StateGraph, END<br> <br>class AgentState(TypedDict):<br>    messages: Annotated[Sequence[BaseMessage], operator.add]<br>    account_id: str<br>    risk_data: dict<br>    approval_required: bool<br> <br>def router_node(state: AgentState) -&gt; dict:<br>    return {&quot;account_id&quot;: state[&quot;account_id&quot;]}<br> <br>def evaluate_risk_node(state: AgentState) -&gt; dict:<br>    run_result = risk_agent.run_sync(f&quot;Evaluate account {state[&#39;account_id&#39;]}&quot;)<br>    return {<br>        &quot;risk_data&quot;: run_result.data.model_dump(),<br>        &quot;approval_required&quot;: run_result.data.risk_score &gt; 0.8<br>    }<br> <br>def route_next(state: AgentState) -&gt; str:<br>    if state[&quot;approval_required&quot;]:<br>        return &quot;human_approval&quot;<br>    return &quot;complete&quot;<br> <br>builder = StateGraph(AgentState)<br>builder.add_node(&quot;router&quot;, router_node)<br>builder.add_node(&quot;evaluate_risk&quot;, evaluate_risk_node)<br>builder.set_entry_point(&quot;router&quot;)<br>builder.add_edge(&quot;router&quot;, &quot;evaluate_risk&quot;)<br>builder.add_conditional_edges(<br>    &quot;evaluate_risk&quot;,<br>    route_next,<br>    {<br>        &quot;human_approval&quot;: END,<br>        &quot;complete&quot;: END<br>    }<br>)<br>graph = builder.compile()</pre><p>During high-concurrency stress testing at 500 requests per second, we identified a second unresolved issue: LangGraph’s PostgreSQL checkpointer leaks connection pool slots when saving state histories with payloads exceeding 2MB. Because the framework serializes the complete conversation graph array on every node edge transition, high throughput causes database connection pool exhaustion within 120 seconds. We currently hack around this state bloat by patching the persistence layer with a custom serializer that truncates message context objects older than 5 execution steps prior to writing checkpoint records to disk.</p><h3>3. OpenTelemetry Tracing and Observability via Logfire</h3><p>Standard Application Performance Monitoring (APM) tools fail when applied to non-deterministic agent workflows. A basic HTTP trace captures overall function duration and status codes, but provides no visibility into system prompt construction, model token consumption breakdown, tool parameter schema validation, or retry cycles.</p><p>We address this visibility gap using <a href="https://pydantic.dev/logfire">Pydantic Logfire</a>, an OpenTelemetry-native observability provider built to track structural execution paths without manual log injection across functions.</p><p>Logfire captures and displays four telemetry metrics natively:</p><ul><li>Inference latency per model execution broken down by prompt and completion generation time.</li><li>Exact prompt and completion token counts mapped directly to execution costs.</li><li>Field-level Pydantic validation failures and structural schema auto-correction loops.</li><li>Node transition latencies and edge evaluations across LangGraph execution instances.</li></ul><pre>import logfire<br>from pydantic_ai import Agent<br> <br>logfire.configure(<br>    service_name=&#39;enterprise-risk-engine&#39;,<br>    pydantic_plugin=logfire.PydanticPlugin(record=&#39;all&#39;)<br>)<br> <br>logfire.instrument_pydantic_ai()</pre><p>When an agent encounters a schema failure or triggers a state graph route, Logfire captures the execution tree directly as structured spans:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*y1zlMXXXGL7vkhzYfd2E_Q.png" /></figure><h3>4. Test Isolation via Dependency Injection</h3><p>Production CI/CD pipelines cannot rely on execution tests that issue live calls to external LLM providers or require direct database infrastructure connections. Relying on live external calls during integration testing induces four major pipeline failures:</p><ul><li>Non-deterministic build results caused by API variance.</li><li>Unbounded network latency stalling test suites.</li><li>Variable compute billing on every pull request commit.</li><li>State mutations in shared database environments.</li></ul><p>We enforce test isolation by decoupling application context dependencies such as database connection pools, external APIs, and session managers using PydanticAI’s Deps injection system.</p><p>Tool calls receive context instances using RunContext[Deps]. During production execution, runtime services receive real connection pools. During test runs, tests inject mock dependencies without altering agent implementation logic, tool code, or state routing rules.</p><pre>from dataclasses import dataclass<br>import pytest<br>from pydantic_ai import Agent, RunContext<br> <br>@dataclass<br>class DatabaseDependencies:<br>    async def fetch_transaction_count(self, account_id: str) -&gt; int:<br>        raise NotImplementedError(&quot;Database connection required&quot;)<br> <br>typed_agent = Agent[DatabaseDependencies, RiskAssessment](<br>    &#39;openai:gpt-4o&#39;,<br>    deps_type=DatabaseDependencies,<br>    result_type=RiskAssessment<br>)<br> <br>@typed_agent.tool<br>async def fetch_account_history(ctx: RunContext[DatabaseDependencies], account_id: str) -&gt; int:<br>    return await ctx.deps.fetch_transaction_count(account_id)<br> <br>@pytest.mark.asyncio<br>async def test_risk_agent_isolation():<br>    class MockDatabaseDependencies(DatabaseDependencies):<br>        async def fetch_transaction_count(self, account_id: str) -&gt; int:<br>            return 42<br> <br>    result = await typed_agent.run(<br>        &quot;Evaluate risk profile for account ACC-9901&quot;,<br>        deps=MockDatabaseDependencies()<br>    )<br>    assert result.data.risk_score &gt;= 0.0<br>    assert result.data.account_id == &quot;ACC-9901&quot;</pre><h3>5. End-to-End System Execution Sequence</h3><p>The interaction between client interfaces, state management, schema enforcement, model generation, and telemetry collection follows an explicit runtime execution sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*qbgimtY4u-fp2cvhQev44Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b31a3048b297" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Production RAG: High-Throughput Model Serving with NVIDIA Triton]]></title>
            <link>https://medium.com/@DataDo/scaling-production-rag-high-throughput-model-serving-with-nvidia-triton-d7c009ad9a15?source=rss-cf37407d7ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7c009ad9a15</guid>
            <category><![CDATA[nvidia-triton]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Data Do GmbH]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 12:42:26 GMT</pubDate>
            <atom:updated>2026-10-05T12:42:26.264Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a Retrieval-Augmented Generation (RAG) prototype in a Jupyter notebook is straightforward. Scaling it to handle thousands of concurrent production users is a completely different engineering challenge.</p><p>In previous posts, we focused heavily on optimizing the retrieval layer — from vector indexing strategies to <a href="https://datascientists.info/index.php/2026/05/13/postgres-unified-graph-rag/">unified Graph-RAG</a> architectures in Postgres. However, once your data pipeline is optimized, the operational bottleneck inevitably shifts to the inference layer.</p><p>Relying on external LLM APIs introduces vendor lock-in, unpredictable latencies, and escalating costs. Conversely, wrapping an open-source embedding model or LLM in a standard FastAPI service with Hugging Face Transformers creates severe performance bottlenecks: single-threaded GIL constraints, memory fragmentation, and poor GPU kernel saturation.</p><p>To achieve enterprise-grade throughput and sub-hundred-millisecond p99 latencies, you need a dedicated, C++-backed inference engine. <a href="https://github.com/triton-inference-server/server">NVIDIA Triton Inference Server</a> is the standard industry solution for this problem.</p><h3>The Architectural Bottleneck: Why Native Python Serving Fails</h3><p>When multiple asynchronous requests hit a standard Python web server hosting an AI model, several issues emerge:</p><ol><li><strong>Unbatched GPU Execution:</strong> Each incoming HTTP request triggers its own forward pass on the GPU. Modern Tensor Cores require large, aligned matrices to reach peak TFLOPS; processing requests one-by-one leaves over 80% of GPU compute capacity idle.</li><li><strong>Memory Fragmentation:</strong> Allocating dynamic tensors per request leads to VRAM fragmentation and frequent, costly Out-Of-Memory (OOM) crashes under peak load.</li><li><strong>Application-Level Queuing:</strong> Queueing requests in Python application code adds latency spikes due to event-loop blocking and thread context switching.</li></ol><p>Triton addresses these issues by moving the serving layer into C++, decoupling model execution from the API web worker, and managing GPU hardware scheduling natively.</p><h3>Target Architecture: Unified Inference Hub</h3><p>In a production Agentic RAG system, Triton acts as a centralized inference microservice serving both your vector embedding models (e.g., bge-large-en-v1.5 compiled to ONNX) and your generative models (e.g., Llama-3 via TensorRT-LLM or vLLM backends).</p><p>Communication between your application backends (e.g., FastAPI, <a href="https://datascientists.info/index.php/2026/01/16/ai-agent-workflows-pydantic-ai/">Pydantic AI agents</a>) and Triton occurs over gRPC using HTTP/2 protocol buffers, eliminating HTTP/1.1 JSON serialization overhead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ipcFTvTefxbEadjU.png" /></figure><h3>Dynamic Batching Configuration</h3><p>Triton’s primary throughput driver is <strong>Dynamic Batching</strong>. Instead of executing model inference immediately, Triton holds incoming requests in a lock-free queue for a configurable microsecond window (max_queue_delay_microseconds), concatenates them into a single matrix, and executes one highly efficient GPU kernel pass.</p><p>Here is an abbreviated production config.pbtxt for an ONNX embedding model repository:</p><pre>name: “bge_large_onnx”<br>platform: “onnxruntime_onnx”<br>max_batch_size: 64<br><br>input [<br>{ name: “input_ids”, data_type: TYPE_INT64, dims: [ -1 ] },<br>{ name: “attention_mask”, data_type: TYPE_INT64, dims: [ -1 ] }<br>]<br>output [<br>{ name: “last_hidden_state”, data_type: TYPE_FP32, dims: [ -1, 1024 ] }<br>]<br><br>dynamic_batching {<br>max_queue_delay_microseconds: 5000<br>preferred_batch_size: [ 8, 16, 32, 64 ]<br>}</pre><h3>Production Integration: Async gRPC Client</h3><p>The following Python implementation demonstrates how to integrate Triton into an asynchronous RAG service layer using gRPC:</p><p>import numpy as np<br>import tritonclient.grpc.aio as grpcclient<br>from transformers import AutoTokenizer</p><p>class TritonEmbeddingClient:<br>def <strong>init</strong>(self, triton_url=”localhost:8001″, model=”bge_large_onnx”):<br>self.url, self.model = triton_url, model<br>self.tokenizer = AutoTokenizer.from_pretrained(“BAAI/bge-large-en-v1.5”)</p><pre>async def embed(self, texts: list[str]) -&gt; np.ndarray:<br>    client = grpcclient.InferenceServerClient(url=self.url)<br>    encoded = self.tokenizer(texts, padding=True, truncation=True, return_tensors=&quot;np&quot;)<br>     <br>    inputs = [<br>        grpcclient.InferInput(&quot;input_ids&quot;, encoded[&quot;input_ids&quot;].shape, &quot;INT64&quot;),<br>        grpcclient.InferInput(&quot;attention_mask&quot;, encoded[&quot;attention_mask&quot;].shape, &quot;INT64&quot;)<br>    ]<br>    inputs[0].set_data_from_numpy(encoded[&quot;input_ids&quot;].astype(np.int64))<br>    inputs[1].set_data_from_numpy(encoded[&quot;attention_mask&quot;].astype(np.int64))<br> <br>    res = await client.infer(model_name=self.model, inputs=inputs)<br>    embeddings = res.as_numpy(&quot;last_hidden_state&quot;)[:, 0, :]  # CLS token pooling<br>     <br>    await client.close()<br>    return embeddings / np.linalg.norm(embeddings, axis=1, keepdims=True)</pre><h3>Load Testing &amp; Benchmarking</h3><p>To measure performance under load, use this compact async benchmark script (benchmark_triton.py):</p><pre>import asyncio, time, numpy as np<br>import tritonclient.grpc.aio as grpcclient<br>async def send_req(client, dummy_id, dummy_mask):<br>inputs = [<br>grpcclient.InferInput(&quot;input_ids&quot;, dummy_id.shape, &quot;INT64&quot;),<br>grpcclient.InferInput(&quot;attention_mask&quot;, dummy_mask.shape, &quot;INT64&quot;)<br>]<br>inputs[0].set_data_from_numpy(dummy_id)<br>inputs[1].set_data_from_numpy(dummy_mask)<br>start = time.perf_counter()<br>await client.infer(&quot;bge_large_onnx&quot;, inputs=inputs)<br>return time.perf_counter() - start<br>async def benchmark(total_reqs=1000, concurrency=32):<br>client = grpcclient.InferenceServerClient(&quot;localhost:8001&quot;)<br>ids, mask = np.ones((1, 128), dtype=np.int64), np.ones((1, 128), dtype=np.int64)<br>sem = asyncio.Semaphore(concurrency)</pre><pre>async def worker():<br>    async with sem:<br>        return await send_req(client, ids, mask)<br> <br>t0 = time.perf_counter()<br>latencies = await asyncio.gather(*[worker() for _ in range(total_reqs)])<br>total_time = time.perf_counter() - t0<br> <br>print(f&quot;Throughput: {total_reqs / total_time:.2f} req/s&quot;)<br>print(f&quot;p95 Latency: {np.percentile(latencies, 95) * 1000:.2f} ms&quot;)<br>await client.close()</pre><p>if <strong>name</strong> == “<strong>main</strong>“:<br>asyncio.run(benchmark())</p><h3>Impact: What Improvements Can You Expect?</h3><p>When migrating from a naive Python application (such as FastAPI wrapped around PyTorch/Hugging Face) to Triton with <a href="https://onnxruntime.ai/">ONNX</a> and Dynamic Batching under heavy concurrent traffic:</p><ul><li><strong>10x+ Increase in Throughput:</strong> Dynamic batching merges individual async requests into packed tensor operations, drastically boosting requests per second without adding extra hardware.</li><li><strong>Over 90% Reduction in p99 Tail Latency:</strong> Decoupling web workers from model execution eliminates application-level queueing, keeping tail latency tightly bounded under traffic spikes.</li><li><strong>Predictable VRAM Memory Footprint:</strong> Allocating memory during server warm-up eliminates GPU memory fragmentation and runtime Out-Of-Memory (OOM) failures.</li></ul><h3>Operational Best Practices</h3><ol><li><strong>Decouple Pre-Processing:</strong> Tokenization and text cleaning should occur in your application layer (or a dedicated CPU container) to avoid burning valuable GPU cycles on string manipulations.</li><li><strong>Use gRPC Health Checks:</strong> In Kubernetes deployments, leverage Triton’s native health endpoints (/v2/health/ready and /v2/health/live) for Liveness/Readiness probes.</li><li><strong>Model Versioning:</strong> Maintain strict model artifact management in Object Storage (S3/GCS). Triton can dynamically load or unload new model versions without restarting the server instance.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7c009ad9a15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating the Python Package Release Process]]></title>
            <link>https://medium.com/@DataDo/automating-the-python-package-release-process-9a5e384a3d35?source=rss-cf37407d7ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a5e384a3d35</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[trivy]]></category>
            <dc:creator><![CDATA[Data Do GmbH]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 12:23:54 GMT</pubDate>
            <atom:updated>2026-09-18T12:23:54.827Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern Data Engineering and ML environments, consistently reaching out to the public internet (like PyPI) for every pipeline, test, or notebook spawn is not just a performance bottleneck — it introduces significant supply-chain risks. To address this, our engineering team deploys <strong>DevPi</strong> as an internal Python package proxy and caching index directly into our Kubernetes clusters.</p><p>This post breaks down our high-level architecture, the automated CI/CD lifecycle for custom packages, and the automated security janitor that actively keeps vulnerabilities out of our execution environments.</p><h3>High-Level Architecture &amp; Networking</h3><p>At its core, our DevPi component provides a cluster-local index for all Python workloads. Instead of reaching external repositories directly, notebooks and pipeline jobs communicate with DevPi, which transparently caches necessary packages and serves locally hosted, custom libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*eKoSL9Ze0KSw3Eh6f2HZXg.png" /></figure><h3>Architecture Highlights</h3><ul><li><strong>Service Layer:</strong> DevPi runs behind a Kubernetes ClusterIP service exposing ports 80 and 3141.</li><li><strong>Storage:</strong> Backed by an OBS/S3 volume (/devpi/files) for package artifacts and a PersistentVolumeClaim (/devpi/server) for fast metadata retrieval.</li><li><strong>Routing:</strong> Managed via an Istio Virtual Service, routing both ports to devpi.kubeflow.svc.cluster.local with a 120-second timeout, ensuring seamless in-cluster DNS resolution.</li></ul><h3>Automating the Release Process</h3><p>Publishing internal code to DevPi is highly standardized using a comprehensive GitLab CI/CD release pipeline. We enforce strict quality and security checks before a package ever reaches the index:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*bfg9KTmsqHkUf72ItGEFpg.png" /></figure><ul><li><strong>Linting:</strong> Fast, static code analysis and formatting checks using <a href="https://github.com/astral-sh/ruff">Ruff</a>.</li><li><strong>Testing:</strong> Building the execution environment and running unit tests against package code via pytest.</li><li><strong>Static Security:</strong> Scanning third-party dependencies to generate a Software Bill of Materials (SBOM) to track supply chain compliance.</li><li><strong>Versioning:</strong> Automatic semantic versioning (MAJOR.MINOR.PATCH) calculation based on structured git commit messages.</li><li><strong>Build &amp; Publish:</strong> Compiling binary wheels (.whl) and source distributions (.tar.gz) via Python’s build module, before pushing to DevPi using twine.</li></ul><h3>Active Security: The Trivy Janitor</h3><p>Having an internal registry is excellent for speed, but hosting vulnerable code is dangerous. We built an automated, multi-tiered security flow centered around Trivy to actively scan and remediate our package cache.</p><h3>1. Scheduled Scanning (The Hourly Cron)</h3><p>A Kubernetes CronJob executes hourly to inspect the OBS-backed package cache. An init-container running Trivy scans the read-only mounted volume, reporting only CRITICAL severity vulnerabilities into a shared volume.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*9axqfGXTtEADF9jm9KC5zA.png" /></figure><h3>2. Event-Driven Scanning (Upload Triggers)</h3><p>We do not wait for the hourly job if new packages arrive. We integrate <strong>Argo Events</strong> to monitor package uploads in real time:</p><ul><li>An EventSource exposes a webhook listening for OBS uploads on port 12000.</li><li>A Sensor filters incoming events, reacting only to relevant artifacts ending in .whl, .tar.gz, or .zip.</li><li>When a match is found, a one-off Kubernetes Job is triggered to immediately scan the new artifacts with Trivy.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*PegbyIEozuk1npubkXyspg.png" /></figure><h3>3. Automated Remediation (The Janitor Script)</h3><p>Scanning is only half the battle. Our custom Python janitor.py container takes over right after Trivy finishes. It parses the JSON output looking for vulnerable package names. If critical threats are found, the script automatically:</p><ol><li>Applies a strict <strong>NetworkPolicy</strong> (isolate-notebooks) limiting ingress and egress traffic for the vulnerable environment (e.g., in the kubeflow namespace).</li><li>Updates the DevPi index configuration via the CLI to whitelist substitute the affected packages, preventing further pulls.</li></ol><h3>Developer Quickstart: Using DevPi</h3><p>For developer environments and CI runners wanting to interact with the cache, environment variables easily point Python tooling to DevPi.</p><h3>Configuration</h3><pre>import os<br>DEVPI_HOST = &quot;devpi.kubeflow.svc.cluster.local&quot;<br>DEVPI_PORT = &quot;3141&quot;<br># Environment configuration for pip and twine<br>os.environ[&quot;PIP_INDEX_URL&quot;] = f&quot;http://{DEVPI_HOST}:{DEVPI_PORT}/root/pypi/+simple/&quot;<br>os.environ[&quot;PIP_TRUSTED_HOST&quot;] = DEVPI_HOST<br>os.environ[&quot;DEVPI_URL&quot;] = f&quot;http://{DEVPI_HOST}:{DEVPI_PORT}&quot;<br>os.environ[&quot;DEVPI_INDEX_URL&quot;] = f&quot;http://{DEVPI_HOST}:{DEVPI_PORT}/root/dev/&quot;<br>os.environ[&quot;TWINE_REPOSITORY_URL&quot;] = f&quot;http://{DEVPI_HOST}:{DEVPI_PORT}/root/dev/&quot;</pre><h3>Installing Packages</h3><p>Once configured, you can simply use standard pip with the formulated simple index endpoint:</p><pre>import subprocess<br>import sys<br>import os<br>devpi_index_url = os.environ[&quot;DEVPI_INDEX_URL&quot;]<br>trusted_host = os.getenv(&quot;PIP_TRUSTED_HOST&quot;, &quot;devpi.kubeflow.svc.cluster.local&quot;)<br>simple_index_url = devpi_index_url.rstrip(&quot;/&quot;) + &quot;/+simple/&quot;<br>subprocess.run([<br>    sys.executable, &quot;-m&quot;, &quot;pip&quot;, &quot;install&quot;,<br>    &quot;--index-url&quot;, simple_index_url,<br>    &quot;--trusted-host&quot;, trusted_host,<br>    &quot;your-custom-package==0.1.0&quot;<br>], check=True)</pre><h3>Building a Resilient Python Infrastructure</h3><p>Bringing DevPi inside your Kubernetes boundary converts an unpredictable external dependency into a managed, high-speed utility. By pairing cluster-local package caching with an automated remediation loop driven by Trivy and Argo Events, engineering teams eliminate external bandwidth dependencies and active security risks simultaneously. This setup provides data science and engineering teams with the speed of local package management alongside the strict governance required for production enterprise platforms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a5e384a3d35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Closed-Loop RAG Flywheel: Operationalizing Expert Feedback to Reduce Hallucinations]]></title>
            <link>https://medium.com/@DataDo/building-a-closed-loop-rag-flywheel-operationalizing-expert-feedback-to-reduce-hallucinations-c8ec00fbc33e?source=rss-cf37407d7ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8ec00fbc33e</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[datado]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Data Do GmbH]]></dc:creator>
            <pubDate>Fri, 04 Sep 2026 08:13:46 GMT</pubDate>
            <atom:updated>2026-09-04T08:13:46.668Z</atom:updated>
            <content:encoded><![CDATA[<p>Standard Retrieval-Augmented Generation (RAG) pipelines often encounter quality ceilings in production. While synthetic benchmarks and evaluation frameworks like RAGAS provide initial visibility into pipeline health, systematically addressing domain-specific hallucinations requires integrating human review directly into system updates.</p><p>Rather than relying on massive annotation projects or constant LLM fine-tuning, a multi-tiered feedback flywheel routes routine domain expert reviews to the appropriate layer of a RAG architecture — ranging from low-latency runtime prompt injections to periodic re-ranker fine-tuning.</p><h3>The Four-Tiered Optimization Hierarchy</h3><p>To minimize implementation overhead while ensuring quick fixes for critical errors, expert feedback is routed based on system level and operational effort:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*cHFOQip2HteOXCFjNzvwtQ.png" /></figure><h3>Architecture &amp; Data Flow</h3><p>This loop decouples immediate behavioral fixes at runtime from longer-term retrieval optimization and automated quality gating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*xBpS4z4x8_h2fjaAhc-3_Q.png" /></figure><h3>Detailed System Breakdown</h3><h3>Ingestion via Streamlit Triage</h3><p>A lightweight Streamlit interface presents logged queries, retrieved semantic chunks (with individual chunk IDs), and LLM outputs side-by-side. When a domain expert marks a query as a <em>Hallucination</em>, selects the relevant chunks, and inputs an <em>Ideal Grounded Response</em>, the application routes the structured payload directly into downstream stores.</p><h3>Priority 1: Sub-10ms Dynamic Few-Shotting</h3><p>When a hallucination fix is logged, the system embeds the raw user query and ideal response pair into a dedicated, low-latency <strong>Few-Shot Vector Table</strong>.</p><p>At runtime:</p><ul><li>Before query expansion or document search occurs, the production pipeline runs a sub-10ms similarity lookup against this table using the raw user vector.</li><li>If a match exceeds a set threshold (e.g., cosine distance $\ge 0.82$), the top historical corrections ($k=2$) are injected into the system prompt as positive demonstrations.</li><li>Performing this lookup <strong>before query expansion</strong> maintains intent matching precision, enforcing refusal rules and domain formatting without requiring model retraining.</li></ul><h3>Priority 2 &amp; 3: Search Precision &amp; Corpus Hygiene</h3><ul><li><strong>Re-Ranker Tuning</strong>: When experts flag retrieval failures, the system compiles contrastive triplets: (User Query, Expert-Selected Chunk [Pos], Noise Chunk [Neg]). Over time, this dataset is used to fine-tune a cross-encoder (e.g., BGE-Reranker) to filter domain noise before context reaches the LLM.</li><li><strong>Metadata Patching</strong>: If an error stems from outdated or corrupt source texts, an exclusion flag is set in the chunk’s vector metadata to drop it during pre-retrieval filtering, while logging a remediation task for content maintainers.</li></ul><h3>Continuous Regression Testing</h3><p>All expert-approved outputs populate a permanent <strong>Golden Benchmark Dataset</strong>. Before a new system prompt, embedding model, or LLM version is merged into production, an automated CI/CD pipeline evaluates the release against this golden set using key RAGAS metrics (<em>Faithfulness</em>, <em>Context Precision</em>, <em>Context Recall</em>, <em>Answer Relevance</em>). Deployments that drop below baseline thresholds are automatically held.</p><h3>Core Engineering Outcomes</h3><ul><li><strong>Faster Remediation</strong>: Reduces time-to-fix for prompt-sensitive errors by deploying dynamic few-shot examples without full model retraining.</li><li><strong>Structured Data Collection</strong>: Daily expert annotations naturally build domain-specific training triplets and evaluation datasets over time.</li><li><strong>Clear Separation of Concerns</strong>: Software engineers maintain pipeline infrastructure while domain experts guide model behavior through a standardized review interface.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8ec00fbc33e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Temporal Data Lineage for Auditing]]></title>
            <link>https://medium.com/@DataDo/temporal-data-lineage-for-auditing-acae89cbe720?source=rss-cf37407d7ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/acae89cbe720</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[auditing]]></category>
            <dc:creator><![CDATA[Data Do GmbH]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 11:36:00 GMT</pubDate>
            <atom:updated>2026-08-13T11:36:00.877Z</atom:updated>
            <content:encoded><![CDATA[<p>Destructive updates in traditional relational databases overwrite history, causing immediate spoliation of evidence during regulatory discovery. When an auditor queries a system state, standard log files provide fragmented temporal approximations rather than deterministic database snapshots.</p><p>Destructive updates in traditional relational databases overwrite history, causing immediate spoliation of evidence during regulatory discovery. When an auditor queries a system state, standard log files provide fragmented temporal approximations rather than deterministic database snapshots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GWpPgMmVNLcyC2we.png" /></figure><p>We enforce deterministic data lineage across four statutory domain environments where automated decisions intersect with legal liability:</p><ul><li><strong>Financial AML &amp; Fraud Detection:</strong> Under regulatory frameworks such as the EU Anti-Money Laundering Directives and the US BSA/Patriot Act, financial institutions must prove the precise historical entity relationships and transaction context present when an automated Suspicious Activity Report (SAR) was triggered or suppressed.</li><li><strong>Government Registries &amp; Real Estate:</strong> Automating beneficial ownership tracking under statutory mandates — such as the German Transparency Register (<em>Transparenzregister</em>) governed by the Money Laundering Act (<em>Geldwäschegesetz — GwG</em>) — requires an unalterable history of ownership chain transformations across decades.</li><li><strong>Healthcare &amp; Life Sciences:</strong> AI-driven clinical decision support tools and automated diagnostic pipelines regulated under FDA and EMA guidelines must trace every generated output back to the exact version of the medical literature and patient state active at the microsecond of care delivery.</li><li><strong>RegTech &amp; AI Legal Synthesis:</strong> When Retrieval-Augmented Generation (RAG) systems ingest and synthesize regulatory guidance for automated contract drafting or compliance checking, organizations must prove the LLM retrieved verified, un-tampered document snapshots valid at transaction time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*1nQE6R-6qcX6CjBTpKuSqw.png" /></figure><h3>Layer 1: System-Versioned Temporal Logging (sys_period) in Relational Stores</h3><p>Updating a vector index or replacing a chunk in a knowledge base without temporal tracing creates an un-auditable system state. If an AI agent provides compliance advice based on a document chunk at $T_1$, and that chunk is re-embedded or modified at $T_2$, traditional databases overwrite the past. During legal discovery, the system loses the ability to prove what knowledge context the model retrieved.</p><p>By implementing sys_period logging on knowledge stores, time becomes an explicit dimension within the database engine itself.</p><h3>Half-Open Temporal Ranges (tstzrange)</h3><p>Instead of tracking a single updated_at timestamp, every document chunk, system prompt version, and embedding reference contains a sys_period column defined as a PostgreSQL tstzrange (timestamp with time zone range).</p><p>This captures the continuous interval during which a specific knowledge state was active:</p><p>sys_period=[tstart,tend]{sys\_period} = [t_{\text{start}}, t_{\text{end}}]</p><p>We define interval boundaries using four exact rules:</p><ul><li><strong>Inclusive lower bound ($t_{\text{start}}$):</strong> The microsecond transaction timestamp (transaction_timestamp()) generated when the record was ingested or modified.</li><li><strong>Exclusive upper bound ($t_{\text{end}}$):</strong> The microsecond transaction timestamp generated when the record was superseded, soft-deleted, or re-embedded.</li><li><strong>Unbounded upper state:</strong> Active records available for live retrieval carry an upper bound of infinity.</li><li><strong>Half-open boundary isolation:</strong> Representing bounds as $[t_{\text{start}}, t_{\text{end}})$ prevents duplicate retrievals at boundary microseconds. If Version 1 closes at 08:30:00.000 and Version 2 opens at 08:30:00.000, an automated retrieval query executed at 08:30:00.000 evaluates to exactly one record state.</li></ul><pre>Active Chunk Version:     [ 2026-01-15 10:00:00+00,  infinity )<br>Deprecated Chunk Version: [ 2026-01-15 10:00:00+00,  2026-06-01 08:30:00+00 )</pre><h3>Temporal Exclusion Constraints</h3><p>Modifying a document chunk without strict concurrency controls causes race conditions and overlapping temporal ranges. In a temporal framework, uniqueness is enforced across both entity identity and valid time windows.</p><p>We configure PostgreSQL Exclusion Constraints backed by Generalized Search Tree (GiST) indexes via the btree_gist extension:</p><pre>CREATE EXTENSION IF NOT EXISTS btree_gist;<br>CREATE EXTENSION IF NOT EXISTS vector;</pre><pre>CREATE TABLE rag_knowledge_chunks (<br>    chunk_id UUID NOT NULL,<br>    document_id UUID NOT NULL,<br>    chunk_index INT NOT NULL,<br>    chunk_content TEXT NOT NULL,<br>    embedding vector(1536),<br>    metadata JSONB DEFAULT &#39;{}&#39;::jsonb,<br>    sys_period TSTZRANGE NOT NULL DEFAULT tstzrange(transaction_timestamp(), &#39;infinity&#39;, &#39;[)&#39;),<br>    <br>    PRIMARY KEY (chunk_id, sys_period),<br>    <br>    -- Enforce: No duplicate chunk_ids can exist with overlapping temporal ranges<br>    CONSTRAINT no_overlapping_chunk_periods <br>    EXCLUDE USING gist (chunk_id WITH =, sys_period WITH &amp;&amp;)<br>);</pre><p>The operator chunk_id WITH = isolates checks to the exact semantic entity, while sys_period WITH &amp;&amp; evaluates range overlaps. If an ingestion worker attempts to write a chunk version whose temporal range overlaps an existing active range for that chunk_id, PostgreSQL rejects the transaction at the database kernel boundary.</p><p>Continuous temporal updates cause severe GiST spatial tree degradation over time. While PostgreSQL autovacuum cleans dead tuple slots, it fails to rebalance GiST internal bounding boxes as timestamp ranges advance continuously. We observed severe index bloat and read latency degradation on high-throughput write paths. Executing a standard REINDEX acquires an ACCESS EXCLUSIVE lock that halts active incoming read and write transactions. We have not fully resolved online GiST index compaction without incurring significant background CPU contention, so we are currently hacking around this issue by executing REINDEX INDEX CONCURRENTLY inside scheduled off-peak maintenance cron jobs.</p><h3>Layer 2: PL/pgSQL Trigger Architecture &amp; State Evolution</h3><p>The database operational layout couples the active query table with an immutable history archive through a kernel-level PL/pgSQL trigger execution boundary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*6AbaY3UhRdbRjkoBXRDO8w.png" /></figure><h3>Knowledge Lifecycle Mechanics</h3><p>The relational engine manages historical state updates through a twin-table structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*3wso2xbb3W1scEP5lTD5mA.png" /></figure><p>We define state transformations across four operational phases:</p><ul><li><strong>State Ingestion (</strong><strong>INSERT):</strong> A regulatory document chunk is embedded at T1. The database initializes sys_period to (T,infty).</li><li><strong>State Mutation (</strong><strong>UPDATE):</strong> The underlying document is re-chunked at T2. The active row&#39;s upper boundary is capped at T2 and copied to rag_knowledge_chunks_history. A new row containing updated text and vector embeddings is inserted into rag_knowledge_chunks with {sys_period} = [T_2, infty].</li><li><strong>State Deprecation (</strong><strong>DELETE):</strong> When a document is retracted at T3, the database removes the row from rag_knowledge_chunks and writes a closed record to rag_knowledge_chunks_history with {sys_period} = [T1, T3].</li><li><strong>Deterministic Read Selection (</strong><strong>SELECT):</strong> Active queries read rag_knowledge_chunks directly without traversing historical record archives.</li></ul><h3>PL/pgSQL Trigger Function</h3><p>To keep backend application code free of temporal versioning logic, state archiving is offloaded entirely to database triggers:</p><pre>-- Mirror table for historical storage<br>CREATE TABLE rag_knowledge_chunks_history (LIKE rag_knowledge_chunks);</pre><pre>-- State management trigger function<br>CREATE OR REPLACE FUNCTION process_rag_chunk_sys_period()<br>RETURNS TRIGGER AS $$<br>DECLARE<br>    sys_now TIMESTAMPTZ := transaction_timestamp();<br>BEGIN<br>    -- Handle Chunk Updates (Re-embedding / Text Edits)<br>    IF (TG_OP = &#39;UPDATE&#39;) THEN<br>        OLD.sys_period := tstzrange(lower(OLD.sys_period), sys_now, &#39;[)&#39;);<br>        INSERT INTO rag_knowledge_chunks_history SELECT OLD.*;</pre><pre>        NEW.sys_period := tstzrange(sys_now, &#39;infinity&#39;, &#39;[)&#39;);<br>        RETURN NEW;<br>        <br>    -- Handle Chunk Deprecation / Removal<br>    ELSIF (TG_OP = &#39;DELETE&#39;) THEN<br>        OLD.sys_period := tstzrange(lower(OLD.sys_period), sys_now, &#39;[)&#39;);<br>        INSERT INTO rag_knowledge_chunks_history SELECT OLD.*;<br>        RETURN OLD;<br>    END IF;<br>    RETURN NULL;<br>END;<br>$$ LANGUAGE plpgsql;</pre><pre>-- Attach invariant trigger<br>CREATE TRIGGER trg_rag_chunks_sys_period<br>BEFORE UPDATE OR DELETE ON rag_knowledge_chunks<br>FOR EACH ROW EXECUTE FUNCTION process_rag_chunk_sys_period();</pre><p>We explicitly set temporal markers using transaction_timestamp() rather than clock_timestamp(). transaction_timestamp() guarantees that all state mutations occurring within a single explicit transaction block receive identical time boundaries, preserving transaction isolation across complex batch updates.</p><h3>Point-in-Time State Reconstruction Mechanics</h3><p>To reproduce the exact database state available during an automated decision on March 15, 2026, at 14:30:00 UTC, we execute a point-in-time (AS OF) reconstruction query using the PostgreSQL containment operator @&gt;:</p><pre>SELECT <br>    chunk_id, <br>    document_id, <br>    chunk_content, <br>    metadata,<br>    sys_period<br>FROM (<br>    SELECT * FROM rag_knowledge_chunks<br>    UNION ALL<br>    SELECT * FROM rag_knowledge_chunks_history<br>) AS continuous_knowledge_base<br>WHERE sys_period @&gt; &#39;2026-03-15 14:30:00+00&#39;::timestamptz<br>  AND document_id = &#39;c7a42b10-8e12-4c91-9e05-2d4e8b31411f&#39;;</pre><h3>Range Partitioning for Historical Scales</h3><p>As historical archives exceed tens of millions of rows, GiST traversal latencies increase. To maintain flat sub-millisecond lookup times, we enforce declarative range partitioning on rag_knowledge_chunks_history using the lower bound of sys_period:</p><pre>CREATE TABLE rag_knowledge_chunks_history (<br>    chunk_id UUID NOT NULL,<br>    document_id UUID NOT NULL,<br>    chunk_index INT NOT NULL,<br>    chunk_content TEXT NOT NULL,<br>    embedding vector(1536),<br>    metadata JSONB DEFAULT &#39;{}&#39;::jsonb,<br>    sys_period TSTZRANGE NOT NULL<br>) PARTITION BY RANGE (lower(sys_period));</pre><pre>CREATE TABLE rag_knowledge_chunks_history_y2026m03 <br>PARTITION OF rag_knowledge_chunks_history<br>FOR VALUES FROM (&#39;2026-03-01 00:00:00+00&#39;) TO (&#39;2026-04-01 00:00:00+00&#39;);</pre><pre>CREATE TABLE rag_knowledge_chunks_history_y2026m04 <br>PARTITION OF rag_knowledge_chunks_history<br>FOR VALUES FROM (&#39;2026-04-01 00:00:00+00&#39;) TO (&#39;2026-05-01 00:00:00+00&#39;);</pre><p>Partition pruning excludes non-relevant partition tables from the execution plan during point-in-time queries, keeping working sets inside the active PostgreSQL buffer pool.</p><h3>API Exposure via Asynchronous FastAPI Services</h3><p>The service layer exposes temporal query interfaces over HTTP, mapping incoming point-in-time requests to underlying PostgreSQL queries using SQLAlchemy Async sessions.</p><pre>from datetime import datetime<br>from typing import Optional<br>from uuid import UUID<br>from fastapi import FastAPI, Depends, Query, HTTPException, Header<br>from sqlalchemy.ext.asyncio import AsyncSession<br>from sqlalchemy import text</pre><pre>app = FastAPI(title=&quot;Deterministic Lineage API&quot;, version=&quot;1.0.0&quot;)</pre><pre>@app.get(&quot;/api/v1/knowledge/chunks/{chunk_id}&quot;)<br>async def get_chunk_as_of(<br>    chunk_id: UUID,<br>    as_of: Optional[datetime] = Query(None, description=&quot;Point-in-time timestamp for historical reconstruction&quot;),<br>    x_legal_basis_id: str = Header(..., description=&quot;Mandatory legal audit justification ID&quot;),<br>    x_operator_id: str = Header(..., description=&quot;Authenticated operator ID&quot;),<br>    db: AsyncSession = Depends(get_db_session)<br>):<br>    # Set localized session variables for PostgreSQL WAL/pg_audit logging<br>    await db.execute(<br>        text(&quot;SET LOCAL audit.context = :ctx&quot;), <br>        {&quot;ctx&quot;: f&quot;operator:{x_operator_id};legal_basis:{x_legal_basis_id}&quot;}<br>    )<br>    <br>    target_time = as_of or datetime.now()<br>    <br>    query = text(&quot;&quot;&quot;<br>        SELECT chunk_id, document_id, chunk_content, metadata, lower(sys_period) as valid_from<br>        FROM (<br>            SELECT * FROM rag_knowledge_chunks<br>            UNION ALL<br>            SELECT * FROM rag_knowledge_chunks_history<br>        ) AS unified_chunks<br>        WHERE chunk_id = :chunk_id <br>          AND sys_period @&gt; :target_time::timestamptz<br>    &quot;&quot;&quot;)<br>    <br>    result = await db.execute(query, {&quot;chunk_id&quot;: chunk_id, &quot;target_time&quot;: target_time})<br>    record = result.mappings().first()<br>    <br>    if not record:<br>        raise HTTPException(status_code=404, detail=&quot;No active chunk state found at specified timestamp&quot;)<br>        <br>    return record</pre><p>We integrate four security and audit specifications into the API layer:</p><ul><li><strong>Auditor Session Context:</strong> Executing SET LOCAL audit.context writes operator identity and statutory justification codes directly into PostgreSQL Write-Ahead Logs (pg_audit).</li><li><strong>Schema Validation:</strong> Pydantic serialization models validate all payload parameters, requiring explicit statutory authorization codes on write and point-in-time read operations.</li><li><strong>Access Control Isolation:</strong> OAuth2/OIDC integration enforces Role-Based Access Control (RBAC) and Row-Level Security (RLS) policies based on auditor jurisdiction.</li><li><strong>OpenAPI Metadata Generation:</strong> The endpoint schema auto-generates compliance documentation exposed directly to internal regulatory tools.</li></ul><p>Executing SET LOCAL audit.context inside asynchronous connection pools (Asyncpg via SQLAlchemy) presents severe connection contamination risks. If an unhandled exception aborts a request before an explicit transaction rollback or commit occurs, residual session variables remain attached to the pooled database connection. Subsequent requests re-using that connection inherit stale audit metadata. We have not fully resolved native connection state reset handling in Asyncpg, so we are currently hacking around this issue by executing RESET ALL; DISCARD TEMP; via a connection checkout event hook, adding 0.4ms to total request overhead.</p><h3>Layer 3: Grounding Non-Deterministic RAG Outputs in Relational Lineage</h3><p>Non-deterministic machine learning model outputs must anchor directly to deterministic relational records. Re-running vector searches without temporal constraints causes context drift when knowledge collections undergo updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*_6IgBe6zpZyX5KNTRUrhxQ.png" /></figure><p>Vector embeddings stored via pgvector map directly to primary keys in system-versioned temporal tables at microsecond $T$. To establish complete model auditability, we log an immutable execution metadata tuple alongside relational primary keys:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*kPJxHOnnK5wCT1Ky9doIrQ.png" /></figure><p>where H is the SHA-256 hash of the system prompt template, V is the model version string, T is the transaction microsecond, S is the fixed seed integer (Temperature = 0), and K is the array of chunk primary keys valid at timestamp T.</p><pre>import hashlib<br>from dataclasses import dataclass<br>from typing import List<br>from uuid import UUID<br><br>@dataclass<br>class DeterministicRAGAuditLog:<br>    prompt_hash: str<br>    model_version: str<br>    timestamp_epoch_us: int<br>    seed: int<br>    chunk_keys: List[UUID]<br>def build_audit_record(<br>    prompt_template: str,<br>    model_version: str,<br>    timestamp_us: int,<br>    seed: int,<br>    retrieved_chunk_ids: List[UUID]<br>) -&gt; DeterministicRAGAuditLog:<br>    p_hash = hashlib.sha256(prompt_template.encode(&quot;utf-8&quot;)).hexdigest()<br>    <br>    return DeterministicRAGAuditLog(<br>        prompt_hash=p_hash,<br>        model_version=model_version,<br>        timestamp_epoch_us=timestamp_us,<br>        seed=seed,<br>        chunk_keys=retrieved_chunk_ids<br>    )</pre><p>Replaying K through the @&gt; containment query engine reconstructs the raw statutory context retrieved at timestamp T, eliminating context drift across model execution runs.</p><h3>Architectural Metric Matrix</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*1HUI9yqXWYFBcxSRKT_PWg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acae89cbe720" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Pure Vectors: Implementing High-Precision Hybrid Search Natively inside Postgres]]></title>
            <link>https://medium.com/@DataDo/beyond-pure-vectors-implementing-high-precision-hybrid-search-natively-inside-postgres-23c85a9d7884?source=rss-cf37407d7ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/23c85a9d7884</guid>
            <category><![CDATA[analytics-platforms]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Data Do GmbH]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 07:46:30 GMT</pubDate>
            <atom:updated>2026-08-07T07:46:30.581Z</atom:updated>
            <content:encoded><![CDATA[<p>We observed a 500ms synchronization lag when separating our storage engine from an external search cluster, which causes broken user experiences when resolving exact alphanumeric queries. Dense embeddings capture abstract semantic meaning but fail at exact keyword matching, causing queries for precise serial numbers like X-992-B, legacy product SKUs, or industry-specific jargon like Kubernetes to return incorrect results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bs1NmG-XNnVDiHTR.png" /></figure><p>We reject the industry reaction of deploying separate enterprise search clusters (such as Elasticsearch or OpenSearch) or specialized vector databases alongside the primary database. This architecture forces the maintenance of two separate data stores, creates eventual consistency issues, doubles infrastructure costs, and introduces complex synchronization pipelines. We enforce high-precision hybrid search natively inside <a href="https://github.com/pgvector/pgvector">PostgreSQL</a>, combining dense semantic vector embeddings with neural sparse lexical vectors (sparsevec) within a single ACID-compliant transactional boundary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*4m9A2o64iZqBHAFYKMzT0w.png" /></figure><h3>Step 1: Designing the Dual-Vector Schema</h3><p>We build a table structure that stores raw entity data alongside two distinct vector formats: a standard 1536-dimension dense vector for abstract semantic context, and a 32,000-dimension sparsevec column representing neural lexical term mappings generated via models like SPLADE or BGE-M3.</p><pre>-- Enable the pgvector extension (Requires v0.7.0+ for sparsevec support)<br>CREATE EXTENSION IF NOT EXISTS vector;<br><br>-- Create high-precision product catalog table<br>CREATE TABLE products (<br>    id SERIAL PRIMARY KEY,<br>    sku VARCHAR(50) UNIQUE NOT NULL,<br>    title TEXT NOT NULL,<br>    description TEXT,<br>    category VARCHAR(100),<br>    <br>    -- 1536-dimension dense embedding for semantic context<br>    dense_embedding vector(1536),<br>    <br>    -- 32,000-dimension sparse vector for lexical precision<br>    sparse_embedding sparsevec(32000)<br>);</pre><blockquote><strong><em>Engineering Note:</em></strong><em> The </em><em>sparsevec(32000) type defines the total maximum vocabulary size of the sparse embedding model. PostgreSQL dynamically optimizes disk storage, writing data exclusively for elements containing non-zero weights to maximize memory and disk efficiency.</em></blockquote><h3>Step 2: Dual-HNSW Index Strategy for Performance</h3><p>To maintain rapid retrieval times as the dataset scales into millions of rows, we deploy two distinct Hierarchical Navigable Small World (HNSW) graphs.</p><pre>-- Create an HNSW index using Cosine Distance for dense vector search<br>CREATE INDEX idx_products_dense_hnsw ON products USING hnsw (dense_embedding vector_cosine_ops)<br>WITH (m = 16, ef_construction = 64);<br><br>-- Create an HNSW index using Inner Product for sparse lexical search<br>CREATE INDEX idx_products_sparse_hnsw ON products USING hnsw (sparse_embedding sparsevec_ip_ops)<br>WITH (m = 16, ef_construction = 64);</pre><p>We score sparse vector matches using Inner Product (sparsevec_ip_ops), as the magnitude represents the absolute keyword and term weight generated by lexical models.</p><h3>Step 3: Implementing Reciprocal Rank Fusion (RRF) Natively</h3><p>We observed that direct scalar addition ($DenseScore + SparseScore$) fails because the scale of cosine distance differs fundamentally from sparse inner-product scaling. We enforce Reciprocal Rank Fusion (RRF) to evaluate the relative position (rank) of an item in both result sets instead of its raw score.</p><p>The formula for the RRF score of a document $d$ is:</p><p>RRF_Score(d)=∑m∈M11+xi(d)RRF\_Score(d) = \sum_{m \in M} \frac{1}{1 + x_i(d)}</p><p>Where $M$ is the set of search strategies (Dense and Sparse), $r_m(d)$ is the rank of document $d$ within strategy $m$, and $k$ is a constant smoothing factor set to 60 to prevent low-ranked items from heavily skewing the results.</p><p>We execute this hybrid search in a single database round-trip using a custom SQL function:</p><pre>CREATE OR REPLACE FUNCTION hybrid_neural_search(<br>    query_dense vector,<br>    query_sparse sparsevec,<br>    match_limit INT DEFAULT 10,<br>    smoothing_k INT DEFAULT 60<br>)<br>RETURNS TABLE (<br>    id INT,<br>    sku VARCHAR,<br>    title TEXT,<br>    category VARCHAR,<br>    combined_score NUMERIC<br>) AS $$<br>WITH dense_results AS (<br>    SELECT <br>        id, <br>        ROW_NUMBER() OVER (ORDER BY dense_embedding &lt;=&gt; query_dense) as rank<br>    FROM products<br>    ORDER BY dense_embedding &lt;=&gt; query_dense<br>    LIMIT (match_limit * 3)<br>),<br>sparse_results AS (<br>    SELECT <br>        id, <br>        -- &lt;#&gt; operator returns negative inner product to sort highest score first<br>        ROW_NUMBER() OVER (ORDER BY sparse_embedding &lt;#&gt; query_sparse) as rank<br>    FROM products<br>    ORDER BY sparse_embedding &lt;#&gt; query_sparse<br>    LIMIT (match_limit * 3)<br>)<br>SELECT <br>    p.id, <br>    p.sku, <br>    p.title, <br>    p.category,<br>    COALESCE(1.0 / (smoothing_k + d.rank), 0.0) + <br>    COALESCE(1.0 / (smoothing_k + s.rank), 0.0) AS combined_score<br>FROM products p<br>LEFT JOIN dense_results d ON p.id = d.id<br>LEFT JOIN sparse_results s ON p.id = s.id<br>WHERE d.id IS NOT NULL OR s.id IS NOT NULL<br>ORDER BY combined_score DESC<br>LIMIT match_limit;<br>$$ LANGUAGE sql STABLE;</pre><h3>Step 4: Optimization Guidelines</h3><p>When running native hybrid search in high-throughput environments, we adjust database configurations beyond default out-of-the-box settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*KLSh62cg7oJgTFcHcL35bA.png" /></figure><h3>Production Verification Checklist</h3><ul><li><strong>Verify Simultaneous Index Execution:</strong> Run EXPLAIN ANALYZE on hybrid queries to ensure both idx_products_dense_hnsw and idx_products_sparse_hnsw execute simultaneous index scans without falling back to sequential table space searches.</li><li><strong>Warm Your Graphs:</strong> Preload both dense and sparse HNSW graphs into the PostgreSQL buffer cache by executing dummy vector scans during the application boot sequence.</li><li><strong>Partitioning Strategy:</strong> If the dataset spans tens of millions of rows, partition tables by a logical boundary like category or tenant_id.</li><li><strong>Local Indexing:</strong> Deploy local HNSW indexes across these partitions to keep individual graph indexes compact and fast.</li></ul><p>We have not fully resolved two operational behaviors:</p><ul><li>We are currently hacking around a vocabulary boundary constraint, forcing a pre-filtering step inside the application layer when SPLADE generates token IDs exceeding our 32000-dimension schema limit, rather than using a dynamic mapping logic within Postgres.</li><li>We observed severe query throughput inversion on collections smaller than 1 million rows when attempting to use the diskann index type, meaning we enforce HNSW purely for sub-scaling workloads due to the introduced quantization decoding floor.</li></ul><p>We are now validating the diskann index type made available via the <a href="https://github.com/timescale/pgvectorscale">pgvectorscale</a> extension. This extension allows us to execute disk-backed graph traversal, transitioning our vector operations from being constrained by physical RAM allocation metrics to being gated by NVMe storage IOPS. By enforcing Statistical Binary Quantization (SBQ) on high-dimensional vectors, DiskANN maintains significant recall accuracy while shrinking the working set footprint to approximately 8.2% of its uncompressed layout. This engineering path complements our existing native hybrid search strategy, providing a scale-out mechanism when individual vector collections exceed physical hardware bounds. We base our implementation on the foundational DiskANN <a href="https://arxiv.org/abs/2310.00402">research</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23c85a9d7884" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>