<?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 Kotobara on Medium]]></title>
        <description><![CDATA[Stories by Kotobara on Medium]]></description>
        <link>https://medium.com/@kotobara?source=rss-207df8990ff0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vIydERIK52PDqbgsSeJljg.png</url>
            <title>Stories by Kotobara on Medium</title>
            <link>https://medium.com/@kotobara?source=rss-207df8990ff0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:59:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kotobara/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[Amazon S3 Features You Might Be Missing: Presigned URLs, Metadata, and More]]></title>
            <link>https://kotobara.medium.com/amazon-s3-features-you-might-be-missing-presigned-urls-metadata-and-more-3efabb9e60b7?source=rss-207df8990ff0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3efabb9e60b7</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Kotobara]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 17:23:48 GMT</pubDate>
            <atom:updated>2026-11-09T17:23:48.559Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bST7Azs35w5ykoCWthtZA.png" /></figure><p><em>Browser PDF previews, direct uploads, and safer writes through a small document-portal example.</em></p><p>A user wants to open an invoice. The backend downloads the PDF from S3, keeps a connection open, and forwards the bytes to the browser. Another endpoint does almost the same work for the Download button. To find out where the document came from, the application reads the file again.</p><p>S3 can take over some of that work. Objects have metadata, responses can specify how content should be presented, and clients can receive temporary access. Let’s connect those capabilities around one document, then add uploads, versions, and protection against accidental overwrites.</p><p>This walkthrough uses a <strong>general purpose bucket</strong>. The Boto3 examples were checked locally on November 1, 2026, with Python <strong>3.12.10</strong> and Boto3/Botocore <strong>1.43.123</strong>. The real SDK generated signatures and POST policies; Stubber supplied operation responses. No requests reached AWS, and browser PDF rendering was not tested. Service behavior below follows the linked AWS documentation.</p><h3>🔍 Read metadata without downloading the document</h3><p>Assume a private bucket already exists, versioning is enabled, and the application uses a role with the required permissions. Replace the bucket name and region with your own and place a small invoice.pdf beside your script. Run the Python blocks sequentially. Install boto3==1.43.123 in a separate environment.</p><pre>import base64<br>import hashlib<br>from pathlib import Path</pre><pre>import boto3<br>from botocore.config import Config</pre><pre>s3 = boto3.client(<br>    &quot;s3&quot;, region_name=&quot;eu-central-1&quot;,<br>    config=Config(signature_version=&quot;s3v4&quot;),<br>)<br>bucket = &quot;your-private-document-bucket&quot;<br>key = &quot;documents/invoice-1042.pdf&quot;<br>body = Path(&quot;invoice.pdf&quot;).read_bytes()</pre><pre>uploaded = s3.put_object(<br>    Bucket=bucket, Key=key, Body=body,<br>    ContentType=&quot;application/pdf&quot;,<br>    Metadata={&quot;document-id&quot;: &quot;1042&quot;, &quot;source-system&quot;: &quot;billing&quot;},<br>    ChecksumSHA256=base64.b64encode(hashlib.sha256(body).digest()).decode(),<br>)<br>version = uploaded[&quot;VersionId&quot;]</pre><p>ContentType describes the HTTP representation. Metadata holds our application fields. Over REST, those fields use the x-amz-meta- prefix; Boto3 takes a dictionary without it. S3 returns user-metadata keys in lowercase. The values here are short ASCII identifiers.</p><p>SHA-256 is a separate parameter. Putting a hash in Metadata={&quot;sha256&quot;: ...} would not, by itself, make S3 verify the bytes. This small example reads the entire file into memory; larger files need a different transfer approach.</p><p>Now retrieve the document’s provenance without its body:</p><pre>info = s3.head_object(Bucket=bucket, Key=key, VersionId=version)<br>print(info[&quot;Metadata&quot;][&quot;source-system&quot;])<br>print(info[&quot;ContentType&quot;])</pre><p>For this object, the expected output is billing and application/pdf. HEAD still requires access and incurs applicable request charges.</p><p>User-defined metadata has a <strong>2 KB limit across keys and values</strong>, measured in UTF-8 bytes. To change it after upload, copy the object with replacement metadata; there is no simple patch for one field. Preserve the other metadata and headers you still need. Large JSON payloads belong elsewhere rather than inside HTTP headers. <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingMetadata.html">Object metadata and HEAD</a>.</p><h3>🛠️ One PDF, two signed links</h3><p>A presigned URL delegates an operation using the signing principal’s permissions. For a preview, include the response type and disposition in the GET parameters <strong>before signing</strong>:</p><pre>def document_url(https://medium.com/disposition):<br>    return s3.generate_presigned_url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20%20%20&quot;get_object&quot;,%3Cbr%3E%20%20%20%20%20%20%20%20Params=%7B%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20&quot;Bucket&quot;:%20bucket,%20&quot;Key&quot;:%20key,%20&quot;VersionId&quot;:%20version,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20&quot;ResponseContentType&quot;:%20&quot;application/pdf&quot;,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20&quot;ResponseContentDisposition&quot;:%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20f&#39;{disposition};%20filename=&quot;invoice-1042.pdf&quot;&#39;,%3Cbr%3E%20%20%20%20%20%20%20%20},%3Cbr%3E%20%20%20%20%20%20%20%20ExpiresIn=300,%3Cbr%3E)</pre><pre>preview_url = document_url(https://medium.com/&quot;inline&quot;)<br>download_url = document_url(https://medium.com/&quot;attachment&quot;)</pre><p>inline asks the browser to display the document; attachment asks it to download the file with the supplied name. S3 serves the PDF, while the browser decides how to present it. A disabled PDF viewer or user preference may still cause a download. Signing a link neither converts Word to PDF nor guarantees a preview for every format.</p><p>The parameters are part of the signature. Appending response-content-disposition to an already signed URL will not work. The example uses a fixed ASCII filename; user-provided names need their own validation and encoding. <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html">GetObject response overrides</a>.</p><p>The bucket stays private, but anyone holding the link can use it while access remains valid. It is reusable. ExpiresIn=300 cannot extend temporary credentials, and removing the version or changing permissions can also make the request fail. Keep these URLs out of public logs. With SSE-KMS, account for the required key permissions too. <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html">Presigned URL lifetime and limits</a>.</p><p>For a GET targeting a specific version, the signer needs s3:GetObjectVersion; s3:GetObject alone does not cover that request. <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html">GetObject permissions</a>.</p><p>Opening a URL in a new tab and reading it with frontend fetch() are different browser operations. JavaScript reading a response from another origin needs an appropriate CORS configuration. A valid signature does not replace that configuration. <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/cors.html">S3 CORS</a>.</p><h3>Upload from the browser without proxying the file</h3><p>The backend can issue a form and let the client send the file directly to S3. Choose a presigned <strong>POST</strong> to constrain the size and field values explicitly:</p><pre>from uuid import uuid4</pre><pre>upload_key = f&quot;incoming/{uuid4().hex}.pdf&quot;<br>form = s3.generate_presigned_post(<br>    Bucket=bucket, Key=upload_key,<br>    Fields={<br>        &quot;Content-Type&quot;: &quot;application/pdf&quot;,<br>        &quot;x-amz-meta-document-id&quot;: &quot;1042&quot;,<br>    },<br>    Conditions=[<br>        [&quot;content-length-range&quot;, 1, 10 * 1024 * 1024],<br>        {&quot;Content-Type&quot;: &quot;application/pdf&quot;},<br>        {&quot;x-amz-meta-document-id&quot;: &quot;1042&quot;},<br>    ],<br>    ExpiresIn=300,<br>)</pre><p>The backend returns form[&quot;url&quot;] and <strong>all</strong> of form[&quot;fields&quot;]. The client sends those fields as multipart/form-data, adding the file last. Let the browser construct the multipart boundary; do not set the entire HTTP request&#39;s Content-Type to application/pdf.</p><p>One Boto3 detail matters: a value in Fields does not automatically become a restriction in Conditions. That is why both the content type and metadata appear twice. The SDK fixes the object key from Key, and the policy limits the file to 1 byte–10 MiB. The server chooses the unique key. Before issuing the form, the backend must authorize that user&#39;s upload for the intended document.</p><p>A Content-Type field cannot prove that the bytes contain a valid PDF. The application still needs format validation and its required content checks after upload. Presigned PUT is another useful option, but POST policy conditions such as content-length-range do not automatically apply to it. <a href="https://docs.aws.amazon.com/boto3/latest/reference/services/s3/client/generate_presigned_post.html">Boto3 presigned POST</a>.</p><h3>Metadata, tags, and versions answer different questions</h3><p>Keep the source identifier in metadata and the current processing state in tags. Tags can change through a separate operation without copying the body:</p><pre>s3.put_object_tagging(<br>    Bucket=bucket, Key=key, VersionId=version,<br>    Tagging={&quot;TagSet&quot;: [<br>        {&quot;Key&quot;: &quot;processing-status&quot;, &quot;Value&quot;: &quot;validated&quot;},<br>    ]},<br>)</pre><p>This operation sets the version’s entire tag set. Preserve other tags when adding one. For this version-specific request, account for s3:PutObjectVersionTagging. Objects support up to ten tags, which can participate in classification, access policies, and Lifecycle rules. User-defined metadata is a separate mechanism. <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-tagging.html">Object tagging</a>, <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObjectTagging.html">tag-set replacement and permissions</a>.</p><p>The VersionId saved from the first PUT ties our HEAD request, tags, and links to one invoice revision. If someone later replaces the object at the same key, a link without a version targets the current state. With versioning enabled, overwriting creates another version; an ordinary delete without VersionId creates a delete marker. Old versions consume storage and can be removed explicitly or through Lifecycle. Versioning still needs a recovery and retention policy. <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html">S3 Versioning</a>.</p><h3>🧪 Avoid a blind overwrite — and read only what you need</h3><p>A HEAD followed by an ordinary PUT leaves time for another writer to act. To create an object only when no current object exists, put the condition on the write itself:</p><pre>from botocore.exceptions import ClientError</pre><pre>try:<br>    s3.put_object(<br>        Bucket=bucket, Key=&quot;incoming/first-upload.pdf&quot;, Body=body,<br>        ContentType=&quot;application/pdf&quot;, IfNoneMatch=&quot;*&quot;,<br>    )<br>except ClientError as error:<br>    if error.response[&quot;ResponseMetadata&quot;][&quot;HTTPStatusCode&quot;] != 412:<br>        raise<br>    print(&quot;Current object already exists; no overwrite&quot;)</pre><p>An existing current object produces 412 Precondition Failed. Races can have other outcomes, including 409; this code does not disguise those errors as an existing object. For updates against a known state, consider IfMatch with its ETag. Versioning preserves revisions but does not itself prevent an accidental overwrite. <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes.html">Conditional writes</a>.</p><p>Reads have useful boundaries too. Retrieve just the first five bytes of our chosen version:</p><pre>response = s3.get_object(<br>    Bucket=bucket, Key=key, VersionId=version, Range=&quot;bytes=0-4&quot;,<br>)<br>try:<br>    prefix = response[&quot;Body&quot;].read()<br>finally:<br>    response[&quot;Body&quot;].close()</pre><p>For a typical PDF, expect %PDF-. This demonstrates Range; it is not a complete PDF validator. For a conditional GET, IfNoneMatch with a previously obtained ETag can avoid downloading an unchanged body. Do not treat ETag as a universal MD5 checksum: its meaning depends partly on how the object was uploaded. For byte integrity, choose a documented checksum and account for full-object versus composite checksums with multipart uploads. <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html">GetObject</a>, <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html">object integrity</a>.</p><h3>What else belongs around this workflow?</h3><p>An upload event can start text extraction through SQS, Lambda, or EventBridge. S3 Event Notifications are designed for at-least-once delivery and can arrive out of order. Track processing identity, account for object versions, and design retries. Issuing one signed form does not establish a reliable workflow. <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-how-to-event-types-and-destinations.html">S3 event notifications</a>.</p><p>For large files, consider multipart upload. For storage cost and retention, consider Lifecycle, including older versions and incomplete uploads. Inventory and Batch Operations help with inventory and bulk processing; Replication supports replication workflows; Object Lock provides retention controls. Each deserves a concrete scenario beyond the configuration used here. <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html">S3 capabilities</a>.</p><p>The local checks used synthetic credentials, stubbed responses, and a short byte sequence instead of a real PDF. They checked SDK parameters and restrictions included in signatures and policies. They did not test enforcement by S3, IAM/KMS, CORS, browser rendering, version storage after overwrites, or event delivery. A URL can be signed for an object that does not exist; generating a signature does not establish access.</p><p>Start with one document: preserve its provenance, issue separate preview and download links, and pin them to a version. Then check the real HTTP headers and behavior in your browser. That makes S3 part of the application’s behavior, beyond simply accepting its bytes.</p><p>If you found this article helpful, give it a 👏 clap and subscribe for practical Python and data engineering guides. Thanks for reading, and may your links live exactly as long as they need to! ☁️</p><p><em>This article was reviewed with AI assistance.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3efabb9e60b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Checks an AI-Written Data Pipeline Should Pass Before Merge]]></title>
            <link>https://kotobara.medium.com/the-checks-an-ai-written-data-pipeline-should-pass-before-merge-d1ff18ce7ff5?source=rss-207df8990ff0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1ff18ce7ff5</guid>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kotobara]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 16:06:50 GMT</pubDate>
            <atom:updated>2026-11-01T16:06:50.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*twimXf_CouRriN8TSEdPNg.png" /></figure><p><em>Retries, corrections, and a broken report: testing a pipeline change with a small dataset.</em></p><p>The pipeline runs, three orders land in a table, and the test is green. Then the same batch arrives again, and the paid-order total doubles. No exceptions. As far as the program is concerned, everything went beautifully.</p><p>When reviewing an AI-written change, it is easy to focus on the code: clear names, tidy SQL, some tests. A more useful starting point is the failure those tests would actually stop.</p><p>Let’s build a small Python loader and examine seven deliberate defects. We will check schemas, retries, conflicting duplicates, business rules, corrections, a downstream report, and rollback. These are synthetic changes chosen for this experiment; they do not measure a particular model or the frequency of AI mistakes. The same requirements apply to human-written code.</p><h3>🔍 Agree on the result first</h3><p>Our source sends the current state of an order. The destination holds one row per order_id, with amounts in integer cents. An incoming row describes a state; it is not an instruction to add more money.</p><p>The contract is small enough to write down:</p><ul><li>order_id is a positive integer; amount_cents is a nonnegative integer. The string &quot;5000&quot; and the boolean True are invalid.</li><li>The only statuses are paid and cancelled. Refunds are outside this example.</li><li>An exact duplicate within a batch is acceptable. Two different states for the same order in one batch are ambiguous, so the entire batch must be rejected.</li><li>A later batch may correct an existing order. Replaying the latest successful batch must leave the table unchanged.</li><li>If a write fails before the batch commits, the table must retain its previous state.</li></ul><p>We assume batches arrive in source order. There is no record version here, so an old batch arriving late could overwrite a newer state. Handling that requires a version-ordering rule beyond this loader.</p><p>The consumer has a contract too. Its query expects paid_orders and paid_cents, counting only paid orders. That gives us one concrete compatibility boundary to test.</p><h3>🛠️ A small implementation we can break</h3><p>Run the Python blocks below sequentially in one session, without -O: the examples use assertions. No third-party packages are required. The example was verified on October 29, 2026, and rechecked on November 1 using CPython <strong>3.12.10</strong>, SQLite <strong>3.49.1</strong>, and Windows 11. SQLite runs in memory; there is no server or external dataset.</p><pre>import sqlite3</pre><pre>db = sqlite3.connect(&quot;:memory:&quot;, isolation_level=&quot;DEFERRED&quot;)<br>db.execute(&quot;&quot;&quot;CREATE TABLE orders (<br>    order_id INTEGER PRIMARY KEY,<br>    status TEXT NOT NULL,<br>    amount_cents INTEGER NOT NULL<br>)&quot;&quot;&quot;)<br>db.execute(&quot;&quot;&quot;CREATE VIEW paid_summary AS<br>    SELECT count(*) AS paid_orders,<br>           coalesce(sum(amount_cents), 0) AS paid_cents<br>    FROM orders WHERE status = &#39;paid&#39;<br>&quot;&quot;&quot;)</pre><pre>batch = [<br>    {&quot;order_id&quot;: 1, &quot;status&quot;: &quot;paid&quot;, &quot;amount_cents&quot;: 10000},<br>    {&quot;order_id&quot;: 2, &quot;status&quot;: &quot;paid&quot;, &quot;amount_cents&quot;: 5000},<br>    {&quot;order_id&quot;: 3, &quot;status&quot;: &quot;cancelled&quot;, &quot;amount_cents&quot;: 7000},<br>]</pre><p>The report should return two paid orders and <strong>15000 cents</strong>. That expectation comes from the sample data and the metric definition. We should not calculate it with the transformation we are trying to test.</p><p>Before writing anything, validate the entire batch. The exact type checks are intentional: this contract rejects implicit conversions and booleans masquerading as amounts. Another application could normalize strings in a separate, explicit stage.</p><pre>def normalize(batch):<br>    rows = {}<br>    for row in batch:<br>        if set(row) != {&quot;order_id&quot;, &quot;status&quot;, &quot;amount_cents&quot;}:<br>            raise ValueError(&quot;fields&quot;)<br>        if type(row[&quot;order_id&quot;]) is not int or row[&quot;order_id&quot;] &lt;= 0:<br>            raise ValueError(&quot;order_id&quot;)<br>        if type(row[&quot;amount_cents&quot;]) is not int:<br>            raise ValueError(&quot;amount_cents&quot;)<br>        if row[&quot;amount_cents&quot;] &lt; 0:<br>            raise ValueError(&quot;negative amount&quot;)<br>        if row[&quot;status&quot;] not in (&quot;paid&quot;, &quot;cancelled&quot;):<br>            raise ValueError(&quot;status&quot;)<br>        value = (row[&quot;order_id&quot;], row[&quot;status&quot;], row[&quot;amount_cents&quot;])<br>        old = rows.get(row[&quot;order_id&quot;])<br>        if old is not None and old != value:<br>            raise ValueError(&quot;conflicting duplicate&quot;)<br>        rows[row[&quot;order_id&quot;]] = value<br>    return list(rows.values())</pre><p>A dictionary alone would silently keep the last value for a key. The comparison before assignment distinguishes an exact repeat from two contradictory states with no version to resolve them.</p><p>For an existing key, the loader replaces the amount and status with the incoming values. SQLite’s ON CONFLICT handles the uniqueness conflict; excluded refers to the proposed incoming row. <a href="https://www.sqlite.org/lang_upsert.html">SQLite UPSERT documentation</a>.</p><pre>def load(batch, *, fail_after=None):<br>    rows = normalize(batch)<br>    with db:<br>        for index, row in enumerate(rows, 1):<br>            db.execute(&quot;&quot;&quot;INSERT INTO orders VALUES (?, ?, ?)<br>                ON CONFLICT(order_id) DO UPDATE SET<br>                    status = excluded.status,<br>                    amount_cents = excluded.amount_cents<br>            &quot;&quot;&quot;, row)<br>            if index == fail_after:<br>                raise RuntimeError(&quot;injected write failure&quot;)</pre><pre>def snapshot():<br>    return db.execute(&quot;SELECT * FROM orders ORDER BY order_id&quot;).fetchall()</pre><p>fail_after lets the experiment interrupt a write deliberately. In an application test, a controlled failure at the storage boundary can serve the same purpose.</p><p>With the transaction configuration used here, the connection context commits a successful transaction and rolls it back on an uncaught exception. with db does not close the connection, and its behavior depends on transaction settings. <a href="https://docs.python.org/3.12/library/sqlite3.html#how-to-use-the-connection-context-manager">Python sqlite3 transaction handling</a>.</p><h3>🧪 Replay and correction need separate checks</h3><pre>load(batch)<br>before = snapshot()<br>load(batch)<br>assert snapshot() == before</pre><pre>load([{**batch[1], &quot;amount_cents&quot;: 4000}])<br>assert snapshot() == [<br>    (1, &quot;paid&quot;, 10000),<br>    (2, &quot;paid&quot;, 4000),<br>    (3, &quot;cancelled&quot;, 7000),<br>]</pre><p>The first check compares the complete table state. A primary key prevents a second row for the same order, but it does not prevent accidentally adding the incoming amount to the stored amount.</p><p>In the deliberate variant using amount_cents = orders.amount_cents + excluded.amount_cents, replay changes the amounts. The replay check rejects it.</p><p>Now replace the update with DO NOTHING. Replay passes because existing rows stay unchanged. Unfortunately, the correction from 5000 to 4000 cents is also ignored. The correction check catches that. Idempotency is necessary for our retry contract, but it does not establish that the loader handles updates correctly.</p><p>The complete experiment also supplies exact duplicates, conflicting duplicates in both orders, missing and extra fields, invalid types, an unknown status, and a negative amount. For invalid batches, it checks both rejection and unchanged table contents. An error message is insufficient if half the batch has already been written.</p><p>Rejecting extra fields is another explicit choice. If the source must evolve by adding fields, agree on that compatibility policy and change the test accordingly.</p><h3>Run the consumer’s query</h3><p>Renaming a field can look harmless inside the loader. An existing report discovers the break immediately. Check the public column names and execute the query:</p><pre>columns = db.execute(&quot;PRAGMA table_info(paid_summary)&quot;).fetchall()<br>assert [row[1] for row in columns] == [&quot;paid_orders&quot;, &quot;paid_cents&quot;]</pre><pre>report = db.execute(<br>    &quot;SELECT paid_orders, paid_cents FROM paid_summary&quot;<br>).fetchone()<br>assert report == (2, 14000)</pre><p>PRAGMA table_info returns column information for a table or view. Here, we check the names and order of the public fields. That metadata cannot establish what the values mean. <a href="https://www.sqlite.org/pragma.html#pragma_table_info">SQLite PRAGMA documentation</a>.</p><p>Two defects show the difference. Renaming paid_cents to paid_total breaks the query. Dividing amounts by 100 before writing preserves the field name and integer type, but the initial report returns <strong>150</strong> instead of <strong>15000</strong>. An independent expected result catches the wrong unit.</p><p>The full suite also checks the empty report (0, 0) and changing a paid order to cancelled. Successful SQL execution is only the beginning of consumer compatibility.</p><h3>Fail halfway through a write</h3><p>Invalid-input checks cannot demonstrate rollback after a write: our validator finishes before the first INSERT. Inject a separate failure after the first statement executes:</p><pre>before = snapshot()<br>try:<br>    load([<br>        {**batch[1], &quot;amount_cents&quot;: 3500},<br>        {&quot;order_id&quot;: 4, &quot;status&quot;: &quot;paid&quot;, &quot;amount_cents&quot;: 2500},<br>    ], fail_after=1)<br>except RuntimeError as error:<br>    assert str(error) == &quot;injected write failure&quot;<br>else:<br>    raise AssertionError(&quot;failure was not injected&quot;)<br>assert snapshot() == before<br>db.close()</pre><p>Add db.commit() after each row and the exception still occurs, but the first correction survives. Comparing the final state catches the partial write.</p><p>This checks an exception handled within one process and one database. It does not simulate power loss, a broker acknowledgement, or coordinated writes to a database and object storage. Those boundaries need their own recovery scenarios.</p><h3>What the run showed — and what belongs in the PR</h3><p>The baseline passed <strong>nine checks</strong>. The same suite then ran against seven separate variants, each containing a deliberate defect. Every variant was rejected by at least one relevant check:</p><ul><li>Adding amounts on replay failed the state comparison after a repeated batch.</li><li>Ignoring corrections failed the expected order-value check.</li><li>Keeping the last conflicting duplicate failed the ambiguous-batch rejection check.</li><li>Accepting negative amounts failed the business-rule check.</li><li>Renaming a public field failed the schema check and consumer query.</li><li>Committing each row failed rollback after an injected error.</li><li>Writing dollars into a cents field failed the expected-value checks.</li></ul><p>These are <strong>seven detected, deliberately chosen defects</strong>. The suite was designed around these requirements; the result is not a detection rate for arbitrary bugs or a measure of AI quality.</p><p>The article uses assertions for brevity. The local runner uses explicit comparisons and returns a nonzero exit code when a chosen variant fails. A separate matrix run checks that the baseline passes and every deliberate defect fails. Expected failures make that experiment successful; they do not make faulty code acceptable to merge.</p><p>For a pipeline PR, include the contract, sample inputs with independent expectations, the run result, and the boundaries still untested. Review expectations separately from implementation. If an agent changes both the loader and the expected amount, a green test can repeat the same mistake twice.</p><p>For a real warehouse, add checks against its actual engine, types, migrations, and transactions. This example does not test concurrent writers, old batches arriving after new ones, scale, or external side effects. Python validation also does not protect writes that bypass the loader; enforce appropriate constraints in the database too.</p><p>Start with the next pipeline change: choose one requirement, deliberately violate it, and verify that the check fails for the intended reason. Then restore the code. That gives a green result a concrete meaning.</p><p>If you found this article helpful, give it a 👏 clap and subscribe for more practical Python and data engineering guides. Thanks for reading, and may your retries bring back data without inventing extra revenue! 🛠️</p><p><em>This article was reviewed with AI assistance.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1ff18ce7ff5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python 3.15 for Data Pipelines: What Changes in Practice?]]></title>
            <link>https://kotobara.medium.com/python-3-15-for-data-pipelines-what-changes-in-practice-c386900a673b?source=rss-207df8990ff0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c386900a673b</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kotobara]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 15:59:40 GMT</pubDate>
            <atom:updated>2026-11-01T15:59:40.558Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oX6ovCpDqnV_XKWdt8ylaw.png" /></figure><p><em>UTF-8 defaults, deferred imports, and the difference between missing and null.</em></p><p>A Python upgrade makes a CSV job fail on a customer’s name. Another file finally reads correctly, although yesterday the same code mangled its characters. A configuration check starts successfully, but a missing-driver error appears only during export.</p><p>Those are different outcomes, and “the new Python is faster” tells us little about them. For a small ETL job, the useful questions are what values the program receives and when it discovers a problem.</p><p>Python 3.15 was released on October 9, 2026. This walkthrough was verified on October 26 using CPython <strong>3.14.10 and 3.15.2</strong> on Windows x64, with only the standard library. It is a local teaching experiment, without production anecdotes or performance measurements. <a href="https://www.python.org/downloads/release/python-3150/">First stable release</a>, <a href="https://www.python.org/downloads/release/python-3152/">tested maintenance release</a>.</p><p>We will examine three changes at the edges of a pipeline: reading text, loading an optional handler, and interpreting an incremental-read parameter. The first can affect existing code without edits; the other two require deliberately adopting new features.</p><h3>🔍 UTF-8 by default does not identify the source encoding</h3><p>Python 3.15 enables UTF-8 mode by default. A text file opened without an explicit encoding therefore uses UTF-8 rather than depending on the locale. The change is especially visible on Windows with a legacy locale encoding. An environment already using UTF-8 may show no such contrast. <a href="https://peps.python.org/pep-0686/">PEP 686</a>.</p><p>Our two files contain identical names and amounts but different bytes: one uses UTF-8, the other CP1252. Run this example in a new, empty directory. All snippets use the standard library; lazy import and the built-in sentinel require Python 3.15.</p><pre>import csv<br>from pathlib import Path</pre><pre>text = &quot;customer,amount_cents\ncafé,10000\nKraków,5000\n&quot;<br>Path(&quot;utf8.csv&quot;).write_bytes(text.encode(&quot;utf-8&quot;))<br>Path(&quot;legacy.csv&quot;).write_bytes(text.encode(&quot;cp1252&quot;))</pre><pre>def read_orders(path, encoding=None):<br>    with open(path, encoding=encoding, newline=&quot;&quot;) as source:<br>        return list(csv.DictReader(source))</pre><pre>implicit_utf8 = read_orders(&quot;utf8.csv&quot;)<br>try:<br>    implicit_legacy = read_orders(&quot;legacy.csv&quot;)<br>except UnicodeDecodeError as error:<br>    implicit_legacy = type(error).__name__</pre><pre>print([row[&quot;customer&quot;] for row in implicit_utf8])<br>print(implicit_legacy)<br>print(read_orders(&quot;legacy.csv&quot;, encoding=&quot;cp1252&quot;))</pre><p>The tested machine’s locale encoding was <strong>CP1252</strong>. On 3.14.10, implicit decoding preserved the legacy file’s names but turned the UTF-8 names into cafÃ© and KrakÃ³w. The numeric fields still contained 10000 and 5000. A check of the total alone could miss the damaged text.</p><p>On 3.15.2, the same UTF-8 file read correctly. The legacy file instead raised <strong>UnicodeDecodeError</strong>. The release changed the assumption used to read the source; it did not convert the source itself.</p><p>The final call specifies CP1252 and preserves the original rows on both versions. For a UTF-8 source, specify encoding=&quot;utf-8&quot; instead. Choose the encoding from the data supplier&#39;s contract. A new default is no reason to assign UTF-8 to every old export.</p><p>Enable -X warn_default_encoding to find implicit reads. Both such reads produced EncodingWarning in the experiment. Running 3.15 with -X utf8=0 restored the previous behavior on this machine. That is a useful diagnostic control before fixing individual input boundaries; explicit encodings remain the durable solution.</p><h3>🛠️ Lazy imports move work to first use</h3><p>A pipeline CLI often has several commands: show configuration, validate a file, send data. If the export module is needed only for the third command, executing its code on every invocation may be unnecessary.</p><p>Python 3.15 adds lazy import, which postpones loading until the imported name is used. Ordinary import keeps its existing behavior. The new syntax is allowed at module scope, but not inside a function or a try/except block. <a href="https://docs.python.org/3.15/reference/simple_stmts.html#lazy-imports">Lazy import rules</a>.</p><p>Create a small demo_sink.py:</p><pre>def export(rows):<br>    return sum(row[&quot;amount_cents&quot;] for row in rows)</pre><p>Save the following beside it as job.py and run it in a separate Python 3.15 process. This sink only sums values; it does not connect to a warehouse.</p><pre>import sys<br>lazy import demo_sink</pre><pre>print(&quot;demo_sink&quot; in sys.modules)<br>rows = [{&quot;amount_cents&quot;: 10000}, {&quot;amount_cents&quot;: 5000}]<br>print(demo_sink.export(rows))<br>print(&quot;demo_sink&quot; in sys.modules)</pre><p>The output is <strong>False, 15000, True</strong>, on separate lines. The module is absent before the export call and loaded after it is accessed. This checks execution timing, not a speedup. If every invocation immediately calls export, the import work is still required.</p><p>Errors move too. In a separate check, declaring a lazy import of a deliberately nonexistent driver succeeded. ModuleNotFoundError appeared when the driver was accessed. A successful configuration command therefore does not establish that the export command works.</p><p>There is a subtler dependency: handlers registered during import. An additional synthetic sink added itself to a registry when its module executed. After an ordinary import, the registry was populated. After a lazy import, looking up the handler by name raised <strong>KeyError</strong>. Accessing the module itself then performed registration.</p><p>If your application relies on that side effect, keep the import eager or make initialization explicit. Validate a required sink before processing data, rather than accidentally moving that check to the end of a long job. This is an engineering consequence of deferred execution, not a new dependency-validation mechanism. <a href="https://peps.python.org/pep-0810/">PEP 810 semantics and tradeoffs</a>.</p><p>The 3.14 check rejected lazy import with SyntaxError during parsing. Supporting older Python versions in the same source file therefore requires a separate choice of import strategy. An ordinary import inside a function was already available before 3.15; new syntax is optional.</p><h3>🧪 A missing watermark and null request different behavior</h3><p>Now consider an ingestion parameter. For this example, an omitted watermark means resume from the saved checkpoint; explicit null requests a full selection; a number sets the lower ID boundary, with only larger IDs selected. This is our teaching contract, not a universal meaning of null in ETL.</p><p>The convenient config.get(&quot;watermark&quot;) returns None for both an absent key and explicit null. It can accidentally turn a request to resume into a full selection.</p><p>Python 3.15’s built-in sentinel creates a distinct value for this situation. Compare it with is so that None and zero remain valid inputs. <a href="https://docs.python.org/3.15/builtins/functions.html#sentinel">The sentinel type</a>.</p><pre>MISSING = sentinel(&quot;MISSING&quot;)</pre><pre>def select_rows(rows, checkpoint, watermark=MISSING):<br>    if watermark is MISSING:<br>        watermark = checkpoint<br>    if watermark is None:<br>        return list(rows)<br>    return [row for row in rows if row[&quot;event_id&quot;] &gt; watermark]</pre><pre>rows = [{&quot;event_id&quot;: event_id} for event_id in (1, 2, 3)]<br>configs = {<br>    &quot;omitted&quot;: {},<br>    &quot;null&quot;: {&quot;watermark&quot;: None},<br>    &quot;zero&quot;: {&quot;watermark&quot;: 0},<br>    &quot;one&quot;: {&quot;watermark&quot;: 1},<br>}<br>selected = {<br>    name: [row[&quot;event_id&quot;] for row in select_rows(<br>        rows, checkpoint=2, watermark=config.get(&quot;watermark&quot;, MISSING)<br>    )]<br>    for name, config in configs.items()<br>}<br>print(selected)</pre><p>The result: omitted selects event <strong>3</strong>; null selects <strong>1, 2, 3</strong>; zero also selects <strong>1, 2, 3</strong>; and one selects <strong>2, 3</strong>. The deliberately broken version using plain get selected all three events for omitted. The check caught the difference.</p><p>The problem predates 3.15. On the baseline, the same business contract works with MISSING = object(). The built-in type standardizes sentinels and avoids some problems with homemade variants. In particular, MISSING = sentinel(&quot;MISSING&quot;), defined at module scope in an importable module, preserved identity after a pickle round-trip; a plain object() did not. Naming and scope matter here. Transport between processes was not tested. <a href="https://peps.python.org/pep-0661/">PEP 661 motivation</a>.</p><p>A sentinel will not validate that a watermark is an integer, persist a checkpoint, or prevent duplicate writes to a sink. This example selects IDs rather than implementing a complete incremental loader. Those responsibilities remain with the application.</p><h3>What to check before upgrading a worker</h3><p>The local experiment passed <strong>12 automated checks</strong>, covering damaged text values, deferred errors, and incorrect missing-value handling. The target interpreters ran in separate processes using official Windows embeddable packages. This does not verify an entire installed analytics environment.</p><p>Before upgrading a working pipeline:</p><ul><li>Read known samples from each text source and compare values, including non-ASCII characters.</li><li>Exercise every export command you use and verify required handler initialization.</li><li>Test omitted parameters, null, zero, and an explicit selection boundary separately.</li></ul><p>Compatibility with your native extensions, scheduler, and worker image needs separate verification. This experiment installed no pandas, NumPy, or storage drivers. It also provides no CPU, memory, or job-duration measurements from which to infer a benefit for your ETL.</p><p>Account for UTF-8 mode during migration. Adopt lazy imports and sentinels where they fit your architecture and data contract. Start by checking the values at one real input boundary: a successful process exit does not establish that the data survived unchanged.</p><p>If you found this article helpful, give it a 👏 clap and subscribe for more practical Python and data engineering guides. Thanks for reading, and may your upgrades preserve the meaning of your data! 🐍</p><p><em>This article was reviewed with AI assistance.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c386900a673b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Small Analytics Platform with DuckDB and DuckLake]]></title>
            <link>https://kotobara.medium.com/building-a-small-analytics-platform-with-duckdb-and-ducklake-9d0bd15a014d?source=rss-207df8990ff0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d0bd15a014d</guid>
            <category><![CDATA[duckdb]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[ducklake]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Kotobara]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 16:51:56 GMT</pubDate>
            <atom:updated>2026-10-26T16:51:56.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNgrKgzffmD1Yjgf5oQ8Yw.png" /></figure><p><em>Local storage, corrections, snapshots — and the point where one process stops being enough.</em></p><p>Putting data in Parquet is straightforward. Things get interesting when yesterday’s amount needs correcting, an old report needs explaining, and a second process wants to open “our little database.”</p><p>Three questions matter: what executes SQL, what defines the current table state, and where the data lives. DuckDB and DuckLake let us separate those responsibilities locally. One successful SELECT, however, does not make the result a multi-user platform.</p><p>Let’s build that foundation with three synthetic orders, then check corrections, historical reads, and conflicting updates. This is a behavioral walkthrough, not a production story or performance benchmark.</p><h3>🔍 Do we need DuckLake yet?</h3><p>For querying files and producing reports, DuckDB alone may be enough. Mutable tables do not automatically require DuckLake either: a regular DuckDB database already supports transactions.</p><p>Here, we want tables backed by separate files and a way to query a retained state from before a correction. That is our reason for adding DuckLake — not every CSV folder needs a promotion to lakehouse.</p><p>The local setup has three parts:</p><ul><li><strong>DuckDB</strong> executes queries inside the application process.</li><li><strong>The DuckLake catalog</strong> stores table definitions, file references, and snapshots: committed database states.</li><li><strong>The data directory</strong> holds Parquet files. The catalog determines which data belongs to a particular snapshot; a file’s presence alone does not establish its visibility.</li></ul><p>One qualification: DuckLake can store small changes directly in the catalog through <strong>data inlining</strong>. “Metadata here, absolutely every row there” would be misleading. We disable inlining below to make the files visible. <a href="https://ducklake.select/docs/stable/duckdb/advanced_features/data_inlining">Data inlining documentation</a>.</p><h3>🛠️ Create the local layer</h3><p>This example was verified on October 26, 2026, using DuckDB <strong>2.0.0</strong>, DuckLake catalog format <strong>1.1</strong>, and extension build 417a9117f5. Keep the engine version in mind: DuckLake 1.1 requires DuckDB 2.0.0 or later. <a href="https://ducklake.select/docs/stable/duckdb/introduction">Compatibility and setup</a>.</p><p>Run the SQL blocks sequentially in one DuckDB 2.0.0 session, starting in a new, empty working directory. They are self-contained; no companion repository is required. Extension installation needs internet access, but the data stays local. Verification used the Python binding, not a separate CLI run.</p><pre>INSTALL ducklake;<br>LOAD ducklake;</pre><pre>ATTACH &#39;ducklake:metadata.ducklake&#39; AS lake<br>    (DATA_PATH &#39;data/&#39;, DUCKLAKE_VERSION &#39;1.1&#39;);<br>USE lake;</pre><pre>CALL lake.set_option(&#39;data_inlining_row_limit&#39;, 0);</pre><pre>CREATE TABLE orders (<br>    order_id INTEGER,<br>    status VARCHAR,<br>    amount_cents INTEGER<br>);</pre><pre>INSERT INTO orders VALUES<br>    (1, &#39;paid&#39;, 10000),<br>    (2, &#39;paid&#39;, 5000),<br>    (3, &#39;cancelled&#39;, 7000);</pre><p>metadata.ducklake is the catalog database file, not a container holding all the Parquet data. data/ is the separate storage location. The filename extension does not change those roles.</p><p>The explicit USE lake matters too: otherwise, it is easy to create a table in the main in-memory database instead.</p><p>The initial insert produced one Parquet file in the verified run. That is an observation about three rows with inlining disabled, not a batch-size recommendation. Avoiding a separate file for every tiny change is precisely why inlining exists.</p><p>Our deliberately simple metric sums amount_cents for paid orders. This is not a complete revenue model with refunds or taxes. Integer cents keep rounding out of an example about data versions.</p><pre>SELECT count(*) AS paid_orders,<br>       sum(amount_cents) AS paid_cents<br>FROM orders<br>WHERE status = &#39;paid&#39;;</pre><pre>SELECT max(snapshot_id) AS baseline_snapshot<br>FROM lake.snapshots();</pre><p>The result is <strong>two paid orders totaling 15000 cents</strong>. In this fresh catalog, snapshot <strong>2</strong> represents the initial load. Read the identifier rather than treating it as a universal constant: a different sequence of operations produces a different history. <a href="https://ducklake.select/docs/stable/duckdb/usage/snapshots">Listing snapshots</a>.</p><h3>Correct the present without losing the past</h3><p>Suppose the second order should contain 4000 cents. We will also remove the cancelled order from the analytical table. Group both changes into one transaction so they become visible as one consistent state.</p><pre>BEGIN;<br>UPDATE orders SET amount_cents = 4000 WHERE order_id = 2;<br>DELETE FROM orders WHERE order_id = 3;<br>COMMIT;</pre><pre>SELECT count(*) AS paid_orders,<br>       sum(amount_cents) AS paid_cents<br>FROM orders<br>WHERE status = &#39;paid&#39;;</pre><pre>SELECT count(*) AS paid_orders,<br>       sum(amount_cents) AS paid_cents<br>FROM orders AT (VERSION =&gt; 2)<br>WHERE status = &#39;paid&#39;;</pre><p>The current query returns <strong>14000</strong>; the historical query returns <strong>15000</strong>. The current table contains two rows, while snapshot 2 still contains three. Substitute your baseline identifier if it differs.</p><p>Now an old report can point to a specific data state instead of “whatever that file contained last Tuesday.” Save the snapshot identifier alongside the report parameters and metric definition: a data version alone does not reproduce the entire calculation. Historical reads also depend on retaining the necessary history. <a href="https://ducklake.select/docs/stable/duckdb/usage/time_travel">Time travel</a>.</p><p>The local experiment additionally checked rollback: inserting another paid order inside a transaction, then rolling it back, left the total at 14000. Explicitly detaching the catalog and reopening it through a new connection in the same process preserved committed data and historical reads. That checks persistence, not crash recovery.</p><h3>🧪 Two connections are not two processes</h3><p>This is the architectural trap. DuckLake supports different catalog backends, but our local DuckDB catalog file allows <strong>only one process to attach it unless every process attaches it read-only</strong>. Multiple connections inside that one process are supported. A separate reporting process cannot attach alongside a writer, even if the reporting process only reads. <a href="https://ducklake.select/docs/stable/duckdb/usage/choosing_a_catalog_database">Catalog choices and restrictions</a>.</p><p>The verified experiment used connections within <strong>one process</strong>. Its first sequence demonstrated snapshot isolation: a stable data state inside a reader’s transaction.</p><ol><li>A reader starts a transaction and sees 14000.</li><li>Another connection changes the second order to 3500 and commits.</li><li>The reader’s existing transaction still sees 14000.</li><li>After ending that transaction, the reader’s next query sees 13500.</li></ol><p>The reader did not mix the before-and-after states in those queries. That matches DuckLake’s <a href="https://ducklake.select/docs/stable/duckdb/advanced_features/transactions">transaction semantics</a>, but does not establish correctness for an arbitrary concurrent application.</p><p>The second sequence deliberately created a conflict. Two connections started from the same snapshot and updated the same order: one to 3000, the other to 2000 cents. The first committed; the second received TransactionException at COMMIT. The final total was <strong>13000</strong>, not the 12000 that the second update would have produced.</p><p>The check verified both the rejection and the surviving result — not merely that some exception occurred.</p><p>A rejected transaction needs an application-level response. DuckLake can reconcile some non-conflicting changes automatically, but logical conflicts are rejected. Reconsider and retry the transaction against current data when appropriate; do not endlessly resend the same COMMIT. <a href="https://ducklake.select/docs/stable/duckdb/advanced_features/conflict_resolution">Conflict resolution</a>.</p><p>Eight automated checks passed: the initial metric, correction, historical read, rollback, reader snapshot, write conflict, reopening, and retained storage. These are tiny-data behavior checks, not throughput measurements.</p><h3>Small still needs operations</h3><p>A practical next layer is one ingestion-and-reporting process with scheduling, error logs, and data checks. The table format does not supply those responsibilities. In particular, order_id above is just a column: ingestion must detect duplicates and enforce business rules separately.</p><p>Storage also needs attention. The original Parquet file remained after the corrections because retained history still needed it. Deleting a row from the current table does not promise immediate physical removal of every historical representation.</p><p>Plan snapshot retention, small-file consolidation, and cleanup of files no longer required by history. Those operations were not executed here. Deleting “old” files manually by modification date is not a substitute. <a href="https://ducklake.select/docs/stable/duckdb/maintenance/recommended_maintenance">Recommended maintenance</a>.</p><p>Backups must cover a consistent catalog and its corresponding data files, not just one directory. For a small local process, pause writes, compaction, and cleanup while making a manual backup, then test a restore. Cleanup could otherwise remove files referenced by the catalog backup. Backup and restore were not tested in this experiment. <a href="https://ducklake.select/docs/stable/duckdb/guides/backups_and_recovery">Backup and recovery</a>.</p><h3>When to change the architecture</h3><p>Do not pick a migration threshold because a round number of gigabytes sounds convincing. This experiment provides no measurements for one. Look at requirements instead:</p><ul><li><strong>Independent local processes:</strong> the documentation suggests a SQLite catalog. It still has one writer at a time, not unlimited concurrent writes.</li><li><strong>Remote clients and multi-user operation:</strong> consider a PostgreSQL catalog plus shared data storage. Clients also need access to the files; the catalog does not automatically serve Parquet to them.</li><li><strong>User permissions, availability, and operational support:</strong> design those explicitly. Switching catalog backends does not finish the platform.</li></ul><p>The first two options follow the <a href="https://ducklake.select/docs/stable/duckdb/usage/choosing_a_catalog_database">catalog guidance</a>; neither was deployed here. The third is a design criterion, not a tested service claim.</p><p>Starting small is reasonable. Assuming the limits disappeared because the first query worked is less reasonable. Before adding another tool, answer four questions: who owns writes, how do you reproduce an old report, what happens on conflict, and how do you restore the catalog together with its data?</p><p>If you found this article helpful, give it a 👏 clap (or a few) and subscribe for more practical SQL and data engineering guides. Thanks for reading, and happy querying! 🦆</p><p><em>This article was reviewed with AI assistance.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d0bd15a014d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Regression Test Suite for RAG]]></title>
            <link>https://kotobara.medium.com/a-practical-regression-test-suite-for-rag-26150ebf216e?source=rss-207df8990ff0------2</link>
            <guid isPermaLink="false">https://medium.com/p/26150ebf216e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kotobara]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 07:10:44 GMT</pubDate>
            <atom:updated>2026-10-25T07:10:44.424Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ksIkD5DGE2vIo2KPDs8mhA.png" /></figure><p>A small retrieval change sends a production question to two runbooks: staging says retention is 90 days; an archived policy says 30. The current production rule is 7 days. Search returned documents and raised no exception. Staging has quietly acquired a new audience.</p><p>Let’s catch that before generating an answer. We’ll walk through the checks in a small regression suite, using short code excerpts and results from a local retrieval experiment. The answer cases are handwritten: no LLM generates answers in this experiment, and generation quality remains unmeasured.</p><h3>🔍 Three questions behind one RAG score</h3><p>In retrieval-augmented generation, search selects context and a model uses it to answer. Several things can fail independently:</p><ul><li><strong>Retrieval:</strong> did the necessary chunks arrive, with unsuitable versions excluded?</li><li><strong>Support:</strong> does the cited source support the particular claim?</li><li><strong>Completeness:</strong> did the answer cover everything the question asked?</li></ul><p>Good retrieval cannot guarantee a correct answer. A correct answer can also occur without the necessary evidence. Separate signals make it easier to find what broke.</p><p>The <a href="https://arxiv.org/html/2305.14627v2">ALCE paper</a> evaluates answer correctness and citation support separately, checking whether sources support statements. Here we’ll use a narrower task we can inspect directly: structured facts with manual annotations.</p><h3>Start with ten short documents</h3><p>Our fictional service, OrdersSync, has production documentation for retention, retries, deletions, dead-letter records, backfills, freshness, replay, and auditing. Two additional documents cover staging retention and an archived production policy.</p><p>Each document is one retrieval chunk with a stable ID, title, body, environment, and active flag. All data is synthetic.</p><p>Ten questions cover eight answerable cases and two with no answer in the corpus. Two answerable questions require two chunks. For example:</p><pre>{<br>  &quot;id&quot;: &quot;q07&quot;,<br>  &quot;question&quot;: &quot;What is the replay retention window and the retry limit?&quot;,<br>  &quot;relevant&quot;: [&quot;retention-prod&quot;, &quot;retry-prod&quot;],<br>  &quot;expected&quot;: {&quot;retention_days&quot;: 7, &quot;retry_attempts&quot;: 3}<br>}</pre><p>relevant identifies the chunks retrieval should find. expected identifies the facts needed for a complete answer. One correct number cannot cover both retention and retries.</p><p>These labels belong to this corpus. Changing chunk boundaries or document versions requires reviewing IDs and expectations. For a real product, include actual question types beyond phrasing the current retriever already handles well.</p><h3>🛠️ Keep retrieval simple enough to inspect</h3><p>SQLite FTS5 searches document titles and bodies using BM25 ranking. In FTS5, better matches receive smaller bm25 values, so we sort ascending. <a href="https://sqlite.org/fts5.html">SQLite documentation</a>.</p><p>The query builder extracts words, removes a fixed stopword list, and joins the remaining terms with OR. This is a lexical baseline without embeddings. Its main SQL is:</p><pre>SELECT doc_id, bm25(chunks) AS score<br>FROM chunks<br>WHERE chunks MATCH ?<br>  AND environment = &#39;production&#39;<br>  AND active = 1<br>ORDER BY score ASC, doc_id ASC<br>LIMIT ?;</pre><p>We retrieve two chunks. Metadata filters constrain the eligible documents; doc_id breaks equal-score ties. Both variants use the same index. The deliberately broken variant removes only the environment and active filters.</p><p>This is a constructed regression, not an incident from the author’s production system or a change produced by a separate coding agent.</p><h3>Measure what actually reached the context</h3><p>For an answerable question, Recall@2 is the fraction of labeled relevant chunks present in the first two results. The arithmetic is:</p><pre>selected = retrieved[:top_k]<br>relevant_set = set(relevant)<br>recall = len(set(selected) &amp; relevant_set) / len(relevant_set)</pre><p>Finding only retry-prod for q07 gives recall 0.5. Macro Recall@2 averages the eight answerable questions. Questions with an empty relevant list have undefined recall and are excluded rather than assigned an artificial zero.</p><p>We also calculate MRR@2: the mean reciprocal rank of the first relevant chunk within the first two positions, with zero when neither is relevant. These averages cover the same eight questions.</p><p>The local run produced:</p><ul><li><strong>Baseline:</strong> macro Recall@2 <strong>1.0</strong>, MRR@2 <strong>1.0</strong>, forbidden hits <strong>0</strong>.</li><li><strong>Without the filters:</strong> macro Recall@2 <strong>0.6875</strong>, MRR@2 <strong>0.75</strong>, forbidden hits <strong>5</strong>.</li></ul><p>Those five hits are document appearances across three questions, not five different documents. For the simple retention question, retention-staging and retention-archived occupy both positions.</p><p>For q07, retry-prod stays first while staging takes second place. Reciprocal rank remains 1, although recall drops to 0.5. The first useful result hides the missing second source.</p><p>Our small suite requires every answerable case to retrieve all labeled chunks and every case to exclude forbidden versions. That is this demonstration’s release criterion, not a universal threshold for RAG systems.</p><h3>🧪 A valid citation ID can accompany a wrong number</h3><p>Consider this handwritten answer:</p><pre>{<br>  &quot;abstain&quot;: false,<br>  &quot;claims&quot;: [<br>    {&quot;field&quot;: &quot;retention_days&quot;, &quot;value&quot;: 30, &quot;citation&quot;: &quot;retention-prod&quot;}<br>  ]<br>}</pre><p>The document exists, but it says 7 days. Checking whether the citation appears in the context would miss the wrong value.</p><p>Each document therefore has manually annotated field/value facts alongside its text. These annotations never enter the search index. The validator checks that the cited document belongs to the supplied context, is active production documentation, and supports that annotated pair.</p><p>Expected fields and values are checked separately. An answer giving only the retention period for q07 is supported but incomplete. A unit-test excerpt makes the distinction explicit:</p><pre>response = {&#39;abstain&#39;: False, &#39;claims&#39;: [<br>    {&#39;field&#39;: &#39;retention_days&#39;, &#39;value&#39;: 7, &#39;citation&#39;: &#39;retention-prod&#39;}<br>]}<br>actual = check_answer(response, [&#39;retention-prod&#39;, &#39;retry-prod&#39;],<br>                      {&#39;retention_days&#39;: 7, &#39;retry_attempts&#39;: 3}, self.documents_by_id)<br>self.assertTrue(actual[&#39;all_claims_supported&#39;])<br>self.assertFalse(actual[&#39;complete&#39;])<br>self.assertFalse(actual[&#39;passed&#39;])</pre><p>The twelve manual cases include valid answers and abstentions, wrong values, citations outside the context, archived and staging sources, missing facts, empty answers, and duplicate claims. The validator classified all twelve according to their expectations. This evaluates the checker, not an LLM’s accuracy on twelve generations.</p><p>Groundedness here means support for structured facts against manual annotations. The checker cannot establish whether arbitrary prose follows from a passage. Answer-case contexts are supplied manually; no generator connects them to the retrieval experiment.</p><h3>No answer does not require empty retrieval</h3><p>The first test run required empty search results for both unanswerable questions. It failed: a key-rotation question found an audit document through a lexical match. The document contains no key-rotation rule.</p><p>We corrected that expectation without changing the question or corpus. Unknown questions have no recall denominator; abstention is checked separately. One manual case receives the irrelevant audit context and correctly returns abstain: true without claims.</p><p>Empty retrieval is useful diagnostic information. Deciding that the available evidence cannot answer a question still needs an answer-level check.</p><h3>Make the release check fail visibly</h3><p>The local experiment ran on Python 3.12.10 and SQLite 3.49.1, with all ten unit tests passing. A separate release check accepted the baseline with exit code <strong>0</strong> and rejected the deliberately broken retrieval variant with exit code <strong>1</strong>.</p><p>For your own pipeline, keep the failure reasons explicit:</p><ul><li>A required chunk is missing from the context.</li><li>A staging or archived document reaches a production question.</li><li>An answer contains an unsupported claim or leaves out a required fact.</li></ul><p>Preserve the retrieved IDs and per-question outcomes alongside aggregate metrics, configuration, and input versions. That gives a reviewer something concrete to investigate.</p><p>Also separate diagnostics from enforcement. A reporting job can complete successfully while describing a failed candidate. The CI step must propagate a failed release check as a nonzero exit code.</p><h3>The next step is a real model run</h3><p>Free-text answers need semantic support, completeness, and abstention checks on actual generations. The <a href="https://arxiv.org/html/2309.15217v2">Ragas paper</a> estimates faithfulness by extracting statements and using an LLM to assess their support in the context. Those judgments differ from calculating recall over fixed IDs.</p><p>Next, save real model answers and their contexts, add independent human labels, and check agreement with an automated judge. Record the judge’s model version, prompt, and settings. None of those runs or results are part of this experiment.</p><p>Ten constructed questions cannot establish product quality. This suite was used during development and has no held-out evaluation set. Metadata filtering also does not replace authorization. A real retriever needs its own corpus, labels, and access checks.</p><p>Start with one production question that has a current runbook, an old version, and a staging counterpart. Inspect the IDs reaching the generator. Then add an answer with a valid citation and a wrong number. Two small checks can give a release two concrete reasons to stop.</p><p>If you found this article helpful, give it a 👏 clap (or a few) and subscribe for more practical RAG, Python, and data engineering guides. Thanks for reading, and happy testing! 🧪</p><p><em>This article was reviewed with AI assistance.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26150ebf216e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Valid SQL Gives the Wrong Business Answer]]></title>
            <link>https://kotobara.medium.com/when-valid-sql-gives-the-wrong-business-answer-cbce15281196?source=rss-207df8990ff0------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbce15281196</guid>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Kotobara]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 18:29:39 GMT</pubDate>
            <atom:updated>2026-10-23T18:29:39.316Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eEreVNEBJ1tdOc9WLW700Q.png" /></figure><p>Three orders, 170. The extra $70 is a reporting feature nobody requested.</p><p>The example uses synthetic orders and refunds.</p><p>Let’s find where that money came from. We’ll build a small sales report, break it in a few plausible ways, and add tests that catch the mistakes. Python’s sqlite3 module lets us run the example in memory without a database server. <a href="https://docs.python.org/3/library/sqlite3.html">Python sqlite3 documentation</a>.</p><h3>🔍 Step 1: Decide what “January net sales” means</h3><p>Before the first SELECT, we need one agreement. Does January mean when an order was created or when it was paid? Do refunds belong to their settlement month, or do they reduce the value of the original month’s orders? Each choice answers a different question.</p><p>Here’s the metric contract for our example:</p><ul><li>Include completed orders paid from January 1, 2026, inclusive, to February 1, exclusive, in UTC.</li><li>Sum their item values: quantity multiplied by unit price.</li><li>Subtract settled refunds for those orders with a settlement time strictly before February 1. Exclude pending refunds.</li><li>Use integer USD cents. Discounts, taxes, shipping, and fees are outside the model.</li></ul><p>We’re measuring the net item value of a January payment cohort at a chosen refund cutoff. “Cohort” just means the orders selected by the same rule. This is our example’s definition of net sales; accounting revenue would need its own definition.</p><p>Keep the payment window and refund cutoff separate. Move the cutoff to February 2, and a later refund can change the value of the same January cohort. Order statuses still come from a fixed snapshot. The cutoff controls eligible refunds; reconstructing historical order states would require more data.</p><h3>Step 2: Keep the data small enough to check</h3><p>Six orders, seven item rows, and five refund records are enough. The amounts below use dollars for readability; the code stores cents.</p><ul><li><strong>Order 1:</strong> completed and paid in January. Items: 50. Eligible refunds: 10. Contribution: <strong>$70</strong>.</li><li><strong>Order 2:</strong> completed and paid in January. Items: 100**.</li><li><strong>Order 3:</strong> cancelled and unpaid. Items: $70. No refunds. Excluded from the metric.</li><li><strong>Order 4:</strong> pending payment. Items: $40. No refunds. Excluded from the metric.</li><li><strong>Order 5:</strong> completed and paid exactly on February 1. Items: $90. No refunds. Excluded from the January cohort.</li><li><strong>Order 6:</strong> completed and paid in January. Items: 50. Contribution: <strong>$0</strong>.</li></ul><p>Order 1 also has a 7 pending refund. Neither qualifies. Order 6 remains in the cohort despite its full refund: it contributes zero dollars and still counts as an order.</p><p>Add the contributions by hand: (100 − 30) + 100 + (50 − 50) = 170 dollars. Now we have a ledger to check against, before the query gets a chance to convince us it’s right.</p><h3>First attempt: $360</h3><p>Let’s start with the straightforward version:</p><pre>SELECT COALESCE(SUM(quantity * unit_price_cents), 0) AS net_cents<br>FROM orders<br>JOIN order_items USING (order_id)<br>WHERE created_at &gt;= :period_start<br>  AND created_at &lt; :period_end;</pre><p>Run it against the sample data and you get 36000 cents. It includes cancelled and pending orders created in January and subtracts no refunds. The net_cents alias describes what we wanted, while the query calculates something else.</p><p>Switch to paid_at and add orders.status = &#39;completed&#39;. We’re down to 25000 cents: the right orders, with their gross item value. Next, we need to subtract refunds.</p><p>That gives us two things to check separately: which orders qualify, and how much each should contribute.</p><h3>Add refunds, get $240</h3><p>A join seems reasonable here:</p><pre>SELECT<br>    COUNT(*) AS joined_rows,<br>    COUNT(DISTINCT orders.order_id) AS order_count,<br>    COALESCE(SUM(quantity * unit_price_cents), 0)<br>        - COALESCE(SUM(refunds.amount_cents), 0) AS net_cents<br>FROM orders<br>JOIN order_items USING (order_id)<br>LEFT JOIN refunds<br>    ON orders.order_id = refunds.order_id<br>   AND refunds.status = &#39;settled&#39;<br>   AND refunds.settled_at &lt; :as_of<br>WHERE orders.status = &#39;completed&#39;<br>  AND paid_at &gt;= :period_start<br>  AND paid_at &lt; :period_end;</pre><p>This version returns three distinct orders, six joined rows, and 24000 cents. Checking only the order count would send us home happy with the wrong report.</p><p>Look at what a row means in each table. In order_items, it’s an item; in refunds, it’s a refund operation. That’s the table’s grain. Join them by order, and order 1 gets every matching item–refund pair:</p><ul><li>Item <strong>11</strong> (20).</li><li>Item <strong>11</strong> (10).</li><li>Item <strong>12</strong> (20).</li><li>Item <strong>12</strong> (10).</li></ul><p>Two items multiplied by two refunds give us four rows. Those rows sum to 60 in refunds. Order 1 now contributes 70. Add 240.</p><p>The join is producing exactly the combinations its condition asks for. Also keep the refund filters in ON: moving them into WHERE would exclude orders without matching refunds. <a href="https://sqlite.org/lang_select.html">SQLite’s explanation of joins and filtering</a>.</p><p>COUNT(DISTINCT order_id) counts the identifiers correctly. It tells us nothing about how often each amount entered the sum.</p><h3>The tempting fix: SUM(DISTINCT …)</h3><p>Maybe we can remove the repeats inside the sums:</p><pre>SUM(DISTINCT quantity * unit_price_cents)<br>    - SUM(DISTINCT refunds.amount_cents)</pre><p>Now we get 7000 cents. Only two distinct item values survive: 100. The trouble is that all three $50 items are legitimate: two belong to order 1 and one to order 6.</p><p>DISTINCT inside an aggregate removes duplicate argument values. It cannot identify which business events those values represent. <a href="https://www.sqlite.org/lang_aggfunc.html">SQLite aggregate documentation</a>.</p><p>That’s why the sample data deliberately includes equal prices. A test with unique prices could miss the valid amounts this fix throws away.</p><h3>🛠️ Step 3: Get to one row per order before joining</h3><p>Let’s give both sides the same grain. Aggregate items and eligible refunds separately, then join those totals to the selected orders. Each side can now add at most one row per order:</p><pre>WITH eligible_orders AS (<br>    SELECT order_id<br>    FROM orders<br>    WHERE status = &#39;completed&#39;<br>      AND paid_at &gt;= :period_start<br>      AND paid_at &lt; :period_end<br>),<br>item_totals AS (<br>    SELECT order_id, SUM(quantity * unit_price_cents) AS gross_cents<br>    FROM order_items<br>    GROUP BY order_id<br>),<br>refund_totals AS (<br>    SELECT order_id, SUM(amount_cents) AS refunded_cents<br>    FROM refunds<br>    WHERE status = &#39;settled&#39;<br>      AND settled_at &lt; :as_of<br>    GROUP BY order_id<br>)<br>SELECT<br>    eligible_orders.order_id,<br>    COALESCE(item_totals.gross_cents, 0) AS gross_cents,<br>    COALESCE(refund_totals.refunded_cents, 0) AS refunded_cents,<br>    COALESCE(item_totals.gross_cents, 0)<br>        - COALESCE(refund_totals.refunded_cents, 0) AS net_cents<br>FROM eligible_orders<br>LEFT JOIN item_totals USING (order_id)<br>LEFT JOIN refund_totals USING (order_id)<br>ORDER BY eligible_orders.order_id;</pre><p>We get 7000, 10000, and 0 cents, matching the ledger order by order. Python adds them up to 17000; another SQL aggregation could do the same job. Keep that order detail available during review. Two mistakes can cancel each other out in a grand total.</p><p>One detail matters here: no refund means zero refunded cents. A completed order with no items needs a data-quality check. COALESCE can supply a zero, but we still need to detect missing data. The test suite checks that case separately.</p><h3>🧪 Step 4: Change the data without changing the answer</h3><p>The companion example contains the schema, fixed inserts, SQL files, and tests. From the project root:</p><pre>python articles/M01-sql-business-metrics/examples/run.py --test</pre><p>The example ran locally on Python 3.12.10 and SQLite 3.49.1, with all 12 tests passing. We check the ledger, then make changes whose effect we can predict.</p><p>For example, splitting a 25 items should preserve the total:</p><pre>self.connection.execute(<br>    &#39;UPDATE order_items SET unit_price_cents = 2500 WHERE item_id = 11&#39;<br>)<br>self.connection.execute(<br>    &#39;INSERT INTO order_items VALUES (13, 1, 1, 2500)&#39;<br>)<br>self.assertEqual(self.net_total(), 17000)</pre><p>The correct metric stays at 17000. The direct join changes its answer because the same refunds now repeat across three items. Another test splits a refund into two operations with the same combined value.</p><p>Adding an item at an already-seen price must increase the metric by that item’s value. This catches the SUM(DISTINCT ...) mistake. Other checks cover statuses, both payment-window boundaries, pending refunds, an empty cohort, and a later refund cutoff.</p><h3>Where this approach needs more work</h3><p>This works for the order-level question we agreed on. For a product or category report, you’ll need to link refunds to items or decide how to allocate order-level refunds.</p><p>Timestamps here use one normalized UTC format. The model does not reconstruct changing statuses, late-arriving records, or corrected source data. Filtering settled_at limits when a refund occurred, not when the reporting system learned about it. Reproducible historical reporting needs that distinction resolved through history or snapshots.</p><p>Before shipping your next sales query, build a small ledger with deliberately awkward orders: multiple items, multiple refunds, equal prices, no refunds, and boundary timestamps. Check each contribution, then split an item or refund and see whether the total stays put.</p><p>It’s a small test. In this example, it would have caught the extra $70 before it reached the report.</p><p>If you found this article helpful, give it a 👏 clap (or a few) and subscribe for more practical SQL, Python, and data engineering guides. Thanks for reading, and happy querying! 🎉</p><p><em>This article was reviewed with AI assistance.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbce15281196" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Reliable Job Queue in PostgreSQL (Without Redis, Kafka and Existential Crisis)]]></title>
            <link>https://kotobara.medium.com/building-a-reliable-job-queue-in-postgresql-without-redis-kafka-and-existential-crisis-c86928606f31?source=rss-207df8990ff0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c86928606f31</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[task-queues]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Kotobara]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 13:40:17 GMT</pubDate>
            <atom:updated>2026-03-01T13:40:17.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5WRvEDIDdGjyuKsNMLgU0g.png" /></figure><p>We love adding infrastructure. Redis for queues. Kafka for events. RabbitMQ, because “enterprise.”<br> And then one day you look at your stack and realize you have more brokers than business logic.</p><p><em>What if… PostgreSQL is already enough?</em></p><p>Let’s build a production-ready job queue directly in PostgreSQL using row locking and FOR UPDATE SKIP LOCKED.</p><p>No magic. No extra services. Just SQL behaving like a responsible adult.</p><h3>Why PostgreSQL as a Queue?</h3><p>Postgres already gives you:<br>- ACID guarantees<br>- Row-level locking<br>- Transactions<br>- Durable storage<br>- Indexing<br>- Visibility into job state</p><p>If your workload is moderate (thousands, maybe tens of thousands of jobs per minute), Postgres handles it comfortably.</p><p>And unlike many queue systems, your jobs live next to your business data. No sync headaches.</p><h3>The Core Idea</h3><p>We want:</p><ol><li>Multiple workers</li><li>No job processed twice</li><li>No blocking between workers</li><li>Safe retries</li><li>Visibility into failures</li></ol><p>The magic ingredient:</p><pre>FOR UPDATE SKIP LOCKED</pre><p>This allows multiple workers to fetch jobs concurrently without stepping on each other.</p><h3>Step 1 — Job Table Design</h3><p>Keep it simple but realistic.</p><pre>CREATE TABLE job_queue (<br>    id              BIGSERIAL PRIMARY KEY,<br>    payload         JSONB NOT NULL,<br>    status          TEXT NOT NULL DEFAULT &#39;pending&#39;,<br>    attempts        INT NOT NULL DEFAULT 0,<br>    max_attempts    INT NOT NULL DEFAULT 5,<br>    run_at          TIMESTAMPTZ NOT NULL DEFAULT NOW(),<br>    locked_at       TIMESTAMPTZ,<br>    locked_by       TEXT,<br>    last_error      TEXT,<br>    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()<br>);</pre><p>Recommended index:</p><pre>CREATE INDEX idx_job_queue_pending <br>ON job_queue (run_at) <br>WHERE status = &#39;pending&#39;;</pre><p>Why partial index? Because scanning the entire table every time is how you ruin your weekend.</p><h3>Step 2 — Enqueue a Job</h3><p>Simple insert:</p><pre>INSERT INTO job_queue (payload)<br>VALUES (&#39;{&quot;type&quot;: &quot;send_email&quot;, &quot;user_id&quot;: 123}&#39;);</pre><p>If you need delayed execution:</p><pre>INSERT INTO job_queue (payload, run_at)<br>VALUES (&#39;{&quot;type&quot;: &quot;generate_report&quot;}&#39;, NOW() + INTERVAL &#39;10 minutes&#39;);</pre><h3>Step 3 — Dequeue with SKIP LOCKED</h3><p>This is the heart of the system.</p><pre>WITH next_job AS (<br>    SELECT id<br>    FROM job_queue<br>    WHERE status = &#39;pending&#39;<br>      AND run_at &lt;= NOW()<br>    ORDER BY run_at<br>    FOR UPDATE SKIP LOCKED<br>    LIMIT 1<br>)<br>UPDATE job_queue<br>SET status = &#39;processing&#39;,<br>    locked_at = NOW(),<br>    locked_by = &#39;worker-1&#39;,<br>    attempts = attempts + 1<br>FROM next_job<br>WHERE job_queue.id = next_job.id<br>RETURNING job_queue.*;</pre><p>What happens here?</p><ul><li>Multiple workers run this simultaneously</li><li>Each worker locks a different row</li><li>Locked rows are skipped</li><li>No blocking</li><li>No duplicates</li></ul><p>It’s shockingly elegant for something written in SQL.</p><h3>Step 4 — Worker Logic (Python Example)</h3><p>Because yes, someone has to actually run the job.</p><pre>import psycopg2<br>import json<br><br>def process_jobs():<br>    conn = psycopg2.connect(...)<br>    conn.autocommit = False<br><br>    while True:<br>        with conn.cursor() as cur:<br>            cur.execute(DEQUEUE_SQL)<br>            row = cur.fetchone()<br><br>            if not row:<br>                conn.commit()<br>                break<br><br>            job_id, payload = row[0], row[1]<br><br>            try:<br>                handle_job(payload)<br><br>                cur.execute(<br>                    &quot;UPDATE job_queue SET status=&#39;done&#39; WHERE id=%s&quot;,<br>                    (job_id,)<br>                )<br><br>            except Exception as e:<br>                cur.execute(<br>                    &quot;&quot;&quot;<br>                    UPDATE job_queue<br>                    SET status = CASE<br>                        WHEN attempts &gt;= max_attempts THEN &#39;failed&#39;<br>                        ELSE &#39;pending&#39;<br>                    END,<br>                    last_error = %s<br>                    WHERE id = %s<br>                    &quot;&quot;&quot;,<br>                    (str(e), job_id)<br>                )<br><br>            conn.commit()</pre><p>Notice:</p><ul><li>Job processing and status updates happen in one transaction</li><li>Retry logic is controlled by the database</li><li>Failed jobs don’t disappear silently</li></ul><h3>Handling Crashed Workers</h3><p>What if a worker dies mid-job?<br>You’ll have jobs stuck in processing.<br>Solution: add a reaper query.</p><pre>UPDATE job_queue<br>SET status = &#39;pending&#39;,<br>    locked_at = NULL,<br>    locked_by = NULL<br>WHERE status = &#39;processing&#39;<br>  AND locked_at &lt; NOW() - INTERVAL &#39;10 minutes&#39;;</pre><p>Run it periodically.<br>Now your queue heals itself. Almost suspiciously competent.</p><h3>Concurrency Model</h3><p>Let’s imagine 5 workers running in parallel.</p><p>Without SKIP LOCKED:</p><ul><li>Workers block each other.</li><li>Throughput collapses.</li><li>You start questioning your life choices.</li></ul><p>With SKIP LOCKED:</p><ul><li>Each worker grabs a free row.</li><li>No waiting.</li><li>No deadlocks.</li><li>Horizontal scaling works naturally.</li></ul><p>Postgres does the hard part.</p><h3>When This Approach Is Perfect</h3><p>Use Postgres queue if:</p><ul><li>You already use PostgreSQL</li><li>Job volume is moderate</li><li>You want strong consistency</li><li>You don’t need distributed streaming semantics</li><li>Simplicity matters</li></ul><h3>When You Should Not Use It</h3><p>Let’s be honest.</p><p>If you need:</p><ul><li>Millions of events per second</li><li>Cross-region streaming</li><li>Long event retention</li><li>Complex consumer groups</li></ul><p>Then use Kafka.</p><p>But if your background tasks are:</p><ul><li>Email sending</li><li>Report generation</li><li>Data sync</li><li>ML processing</li><li>Search indexing</li></ul><p>Postgres is more than enough.</p><h3>Final Thoughts</h3><p>There’s something deeply satisfying about using one well-understood tool instead of five shiny ones.</p><p>A PostgreSQL job queue is:</p><ul><li>Predictable</li><li>Transactionally safe</li><li>Easy to debug</li><li>Easy to monitor</li><li>Boring</li></ul><p>And boring infrastructure is beautiful.</p><p>You don’t always need more services.<br> Sometimes you just need better SQL.</p><p>And yes, your database can handle it.</p><p><strong>If you found this article helpful, give it a 👏 clap (or a few) and subscribe for more insights! Thank you for reading, and happy querying with Snowflake Cortex AISQL! 🎊</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c86928606f31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Entity Recognition and Anonymization: AWS Comprehend vs Microsoft Presidio]]></title>
            <link>https://kotobara.medium.com/entity-recognition-and-anonymization-aws-comprehend-vs-microsoft-presidio-62cf638642e3?source=rss-207df8990ff0------2</link>
            <guid isPermaLink="false">https://medium.com/p/62cf638642e3</guid>
            <category><![CDATA[anonymization]]></category>
            <category><![CDATA[presidio]]></category>
            <category><![CDATA[pii]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[aws-comprehend]]></category>
            <dc:creator><![CDATA[Kotobara]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 09:41:26 GMT</pubDate>
            <atom:updated>2025-11-12T09:41:26.468Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dND4bRJaxqJsln96G76_-A.png" /></figure><h3>Introduction</h3><p>Protecting sensitive data is a crucial skill for modern developers. <strong>Entity recognition</strong> in this context refers to identifying personally identifiable information (PII) like names, phone numbers, emails, etc., within text. <strong>Anonymization</strong> (or redaction) means masking or removing that PII so the data can be safely used (for example, in analytics or machine learning) without exposing private details. Two popular tools for automating PII detection are <strong>Amazon’s AWS Comprehend</strong> and <strong>Microsoft’s Presidio</strong>. Both can find PII in text and help anonymize it, but they differ in approach. This article provides a beginner-friendly comparison of AWS Comprehend and Microsoft Presidio, with code examples using each tool’s API/SDK. Junior developers will learn how to detect and redact PII using these tools and understand their ease of use, setup, flexibility, accuracy, and deployment differences.</p><h3>AWS Comprehend for PII Entity Recognition</h3><p>AWS Comprehend is a fully managed cloud service for natural language processing. It includes a pre-trained <strong>PII detection</strong> feature that can scan text (in English or Spanish) and return any detected sensitive entities. Under the hood, AWS uses machine learning models to identify PII. As a cloud API, you send text to the service and get back structured results (in JSON) listing each entity type, its position in the text, and a confidence score. For example, if a text contains a person’s name and phone number, Comprehend might return that it found a <strong>NAME</strong> and <strong>PHONE_NUMBER</strong> entity with high confidence, along with the text offsets where those appear.</p><p>Using AWS Comprehend via the AWS SDK or CLI is straightforward. First, you need AWS credentials and to enable the Comprehend API. You can then call the detect_pii_entities operation. Here’s an example using the AWS CLI to detect PII in a sample text:</p><pre>aws comprehend detect-pii-entities \<br>  --text &quot;Dr. Emily Johnson recently visited our clinic. Her contact number is (555) 123-4567, and her email is [email protected]. She lives at 456 Elm Street, Springfield, IL 62704.&quot; \<br>  --language-code en</pre><p>This command sends the text to Comprehend’s PII detection. The output will be a JSON object listing each PII entity found (e.g., <strong>NAME</strong>, <strong>PHONE_NUMBER</strong>, <strong>EMAIL_ADDRESS</strong>, <strong>ADDRESS</strong>), along with their positions and confidence scores. For instance, Comprehend would identify “Emily Johnson” as a <strong>NAME</strong>, the phone number as <strong>PHONE_NUMBER</strong>, the email as <strong>EMAIL_ADDRESS</strong>, etc., each with a score indicating the model’s confidence.</p><p>By default, AWS Comprehend’s real-time API only <strong>detects</strong> PII. If you want to automatically redact (mask) the PII in text, AWS provides an asynchronous batch job feature that can return the text with PII replaced by placeholders. In practice, many developers simply use the detection results and then programmatically replace or remove the sensitive pieces (e.g., replace digits of a credit card number with ****). The advantage of Comprehend is that there’s no machine learning model for you to set up – all the complexity is handled by AWS. You get a reliable, maintained service that recognizes common PII entities using Amazon’s trained models. Another benefit is that Comprehend can leverage contextual cues to reduce false alarms; for example, it might ignore a 9-digit number if it doesn’t resemble a known ID format, but detect it if it’s labeled like “SSN: 123456789”. This results in fewer false positives in some cases. On the flip side, because it’s a generic service, you cannot easily customize what it considers PII – the set of detectable entities is fixed and defined by AWS (though it covers most standard PII types). Also, you can’t restrict detection to only specific PII types in a single API call – Comprehend will always scan for all supported PII and you would filter the results in your code if needed. Finally, since it’s a cloud service, using Comprehend means your text data is sent to AWS servers (which could be a consideration for highly sensitive data), and it incurs a cost per use (though relatively small, on the order of fractions of a cent per hundred characters).</p><h3>Microsoft Presidio for PII Detection and Anonymization</h3><p>Microsoft Presidio is an <strong>open-source</strong> framework for PII detection and anonymization. Unlike AWS Comprehend which is offered as a web service, Presidio is a <strong>library</strong> (and a set of APIs) you can run in your own environment. It was designed to be highly customizable and extensible. Out of the box, Presidio uses a combination of techniques: it has predefined pattern recognizers (like regular expressions for phone numbers, email patterns, etc.), an <strong>NLP named entity recognition (NER)</strong> model (SpaCy by default) for things like names and locations, and even contextual checks (like Luhn checksum for credit card numbers or known prefixes for SSNs). In simpler terms, Presidio tries multiple methods to find PII in text — if a regex finds a pattern or the ML model finds an entity, it flags it, and it can cross-verify with context or checks to improve accuracy.</p><p>One of Presidio’s strengths is that it not only detects PII, but also provides an <strong>anonymization</strong> engine to redact or replace that PII automatically. Developers can specify different anonymization <strong>operators</strong> — for example, replace detected PII with a generic placeholder, mask it with asterisks, hash it, or even encrypt it. Presidio supports <strong>customization</strong> at many levels: you can add new PII types (e.g. if you want to detect employee IDs or other domain-specific data) by writing custom recognizers, switch out the underlying NER model or language (SpaCy English model is default, but you can plug in Stanza or transformer models for other languages), and adjust the confidence thresholds or context words to fine-tune detection. This flexibility means Presidio can be tailored to detect practically any sensitive pattern if configured properly, whereas a service like Comprehend is limited to the predefined entity types it supports.</p><p>To use Presidio, you will need a Python environment (or you can use Docker containers that Microsoft provides). For example, to get started in Python you would install the Presidio packages and a language model:</p><pre>pip install presidio-analyzer presidio-anonymizer<br>python -m spacy download en_core_web_lg</pre><p>The above installs the Presidio Analyzer and Anonymizer packages, and downloads SpaCy’s large English model (which Presidio uses for NLP). Now, here’s a simple Python snippet using Presidio to detect and redact a phone number in text:</p><pre>from presidio_analyzer import AnalyzerEngine<br>from presidio_anonymizer import AnonymizerEngine<br><br>text = &quot;Contact me at (555) 123-4567 for more information.&quot;<br><br># Initialize the Analyzer and Anonymizer<br>analyzer = AnalyzerEngine()<br>anonymizer = AnonymizerEngine()<br><br># Detect PII entities in the text (looking specifically for phone numbers)<br>analysis_results = analyzer.analyze(text=text, entities=[&quot;PHONE_NUMBER&quot;], language=&#39;en&#39;)<br>print(analysis_results)  # list of identified entities with positions and scores<br><br># Anonymize the detected PII (replace phone number with a default mask)<br>anonymized_result = anonymizer.anonymize(text=text, analyzer_results=analysis_results)<br>print(anonymized_result.text)</pre><p>In the analysis step, we specifically told Presidio to only look for phone numbers by setting entities=[&quot;PHONE_NUMBER&quot;]. The AnalyzerEngine will return a list of findings (each with a type, start/end index, and confidence score). In this case, it should find the phone number (555) 123-4567 and label it as PHONE_NUMBER. The printout of analysis_results might look like:</p><pre>[type: PHONE_NUMBER, start: 12, end: 26, score: 1.0]</pre><p>This indicates Presidio found a phone number at character positions 12–26 with high confidence (score 1.0). We then pass these results to AnonymizerEngine.anonymize(), which by default will replace the phone number in the text with a placeholder. The anonymized_result.text might read:</p><pre>Contact me at &lt;PHONE_NUMBER&gt; for more information.</pre><p>Now the sensitive number is removed. Presidio makes it easy to configure how you anonymize each type of entity — you could mask with ******, use fake values, or other methods, by specifying different operators in the call (for example, an encryption operator if you wanted reversible anonymization<a href="https://blog.stackademic.com/presidio-in-action-detecting-and-securing-pii-in-text-451711e3c544?gi=cd900a29eb1c#:~:text=operation%20of%20our%20choice,engine%20contains%20of%202%20components">blog.stackademic.com</a>).</p><p>Because Presidio runs locally (or in whatever environment you deploy it), <strong>your data stays in-house</strong> — it’s not sent to an external cloud service. This is a big advantage if you have strict data privacy requirements or cannot share data with third-party services. However, being open-source also means you are responsible for maintaining it. There’s no official support beyond community resources, and using Presidio might require more coding and infrastructure if you want to scale it (e.g. running it as a service, managing updates)<a href="https://datastreamer.io/top-pii-redaction-tools-guide/#:~:text=Being%20open,the%20world%20of%20PII%20redaction">datastreamer.io</a>. Microsoft does provide samples for deploying Presidio in various ways (as a web API, on Kubernetes, etc.)<a href="https://microsoft.github.io/presidio/faq/#:~:text=Deployment">microsoft.github.io</a>. In terms of performance and accuracy, Presidio’s default configuration works well for common PII patterns, but since it relies partly on SpaCy’s NLP, extremely domain-specific or subtle entities might not be caught until you add a custom recognizer or a better model. The good news is you have the freedom to improve its detection logic for your needs.</p><h3>AWS Comprehend vs Microsoft Presidio: A Comparison</h3><p>Both AWS Comprehend and Microsoft Presidio can help automate PII detection and anonymization, but they have different strengths. Here’s a concise comparison on key points:</p><ul><li><strong>Ease of Use:</strong> AWS Comprehend is very easy to get started — you call a web API and get results, no ML expertise required. Presidio, being a library, is also developer-friendly but requires writing code and understanding its components. In short, Comprehend is plug-and-play via API, whereas Presidio might involve a bit more hands-on setup and coding (though it’s straightforward for Python developers).</li><li><strong>Setup and Integration:</strong> With Comprehend, setup mainly involves an AWS account and credentials. There’s nothing to install, but you do need network access to AWS and must handle authentication. In contrast, Presidio requires installing packages (and downloading models like SpaCy’s), and possibly setting up a service if multiple apps will use it. Integrating Comprehend with your application can be as simple as an HTTPS request to AWS, while integrating Presidio means running it within your app’s environment or as a microservice. Additionally, Comprehend automatically scales on AWS infrastructure, whereas with Presidio you’d need to scale the compute resources yourself if processing large volumes of data.</li><li><strong>Flexibility &amp; Customization:</strong> This is where Presidio shines. Presidio is <strong>designed to be customized</strong> — you can modify or add new PII detectors (regex, ML models, etc.) to cover niche entities and languages. You have fine-grained control over what is considered sensitive and how to anonymize it. AWS Comprehend’s PII detection, on the other hand, is a fixed service — you cannot change how it works or add new entity types it doesn’t already know. The AWS service uses proprietary models and doesn’t allow tweaking recognition rules. If your use case involves standard PII types, Comprehend’s predefined model is usually sufficient. But if you need to detect custom patterns (say, <strong>policy IDs</strong> or game usernames), or you want to integrate with different NLP frameworks, Presidio’s flexibility is invaluable.</li><li><strong>Accuracy:</strong> Both tools are quite accurate on common PII, but their approaches differ. AWS Comprehend uses a trained model and context, which often gives it <strong>broad coverage and precision for typical personal data</strong>. It may produce fewer false positives — for example, it might avoid flagging a random 9-digit number unless context suggests it’s an ID. However, Comprehend might miss some instances if they don’t fit its learned patterns (in one test, it failed to recognize an SSN lacking the usual format until a keyword like “SSN” was present). Presidio’s default recognizers (regex + NER) will catch many obvious patterns (it would detect a raw 9-digit number as a potential SSN), but this can result in more <strong>false positives</strong> unless you fine-tune it. The upside is that Presidio provides confidence scores and allows you to adjust rules or thresholds to improve accuracy. In sum, Comprehend’s out-of-the-box accuracy is excellent for general-purpose needs (and was noted for having very few false positives in at least one evaluation), while Presidio’s accuracy can approach similar levels with customization — and it may outperform in scenarios involving custom entity types or formats that Comprehend doesn’t handle at all (because you can teach Presidio about them).</li><li><strong>Deployment (Cloud vs Local):</strong> AWS Comprehend is a <strong>cloud service</strong>. This means you don’t manage servers for it — you just use it over the internet. The trade-off is that your text data is sent to AWS’s cloud and you incur usage fees. Some organizations are uncomfortable sending sensitive text to an external service, even if AWS promises security. Microsoft Presidio is <strong>self-hosted</strong> — you run it on your own machines or in your private cloud. All processing happens locally in your environment. This gives you full control over data residency and privacy. It also means, however, that you are responsible for ensuring the service is running reliably. From a scalability perspective, Comprehend can handle large volumes on AWS seamlessly, whereas scaling Presidio would mean deploying it on more powerful hardware or multiple instances yourself. If internet access or latency is a concern (e.g., analyzing data in a secure offline environment), Presidio would be the go-to choice since it does not require external calls. Conversely, if maintaining infrastructure is not desirable, Comprehend’s fully-managed cloud approach is convenient.</li></ul><h3>Conclusion</h3><p><strong>AWS Comprehend and Microsoft Presidio are both powerful tools for entity recognition and data anonymization</strong>, but they cater to slightly different needs. If you want a quick, hassle-free solution and don’t mind using a cloud service, AWS Comprehend offers accurate PII detection with minimal setup — ideal for smaller projects or when you’re already in the AWS ecosystem. On the other hand, if your project demands more control — say you need to detect custom sensitive data types, work in an offline environment, or apply specific anonymization policies — Microsoft Presidio provides a flexible framework that you can mold to your requirements. Presidio requires a bit more effort to set up, but it empowers you to extend its capabilities in ways a closed cloud service cannot. Many teams might even use both: for example, using Comprehend for quick cloud-based processing of standard data, and Presidio for in-house processing of highly sensitive or specialized data. By understanding the strengths of each, you can choose the right tool for the job and build privacy-preserving features into your applications with confidence. Happy coding, and happy anonymizing!</p><p>👏 If this article helped you, leave a <em>Clap</em>, share it with your data team, and follow for the next deep dive</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62cf638642e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Snowflake Cortex Analyst: When SQL Starts to Understand Meaning]]></title>
            <link>https://kotobara.medium.com/snowflake-cortex-analyst-when-sql-starts-to-understand-meaning-5e73a215d94b?source=rss-207df8990ff0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e73a215d94b</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Kotobara]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 08:35:52 GMT</pubDate>
            <atom:updated>2025-10-12T08:35:52.436Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0h5beJbl0WH4fREIQQPDgQ.png" /></figure><h3>🚀 Introduction — When SQL Starts to Understand Meaning</h3><p>For decades, SQL has been <em>literal</em>.<br> It executes exactly what you tell it to — but it never really <em>understands</em> what you mean.</p><p>Now imagine this:</p><pre>SELECT &quot;Total revenue per product in Europe&quot; FROM SALES_SEMANTIC_VIEW;</pre><p>…and Snowflake automatically figures it out: which tables to join, which metrics to sum, which filters to apply.<br> That’s what <strong>Snowflake Cortex Analyst</strong> does — it turns your data warehouse into a <strong>semantic reasoning engine</strong>.</p><h3>🧩 What Is a Semantic View?</h3><blockquote><em>A </em><strong><em>Semantic View</em></strong><em> is a layer that defines what your data </em>means<em> — not just how it’s stored.</em></blockquote><p>It acts like an intelligent <em>data catalog + logic layer</em>, mapping business concepts (like “revenue”, “orders”, “regions”) to the physical schema.<br> In simple terms: it’s the <em>mind</em> of your data warehouse.</p><p>Instead of manually joining tables every time you query, you create a <strong>semantic model</strong> (via YAML) that tells Snowflake how everything connects — tables, relationships, metrics, dimensions, synonyms, and business rules.</p><p>Then, Cortex Analyst can use this model to interpret <strong>natural language queries</strong> like:</p><blockquote><em>“Show me total revenue by product category for Q1.”</em></blockquote><p>…and generate optimized SQL on the fly.</p><h3>⚙️ How Cortex Analyst Works</h3><p>Here’s the high-level process behind Cortex Analyst:</p><ol><li><strong>Semantic View Layer</strong> — defines logical tables, metrics, and relationships.</li><li><strong>Natural Language Understanding</strong> — parses your question and maps it to the model.</li><li><strong>SQL Generation</strong> — automatically builds and executes a valid query.</li><li><strong>Explanation Layer</strong> — returns both results and an explanation of how they were derived.</li></ol><p>This bridges the gap between <strong>business intent</strong> and <strong>data logic</strong>, letting anyone — not just engineers — query data intelligently.</p><h3>🧱 Building Your Own Semantic View</h3><p>Let’s go hands-on.</p><h3>Step 1: Define Your Business Model</h3><p>Start with your core entities and concepts:</p><pre>| Concept        | Example                                      |<br>| -------------- | -------------------------------------------- |<br>| **Facts**      | Orders, Sales, Payments                      |<br>| **Dimensions** | Product, Customer, Region, Date              |<br>| **Metrics**    | Total Revenue, Average Discount, Order Count |</pre><h3>Step 2: Create a Semantic Model (YAML)</h3><p>The YAML file defines how your semantic view works — think of it as a <strong>blueprint</strong> of your data’s meaning.</p><p>Here’s a simple example:</p><pre># semantic_model.yaml<br>semantic_model: orders_model<br>version: 1<br><br>logical_tables:<br>  orders:<br>    base_relation:<br>      database: MY_DB<br>      schema: SALES_SCHEMA<br>      name: orders<br>    description: &quot;Table of customer orders&quot;<br>    synonyms: [&quot;sales&quot;, &quot;purchases&quot;]<br>    columns:<br>      order_id:<br>        type: integer<br>      order_date:<br>        type: date<br>      customer_id:<br>        type: integer<br>      product_id:<br>        type: integer<br>      amount:<br>        type: numeric<br>        description: &quot;Order amount, in currency units&quot;<br>      discount_pct:<br>        type: numeric<br>        description: &quot;Discount applied to the order&quot;<br>    metrics:<br>      total_amount:<br>        expression: &quot;SUM(amount * (1 - discount_pct))&quot;<br>        description: &quot;Total net revenue&quot;<br>        type: sum<br>    dimensions:<br>      order_date:<br>        column: order_date<br>      product_id:<br>        column: product_id<br><br>  products:<br>    base_relation:<br>      database: MY_DB<br>      schema: SALES_SCHEMA<br>      name: products<br>    description: &quot;Product catalog&quot;<br>    columns:<br>      product_id:<br>        type: integer<br>      product_name:<br>        type: string<br>      category:<br>        type: string<br>    dimensions:<br>      product_name:<br>        column: product_name<br>      category:<br>        column: category<br><br>relationships:<br>  orders_to_products:<br>    from_table: orders<br>    from_column: product_id<br>    to_table: products<br>    to_column: product_id<br><br>sample_queries:<br>  - &quot;What is total revenue per product category this month?&quot;<br>  - &quot;Compare revenue between Europe and Asia last quarter&quot;<br><br>custom_instructions:<br>  sql_generation:<br>    - when_user_says: &quot;revenue&quot;<br>      use_metric: &quot;total_amount&quot;</pre><p>Step 3: Upload and Register the Model</p><pre>CREATE DATABASE semantic_model;<br>CREATE SCHEMA semantic_model.definitions;<br><br>CREATE STAGE semantic_model.public DIRECTORY = (ENABLE = TRUE);<br>GRANT READ ON STAGE semantic_model.public TO ROLE analyst;<br><br>-- Upload the YAML<br>PUT file://path/to/semantic_model.yaml @semantic_model.public;<br><br>-- Create a semantic view object<br>CREATE SEMANTIC VIEW orders_view<br>  USING MODEL @semantic_model.public/semantic_model.yaml;</pre><p>Now, your semantic view is ready — Cortex Analyst can “understand” it.</p><p>Step 4: Query Using Cortex Analyst</p><pre>SELECT CORTEX_ANALYST(<br>  &#39;Show total revenue by product category for Q1&#39;,<br>  &#39;orders_view&#39;<br>);</pre><p>Cortex Analyst automatically translates that natural question into SQL similar to:</p><pre>SELECT<br>  p.category,<br>  SUM(o.amount * (1 - o.discount_pct)) AS total_revenue<br>FROM SALES_SCHEMA.orders o<br>JOIN SALES_SCHEMA.products p<br>  ON o.product_id = p.product_id<br>WHERE QUARTER(o.order_date) = 1<br>GROUP BY p.category;</pre><p>All without you writing a single JOIN or SUM manually. 🤯</p><h3>🔮 Advanced Semantic View Features</h3><p>Once you master the basics, you can unlock the real power of semantic modeling.</p><h3>1. 🧠 Custom Instructions</h3><p>Give Cortex extra “hints” to improve query understanding:</p><pre>custom_instructions:<br>  sql_generation:<br>    - when_user_says: [&quot;profit&quot;, &quot;margin&quot;]<br>      use_metric: &quot;gross_margin&quot;<br>    - when_user_says: [&quot;exclude returns&quot;]<br>      add_filter: &quot;is_returned = FALSE&quot;</pre><p>This lets you fine-tune how language maps to your data logic.</p><h3>2. ✅ Verified Queries</h3><p>Add examples of valid natural-language questions to “train” the model:</p><pre>sample_queries:<br>  - &quot;How many orders were placed last month?&quot;<br>  - &quot;Average order value by region&quot;</pre><p>These help Cortex learn the language of your business.</p><h3>3. 🔤 Synonyms</h3><p>Map alternative names to your tables and columns:</p><pre>logical_tables:<br>  orders:<br>    synonyms: [&quot;sales&quot;, &quot;transactions&quot;]<br>    columns:<br>      amount:<br>        synonyms: [&quot;revenue&quot;, &quot;total&quot;, &quot;sales_amount&quot;]</pre><p>Now, whether a user says “sales” or “orders,” Cortex knows what to do.</p><h3>4. 🎯 Default Filters</h3><p>Avoid messy data by applying global filters automatically:</p><pre>default_filters:<br>  - &quot;is_deleted = FALSE&quot;<br>  - &quot;is_returned = FALSE&quot;</pre><p>This keeps every generated query clean and production-safe.</p><h3>5. 🗓️ Time Hierarchies</h3><p>Define date hierarchies so Cortex can interpret “month”, “quarter”, and “year” naturally:</p><pre>time_dimensions:<br>  order_date:<br>    grain: day<br>    hierarchy: [day, month, quarter, year]</pre><p>Now, “show monthly sales” just works.</p><h3>6. 🔗 Multiple Relationships and Fact Tables</h3><p>You can define multiple relationships and even union multiple base relations to create flexible, cross-domain models.</p><h3>7. 🔒 Security &amp; Access Control</h3><p>Semantic Views are governed by Snowflake’s RBAC — you can grant usage selectively:</p><pre>GRANT USAGE ON SEMANTIC VIEW orders_view TO ROLE analyst;</pre><p>YAML models can also live in private stages, ensuring isolation of sensitive logic.</p><h3>🧪 Full Advanced Example</h3><p>Here’s a full YAML model combining several advanced features:</p><pre>semantic_model: orders_products_model<br>version: 1<br><br>logical_tables:<br>  orders:<br>    base_relation:<br>      database: MY_DB<br>      schema: SALES<br>      name: orders<br>    description: &quot;Customer orders including items and discounts&quot;<br>    synonyms: [&quot;sales&quot;, &quot;transactions&quot;]<br>    columns:<br>      order_id: {type: integer}<br>      order_date: {type: date}<br>      product_id: {type: integer}<br>      amount: {type: numeric, description: &quot;Gross sales&quot;}<br>      discount_pct: {type: numeric}<br>      is_returned: {type: boolean}<br>    metrics:<br>      net_revenue:<br>        expression: &quot;SUM(amount * (1 - discount_pct))&quot;<br>        description: &quot;Revenue after discount&quot;<br>      order_count:<br>        expression: &quot;COUNT(order_id)&quot;<br>        description: &quot;Number of orders&quot;<br>    time_dimensions:<br>      order_date:<br>        grain: day<br>        hierarchy: [day, month, quarter, year]<br><br>  products:<br>    base_relation:<br>      database: MY_DB<br>      schema: SALES<br>      name: products<br>    columns:<br>      product_id: {type: integer}<br>      product_name: {type: string}<br>      category: {type: string}<br><br>relationships:<br>  orders_to_products:<br>    from_table: orders<br>    from_column: product_id<br>    to_table: products<br>    to_column: product_id<br><br>default_filters:<br>  - &quot;is_returned = FALSE&quot;<br><br>custom_instructions:<br>  sql_generation:<br>    - when_user_says: [&quot;revenue&quot;, &quot;income&quot;]<br>      use_metric: &quot;net_revenue&quot;<br>    - when_user_says: [&quot;number of orders&quot;, &quot;count orders&quot;]<br>      use_metric: &quot;order_count&quot;<br><br>sample_queries:<br>  - &quot;Net revenue by product category in 2025&quot;<br>  - &quot;Monthly order count this year&quot;</pre><p>Querying It:</p><pre>SELECT CORTEX_ANALYST(<br>  &#39;Show net revenue by product category for 2025, by month&#39;,<br>  &#39;orders_view&#39;<br>);</pre><p>And Cortex Analyst responds with the perfect SQL — grouping, filtering, and aggregating automatically.</p><h3>🧠 In Practice: Why It Matters</h3><p>Semantic Views turn your warehouse into a <strong>living knowledge base</strong>.</p><pre>| Role               | Benefit                                           |<br>| ------------------ | ------------------------------------------------- |<br>| **Analysts**       | Ask natural questions without writing SQL         |<br>| **Data Engineers** | Centralize business logic in YAML instead of code |<br>| **Executives**     | Get self-service insights                         |<br>| **Developers**     | Build LLM-powered apps that “talk” to data        |</pre><h3>🧭 Conclusion</h3><p><strong>Cortex Analyst + Semantic Views</strong> bridge human language and data logic.<br> They let you <em>speak</em> to Snowflake — and get back not just numbers, but understanding.</p><blockquote><em>SQL told computers </em>what to do.<em><br> </em><strong><em>Cortex Analyst</em></strong><em> teaches them </em>what we mean.</blockquote><p>👏 If this article helped you, leave a <em>Clap</em>, share it with your data team, and follow for the next deep dive — <strong>Cortex Search &amp; AI SQL in action</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e73a215d94b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake Cortex AISQL: Bringing AI-Powered Functions into SQL]]></title>
            <link>https://kotobara.medium.com/snowflake-cortex-aisql-bringing-ai-powered-functions-into-sql-28e65540a027?source=rss-207df8990ff0------2</link>
            <guid isPermaLink="false">https://medium.com/p/28e65540a027</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Kotobara]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 10:16:00 GMT</pubDate>
            <atom:updated>2025-09-30T10:28:01.401Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nt8EGOVcuD14lmERY1q4sg.png" /></figure><p>Snowflake’s <strong>Cortex AISQL</strong> is a new suite of functions that seamlessly infuse AI and large language model (LLM) capabilities into SQL queries. Imagine performing sentiment analysis, language translation, text summarization, embedding generation, or even text generation <strong>directly within Snowflake</strong> — no external APIs or moving data out! These <strong>AI SQL functions</strong> leverage models from OpenAI, Anthropic, and others, all hosted securely in Snowflake’s Data Cloud. In this article, we’ll explore the key Cortex AISQL functions — <strong>SENTIMENT</strong>, <strong>TRANSLATE</strong>, <strong>AI_SUMMARIZE_AGG</strong>, <strong>AI_EMBED</strong>, <strong>AI_SIMILARITY</strong>, and <strong>AI_COMPLETE</strong> — with clear SQL <em>and</em> Python examples for each. We’ll also discuss costs (token-based), limitations (context windows, language support), and security considerations. Let’s dive in! 🤖</p><h3>😊 Sentiment Analysis with AI_SENTIMENT</h3><p><strong>AI_SENTIMENT</strong> detects the overall sentiment of a given text and can even perform aspect-based sentiment analysis. This function returns a JSON object with sentiment scores. By default it gives an <strong>overall</strong> sentiment (positive/negative/neutral), and if you provide specific categories (as an array of aspects), it will return sentiment for each. It currently supports multiple languages, including English, French, German, Hindi, Italian, Spanish, and Portuguese (categories can be in the text language or English).</p><p>For example, let’s analyze a simple customer review in SQL:</p><pre>SELECT AI_SENTIMENT(&#39;The product is outstanding! I loved it.&#39;);<br>-- Returns: { &quot;categories&quot;: [ { &quot;name&quot;: &quot;overall&quot;, &quot;sentiment&quot;: &quot;positive&quot; } ] } :contentReference[oaicite:4]{index=4}</pre><p>The result indicates the overall sentiment is <strong>positive</strong>. We can also specify aspects to get fine-grained sentiment. Suppose we have a table reviews(review_text) and we want to gauge sentiment about specific facets like <em>quality</em> and <em>service</em>:</p><pre>SELECT AI_SENTIMENT(review_text, [&#39;quality&#39;,&#39;service&#39;]) AS sentiment_analysis<br>FROM reviews;</pre><p>Each output will include sentiments per category (e.g. <em>quality</em>: positive, <em>service</em>: negative, etc.) along with the overall sentiment.</p><p><strong>Python Example:</strong> Using Snowflake’s Python API (e.g. Snowpark), you can run the same query. For instance, using Snowpark DataFrame:</p><pre>result_df = session.table(&quot;REVIEWS&quot;).select(<br>    F.call_function(&quot;AI_SENTIMENT&quot;, F.col(&quot;review_text&quot;), F.array_construct(&quot;quality&quot;,&quot;service&quot;))<br>)<br>result_df.show()</pre><p>This would output a JSON-like object for each review’s sentiment analysis, similar to the SQL result. Under the hood, Snowflake adds its own prompt to ensure the model returns structured sentiment, so your input length may translate to more tokens.</p><h3>🌐 Multilingual Translation with AI_TRANSLATE</h3><p>Need to translate text within your database? <strong>AI_TRANSLATE</strong> has you covered. This function translates text from a source language to a target language, supporting a wide range of languages (e.g. en for English, es for Spanish, de for German, etc.). If you don’t know the source language, you can pass an empty string &#39;&#39; to auto-detect it. The result is the translated text string.</p><p><strong>SQL Example:</strong> Let’s translate an English sentence to French:</p><pre>SELECT AI_TRANSLATE(&#39;Snowflake makes data analytics easy and fun!&#39;, &#39;en&#39;, &#39;fr&#39;);<br>-- Result: &quot;Snowflake rend l&#39;analyse des données facile et amusante!&quot; (French translation)</pre><p>You can also translate table data in bulk. For example, translating a review_content column from English to German:</p><pre>SELECT AI_TRANSLATE(review_content, &#39;en&#39;, &#39;de&#39;) <br>FROM reviews <br>LIMIT 10;</pre><p>This will output each English review in German. The function can handle long texts too — even entire paragraphs or transcripts — making it great for localization use cases. It even supports mixed-language inputs (“Spanglish” etc.) by auto-detecting the mix.</p><p><strong>Python Example:</strong> In a Python environment, you could run:</p><pre>translate_df = session.sql(&quot;SELECT AI_TRANSLATE(&#39;Hello, world!&#39;, &#39;en&#39;, &#39;es&#39;);&quot;)<br>print(translate_df.collect()[0][0])<br># Output: &quot;Hola, mundo!&quot;</pre><p>This prints the translated string (English “Hello, world!” to Spanish “Hola, mundo!”). Using Snowpark, you might also integrate translation into pipelines, for example to add a new column with translated text.</p><h3>📝 Text Summarization with AI_SUMMARIZE_AGG</h3><p><strong>AI_SUMMARIZE_AGG</strong> is an <strong>aggregate function</strong> that produces a summary of a collection of texts. It’s extremely useful for condensing long lists of feedback, reviews, or documents into a concise summary. Unlike one-shot summary functions that are limited by an LLM’s context window, AI_SUMMARIZE_AGG can handle <em>datasets larger than a single prompt’s context limit</em> by intelligently aggregating across rows. In other words, you can summarize thousands of rows of text in one go.</p><p>For example, suppose you have a table feedback(comments) with many customer comments. You can get a single summary of all comments like so:</p><pre>SELECT AI_SUMMARIZE_AGG(comments) AS overall_summary <br>FROM feedback;</pre><p>This will return a brief paragraph encapsulating the key points. For instance, summarizing a handful of restaurant review snippets might yield: <em>“The restaurant received mixed reviews. Some customers praised the food (especially the pizza) and found it excellent, while others had a neutral or mediocre experience, citing issues with service.”</em>. The function works on single text or on text combined from multiple columns (you can CONCAT fields before summarizing). You can also use it in groups (e.g., summary per category or product by grouping).</p><p><strong>SQL Example:</strong> Summarize a few sample reviews:</p><pre>WITH reviews AS (<br>  SELECT &#39;Excellent food and cozy ambience.&#39; AS review UNION ALL<br>  SELECT &#39;Great food, but the service was slow.&#39; UNION ALL<br>  SELECT &#39;Mediocre experience overall, nothing special.&#39;<br>)<br>SELECT AI_SUMMARIZE_AGG(review) AS summary FROM reviews;</pre><p>This might return a single summary like: <em>“The reviews highlight excellent food and a cozy ambiance, though there were some complaints about slow service. Overall experiences ranged from outstanding to mediocre.”</em></p><p><strong>Python Example:</strong> Using Snowpark in Python, you could aggregate similarly:</p><pre>from snowflake.snowpark.functions import col, call_function<br>summary_df = session.table(&quot;FEEDBACK&quot;).agg(call_function(&quot;AI_SUMMARIZE_AGG&quot;, col(&quot;comments&quot;)).alias(&quot;summary&quot;))<br>print(summary_df.collect()[0][&quot;SUMMARY&quot;])</pre><p>This would give you the summarized text. It’s a powerful way to quickly get the gist of large text datasets <em>within</em> your database.</p><h3>🔍 Semantic Search with AI_EMBED and AI_SIMILARITY</h3><p>Snowflake now enables <strong>semantic search</strong> and clustering by allowing you to generate and compare <strong>vector embeddings</strong> for text (and images). The duo of <strong>AI_EMBED</strong> and <strong>AI_SIMILARITY</strong> functions makes this possible.</p><h3>AI_EMBED: Turning Text into Vectors</h3><p><strong>AI_EMBED</strong> generates an <strong>embedding vector</strong> from input text or images. In essence, it converts unstructured data into high-dimensional numerical vectors that capture semantic meaning. These vectors can then be stored in Snowflake’s new VECTOR data type and used for similarity search, clustering, or classification. To use AI_EMBED, you must specify which embedding model to use (Snowflake provides several pretrained options like snowflake-arctic-embed models, multilingual models, etc. each yielding vectors of certain dimensions).</p><p><strong>SQL Example:</strong> Create an embedding for a simple phrase:</p><pre>SELECT AI_EMBED(&#39;snowflake-arctic-embed-l-v2.0&#39;, &#39;hello world&#39;);<br>-- Returns a VECTOR value, e.g. [0.123, -0.547, ..., 0.876] (embedding coordinates):contentReference[oaicite:17]{index=17}</pre><p>The above uses Snowflake’s <em>Arctic</em> embedding model to produce a vector. You can imagine storing these for all your documents: e.g.</p><pre>INSERT INTO doc_embeddings(id, vector) SELECT id, AI_EMBED(&#39;model_name&#39;, text) FROM documents;</pre><p>Once vectors are stored, you can index them or use <strong>AI_SIMILARITY</strong> to find close matches.</p><p><strong>Python Example:</strong> Using Snowpark, you might do:</p><pre>df = session.sql(&quot;SELECT AI_EMBED(&#39;snowflake-arctic-embed-l-v2.0&#39;, &#39;Snowflake is cool!&#39;);&quot;)<br>vector = df.collect()[0][0]  # this is a VECTOR (list of floats)</pre><p>Now vector holds the embedding for the given sentence. You could compute distances between such vectors in Python, but Snowflake provides a native way with AI_SIMILARITY.</p><h3>AI_SIMILARITY: Finding Similar Items</h3><p><strong>AI_SIMILARITY</strong> computes a <strong>cosine similarity score</strong> between two inputs — either two text strings or two images (it does <em>not</em> cross-compare between text and image). Essentially, Snowflake will embed both inputs under the hood and return a similarity score between -1 and 1. A score of 1 means identical in meaning, 0 means unrelated, and -1 theoretically means opposite (for text, you’ll usually get between 0 and 1).</p><p><strong>SQL Example (Text):</strong> Let’s compare two phrases for similarity:</p><pre>SELECT AI_SIMILARITY(&#39;I like this dish&#39;, &#39;This dish is very good&#39;) AS similarity;<br>-- Might return ~0.9 (high similarity):contentReference[oaicite:21]{index=21}</pre><p>In practice, the function will return a floating-point number. You can use this in queries — for example, to do semantic searches in your tables. Suppose restaurant_reviews(review) is a table of customer comments, and you want to find which reviews are most similar to the query <em>“I love the food here!”</em>:</p><pre>SELECT review<br>FROM restaurant_reviews<br>ORDER BY AI_SIMILARITY(review, &#39;I love the food here!&#39;) DESC<br>LIMIT 5;</pre><p>This will rank reviews by how similar their content is to the target <br>sentence — effectively a semantic search without any external search engine!</p><p><strong>SQL Example (Images):</strong> You can also compare images stored in stages:</p><pre>SELECT AI_SIMILARITY(<br>    TO_FILE(&#39;@my_images&#39;, &#39;image1.jpg&#39;),<br>    TO_FILE(&#39;@my_images&#39;, &#39;image2.jpg&#39;)<br>);</pre><p>This returns how similar two images are (e.g. detecting if image2 is of the same content as image1).</p><p><strong>Python Example:</strong> In Python, if you have vectors already (from AI_EMBED calls), you could compute similarity manually. But leveraging Snowflake, you might just call:</p><pre>sim_df = session.sql(&quot;SELECT AI_SIMILARITY(&#39;Quick brown fox&#39;, &#39;Fast brown fox&#39;);&quot;)<br>print(sim_df.collect()[0][0])  # prints similarity score</pre><p>This will output a score (e.g. 0.95). For many advanced use-cases, you’d combine these: store embeddings in a table and use AI_SIMILARITY in a JOIN or WHERE to find matches above a threshold (Snowflake even allows constructing a directory of files and filtering images by similarity as shown in the docs).</p><h3>🤖 Text Generation with AI_COMPLETE</h3><p>The <strong>AI_COMPLETE</strong> function is Snowflake’s all-purpose generative AI function. It prompts an LLM to generate a completion (i.e., an answer or continuation) based on your input. Think of it as ChatGPT-style text generation right in SQL. You can use AI_COMPLETE for a variety of tasks: answering questions, drafting text, rewriting or summarizing content, etc. It supports prompts that include text and even images, and can return plain text or even structured outputs like JSON depending on parameters.</p><p>At minimum, you provide a model name and a prompt. Snowflake offers many model choices for AI_COMPLETE — from smaller, faster models to very large, highly capable ones (OpenAI GPT variants, Anthropic Claude, Snowflake’s own models, etc.). The model is specified as the first argument (or via a named parameter). If you omit the optional parameters, the output will be a simple text completion.</p><p><strong>SQL Example:</strong> A basic usage might be:</p><pre>SELECT AI_COMPLETE(&#39;snowflake-arctic&#39;, &#39;What are large language models?&#39;);</pre><p>This will return a text answer explaining large language models (LLMs) using the <strong>Snowflake Arctic</strong> model. We could choose a different model, such as &#39;mistral-large&#39; or &#39;openai-gpt-4.1&#39;, for different balance of speed vs. sophistication. The <strong>AI_COMPLETE</strong> function is recommended for <em>most generative AI tasks</em> in Snowflake.</p><p>We can also use AI_COMPLETE on table data. For instance, suppose we have a table reviews(content) and we want to generate a brief <em>critique</em> for each review. We could do:</p><pre>SELECT AI_COMPLETE(&#39;mistral-large&#39;, <br>    CONCAT(&#39;Critique this review in one sentence: &#39;, content)<br>) AS critique<br>FROM reviews;</pre><p>Each row will contain the model’s generated critique of the review. You can include instructions in your prompt (as shown with “Critique this review…”), use special formatting or tags, etc., to guide the model’s output (prompt engineering).</p><p>Snowflake also allows advanced options with AI_COMPLETE: you can pass a JSON model_parameters object to control generation settings (like temperature, max tokens, etc.), and a response_format to enforce a certain format (for example, ask for a JSON output and have it parsed into a VARIANT). You can even set show_details =&gt; true to get a response that includes usage metrics (token counts, etc.) and other metadata. For brevity, we won’t dive deep into those here, but know that AI_COMPLETE is very flexible.</p><p><strong>Python Example:</strong> Using AI_COMPLETE in Python via Snowpark:</p><pre>query = &quot;&quot;&quot;<br>SELECT AI_COMPLETE(<br>    model =&gt; &#39;openai-gpt-4.1&#39;,<br>    prompt =&gt; &#39;Write a creative ad for a Snowflake t-shirt in one sentence.&#39;<br>) AS result<br>&quot;&quot;&quot;<br>result = session.sql(query).collect()[0][&quot;RESULT&quot;]<br>print(result)<br># e.g. Output: &quot;Wear the storm: a Snowflake t-shirt that makes every data adventure cool and breezy!&quot;</pre><p>This runs the query and prints the generated ad text. In a notebook, you could loop over inputs or use AI_COMPLETE to generate data (like product descriptions) directly in Snowflake tables.</p><p>Snowflake’s integration of AI models means <strong>no data leaves Snowflake when using AI_COMPLETE</strong> — the models run in-platform, preserving security and governance. However, always review generated content, especially if using it in production, as with any generative AI.</p><h3>💰 Costs and Limitations</h3><p>Before you get too excited deploying these at scale, be mindful of <strong>costs and limits</strong>. <strong>Snowflake Cortex AI functions are billed based on the number of tokens processed</strong> (inputs plus outputs). A token is roughly 4 characters of text. Each function has an associated credit cost per million tokens (refer to Snowflake’s pricing documentation).</p><ul><li><strong>Generative functions (AI_COMPLETE, AI_TRANSLATE, AI_SUMMARIZE, etc.) count both input and output tokens</strong> towards billing. For instance, if you prompt a model with 100 tokens and it responds with 300 tokens, you pay for ~400 tokens.</li><li><strong>Embedding and similarity functions count only input tokens</strong>, since they don’t generate large outputs.</li><li>Some functions implicitly add system prompts. For example, AI_SENTIMENT, AI_CLASSIFY, etc., may prepend instructions internally, so the token count might be a bit higher than just your text length.</li><li><strong>Binary data</strong>: For audio, it’s billed at a fixed rate (e.g. 50 tokens per second of audio) and images have an equivalent token size depending on model.</li></ul><p><strong>Performance Tips:</strong> Snowflake recommends using a warehouse no larger than Medium for these functions — bigger warehouses don’t speed up model inference, they just cost more. So you can save money by running AI functions on smaller warehouses (since the heavy lifting is in the model inference, not pure compute).</p><p><strong>Model Limits:</strong> Each model has a maximum <strong>context window</strong> (the total tokens of prompt + response it can handle). Some models Snowflake offers are huge (up to 200k token context for certain Claude models). But if you exceed the limit, you’ll get an error. For example, if a model has a 8,192 token output limit and you feed it near the max input, it won’t be able to generate a long answer. Plan your prompt sizes accordingly, or use functions like AI_SUMMARIZE_AGG that bypass single-prompt limits.</p><p><strong>Quality Considerations:</strong> Output quality and speed depend on the chosen model. Snowflake provides a range from fast, cost-efficient models to very advanced ones. It’s wise to choose a model appropriate to your task complexity to get the best <strong>performance per credit</strong>. For example, a smaller model might be fine for simple classification, but you might choose a GPT-4 level model for complex creative writing — knowing it will cost more. You can also use the account usage views to monitor how many credits your AI queries consume.</p><p><strong>Function Limitations:</strong> At time of writing, these AI functions (being quite new) have a few limitations. They don’t support <strong>dynamic tables</strong> (so you can’t use them in a streaming auto-materializing context). Also, certain staging scenarios for files are not supported (e.g. some encrypted stages for file inputs). Always check Snowflake’s latest docs for any updated limitations or GA status (many of these functions are in Preview <a href="https://quickstarts.snowflake.com/guide/getting-started-with-cortex-aisql/index.html#:~:text=NOTE%3A%20Individual%20functions%20in%20the,can%20be%20used%20in%20production">quickstarts.snowflake.com</a>).</p><h3>🔒 Security and Governance</h3><p>One huge advantage of Snowflake Cortex is that your data remains within Snowflake’s secure environment even when using powerful third-party models. <strong>All the models are hosted by Snowflake</strong>, so the data you send to AI functions <strong>never leaves your Snowflake region</strong>. This helps meet data governance and privacy requirements — you can leverage AI on sensitive data without uploading it to external services.</p><p>That said, governance is still important. Snowflake requires the special role <strong>SNOWFLAKE.CORTEX_USER</strong> to run these AI functions. By default, this role is granted to PUBLIC (meaning any user can call them), but account administrators can <strong>restrict access</strong> by revoking it from PUBLIC and only granting it to specific roles. A best practice is to create a custom role for AI usage, grant it the CORTEX_USER role, and then assign that to permitted users. This way, you have control over who can execute potentially expensive or sensitive AI computations.</p><p>Snowflake also provides an account-level parameter to control model usage. With CORTEX_MODELS_ALLOWLIST, admins can specify which models are allowed (e.g. maybe you only trust Snowflake’s models, or want to exclude a certain third-party model). You could allow all, a select list, or none (to effectively disable AI usage).</p><p><strong>Guardrails:</strong> When generating content, there’s always a risk of unwanted or harmful outputs. Snowflake offers a <strong>guardrails</strong> option for AI_COMPLETE — you can set guardrails: true in the function’s parameters to enable content filtering and safety checks on the model’s output. This can help prevent toxic or policy-violating content from being returned. It’s a good idea to enable this in user-facing applications or when using very general prompts.</p><p>Finally, as with any powerful tool, use these functions responsibly. Monitor usage (Snowflake’s views like CORTEX_FUNCTIONS_USAGE_HISTORY let you audit who is using what models, how often, and the token consumption). Treat AI-generated insights as suggestions – especially if they feed into automated decisions – and maintain human oversight to ensure quality and compliance.</p><h3>🤗 Conclusion and Next Steps</h3><p>Snowflake Cortex AISQL functions are an exciting leap that turn your database into an AI powerhouse. We’ve seen how you can perform sentiment analysis, translate text, summarize large collections of documents, build semantic search, and generate content — all with simple SQL functions and a bit of Snowflake magic. This tight integration means you can prototype and deploy AI-driven features faster, without complex infrastructure.</p><p>The examples we walked through are just the beginning. As Snowflake continues to enhance these capabilities (and more functions graduate from preview to GA), the possibilities for integrating AI into your data workflows are endless. So go ahead — try out an AI query in your Snowflake worksheet or Snowpark notebook. Perhaps use AI_COMPLETE to brainstorm product descriptions, or AI_SIMILARITY to match customer issues to knowledge base articles. The ease of SQL with the power of AI is a compelling combo.</p><p><strong>If you found this article helpful, give it a 👏 clap (or a few) and subscribe for more insights! Thank you for reading, and happy querying with Snowflake Cortex AISQL! 🎊</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28e65540a027" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>