<?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 Dominik Franczyk on Medium]]></title>
        <description><![CDATA[Stories by Dominik Franczyk on Medium]]></description>
        <link>https://medium.com/@franczykdominik?source=rss-3d2a1d8d511d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BDwBsTK28-Gw-go7w2MfSA.jpeg</url>
            <title>Stories by Dominik Franczyk on Medium</title>
            <link>https://medium.com/@franczykdominik?source=rss-3d2a1d8d511d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:44:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@franczykdominik/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[Migrating Real pytest Suites Without Silent Approximation]]></title>
            <link>https://medium.com/@franczykdominik/migrating-real-pytest-suites-without-silent-approximation-323887d0a004?source=rss-3d2a1d8d511d------2</link>
            <guid isPermaLink="false">https://medium.com/p/323887d0a004</guid>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Dominik Franczyk]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 13:01:01 GMT</pubDate>
            <atom:updated>2026-08-04T13:01:01.871Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Testenix now converts simple classes, autouse fixtures, tmp_path, supported monkeypatch operations, and narrowly defined async tests — while refusing semantics it cannot prove.</em></p><p>The first migration demo for almost any test framework converts a plain function with one assert. Real suites use tmp_path, monkeypatch, autouse fixtures, test classes, async markers, helper functions, and configuration that changes execution semantics.</p><p><em>Disclosure: I developed this story with AI assistance, then migrated and executed the included pytest demo and checked every capability and limitation against the current Testenix contract.</em></p><p>The pytest migrator available in Testenix 0.3.0 supports a broader — but still deliberately conservative — subset introduced in version 0.2. It does not mutate the source suite. It builds a new candidate, runs the original baseline, runs the native candidate serially and in parallel, compares mapped outcomes, rechecks source fingerprints, and publishes only after those gates pass.</p><p>Install the released package with the pytest extra:</p><pre>python -m pip install --upgrade &quot;testenix[pytest]==0.3.0&quot;</pre><h3>Start with evidence, not generated files</h3><p>Inspect static support:</p><pre>testenix migrate auto tests --dry-run</pre><p>Then execute the source baseline and native candidates without publishing:</p><pre>testenix migrate auto tests \<br>  --check \<br>  --report-json reports/migration-check.json</pre><p>Only the final mode creates a new native suite:</p><pre>testenix migrate pytest tests \<br>  --output tests_testenix \<br>  --report-json reports/migration.json</pre><p>The output and report paths must be new, inside the project, and disjoint from both source and generated suites. There is no --force option. The original tests are never deleted or renamed.</p><h3>A more realistic supported example</h3><p>This pytest module combines an autouse fixture, native tmp_path, supported monkeypatch, and a simple test class:</p><pre>import os<br>import pytest<br><br>@pytest.fixture(autouse=True)<br>def demo_environment(monkeypatch: pytest.MonkeyPatch) -&gt; None:<br>    monkeypatch.setenv(&quot;TESTENIX_BLOG_DEMO&quot;, &quot;active&quot;)<br><br>def test_tmp_path_is_fresh(tmp_path) -&gt; None:<br>    marker = tmp_path / &quot;marker.txt&quot;<br>    marker.write_text(&quot;isolated\n&quot;, encoding=&quot;utf-8&quot;)<br>    assert marker.read_text(encoding=&quot;utf-8&quot;) == &quot;isolated\n&quot;<br><br>def test_monkeypatch_rolls_back(monkeypatch: pytest.MonkeyPatch) -&gt; None:<br>    monkeypatch.setenv(&quot;TESTENIX_BLOG_VALUE&quot;, &quot;42&quot;)<br>    assert os.environ[&quot;TESTENIX_BLOG_VALUE&quot;] == &quot;42&quot;<br><br>class TestSimpleClass:<br>    def test_autouse_fixture(self) -&gt; None:<br>        assert os.environ[&quot;TESTENIX_BLOG_DEMO&quot;] == &quot;active&quot;</pre><p>Running the current migrator on this file produced a validated native suite with three mapped tests. The source baseline, native serial run, and native parallel run all reported three passes and zero gating outcomes. The final output was published atomically to a new directory; the originals were unchanged.</p><p>The generated module uses a native autouse fixture, keeps the tmp_path and monkeypatch requests, and adds a fresh-instance wrapper for the class method.</p><h3>What tmp_path and monkeypatch mean here</h3><p>Native tmp_path supplies a fresh pathlib.Path and removes its temporary directory at teardown.</p><p>The dependency-free monkeypatch implementation supports:</p><ul><li>setattr in object/attribute form;</li><li>setattr in dotted-import form;</li><li>setenv;</li><li>idempotent undo;</li><li>automatic LIFO rollback during test teardown.</li></ul><p>Supported operations can flow through statically resolved module-local helpers when every propagated use remains inside the known subset. Imported helpers, dynamic rebinding, unsupported methods, and escaped monkeypatch values are blocked.</p><p>This is not a claim of complete pytest MonkeyPatch compatibility. The migrator recognizes and validates a precise contract.</p><h3>The async path is intentionally narrow</h3><p>The converter supports a bare @pytest.mark.asyncio on an async def test. It generates a synchronous wrapper that creates and closes a fresh asyncio.Runner for every test or parameter case, matching the default function-scoped loop isolation it accepts.</p><p>It blocks:</p><ul><li>unmarked async tests;</li><li>async fixtures;</li><li>custom event-loop policies;</li><li>non-function asyncio loop scopes;</li><li>enabled asyncio debug mode;</li><li>semantic markers from anyio or other plugins;</li><li>configured behavior it cannot map to the wrapper contract.</li></ul><p>The effective pytest configuration and relevant PYTEST_ADDOPTS overrides are part of the decision. Seeing the decorator in source is not enough when configuration changes what it means.</p><h3>Simple classes mean simple classes</h3><p>Supported pytest classes receive a fresh zero-argument instance per test method. Ordinary helper methods can remain inside the class.</p><p>The migrator rejects inheritance, class decorators, custom construction, pytest class lifecycle hooks, annotated mutable class state, and defaults whose execution meaning cannot be preserved.</p><p>Again, refusal is safer than generating a class-shaped file whose lifecycle differs from pytest.</p><h3>Fixtures and helpers still have a boundary</h3><p>The supported subset includes local function- or module-scoped fixtures, statically boolean autouse=True, and simple fixtures from an adjacent conftest.py.</p><p>It blocks session-scoped fixtures because pytest creates one per run while Testenix session scope is currently worker-local. It also blocks parametrized fixtures, dynamic autouse configuration, fixture overrides, inherited ancestor conftest.py behavior, usefixtures, and built-in fixtures such as capsys, caplog, and request.</p><p>Some runtime helpers — approx, deprecated_call, fail, raises, and warns—can remain in generated modules, but those modules still require pytest at runtime.</p><h3>“Converted” is not the same as “published”</h3><p>Large unsupported suites receive grouped console diagnostics instead of a wall of repeated messages. The JSON report retains every source- and line-addressed diagnostic.</p><p>A dry run can build safe in-memory mappings and label them a statically convertible subset. Only a report with status: published and published: true means the requested output directory exists.</p><p>Before publication, Testenix requires:</p><ol><li>a green source baseline;</li><li>equal source and native inventory;</li><li>equal aggregate outcomes;</li><li>equal mapped per-test outcomes;</li><li>an equal native serial result;</li><li>an equal native parallel result;</li><li>unchanged source fingerprints;</li><li>a successful atomic create-only rename.</li></ol><p>Filesystem changes inside the project are isolated by disposable copies during validation. Network, database, cloud, absolute-path, and other external effects are not sandboxed. Use test credentials and a side-effect-safe selection.</p><h3>A rollout that remains reversible</h3><p>Start with one supported, side-effect-free directory. Run --dry-run, inspect every diagnostic, then run --check. Publish into a new path and add the native suite as a non-gating CI job beside the unchanged pytest job.</p><p>Compare inventory, outcomes, fixture behavior, and runtime over real changes. Expand only after the evidence remains stable.</p><p>For modules that need the full pytest ecosystem, keep using:</p><pre>testenix pytest -q --tb=short tests</pre><p>That command delegates to the real pytest installation. It preserves pytest semantics and output, but it does not use the native Testenix scheduler, workers, retries, history, or result model.</p><p>Read the <a href="https://polishdataengineer.github.io/testenix/guides/migration/">safe migration guide</a> and <a href="https://polishdataengineer.github.io/testenix/guides/pytest-compatibility/">pytest compatibility matrix</a> before evaluating a production suite.</p><figure><img alt="A pytest-to-Testenix migration path highlights supported fixtures, monkeypatch operations, async tests, and explicit refusal boundaries." src="https://cdn-images-1.medium.com/max/1024/1*qSjTVZnDHile8rZAwtZuLg.png" /></figure><figure><img alt="Animated terminal shows Testenix converting supported pytest patterns while reporting unsupported semantics instead of silently approximating them." src="https://cdn-images-1.medium.com/max/1024/1*FaYq4lwqcV3lmR7JjlkncQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=323887d0a004" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Skip a Duplicate Test Collection Import Without Trusting Stale State]]></title>
            <link>https://medium.com/@franczykdominik/skip-a-duplicate-test-collection-import-without-trusting-stale-state-01a8c8dba3c8?source=rss-3d2a1d8d511d------2</link>
            <guid isPermaLink="false">https://medium.com/p/01a8c8dba3c8</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Dominik Franczyk]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 13:01:02 GMT</pubDate>
            <atom:updated>2026-07-30T13:01:02.512Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Testenix collection manifests remove one import from unchanged runs only after exact roots, inventory, dependencies, and SHA-256 fingerprints verify.</em></p><p>Many Python test runs import a selected module twice: once to discover tests and again inside the worker that executes them. For import-heavy applications, the first import can be meaningful wall time. Removing it is attractive. Trusting yesterday’s collected test list is not.</p><p><em>Disclosure: I developed this story with AI assistance, then generated and consumed a real Testenix manifest and verified the trust boundary against the 0.3.0 source and documentation.</em></p><p>Testenix 0.3.0 introduces an explicit collection artifact:</p><pre>testenix manifest tests --output .testenix/collection.json<br>testenix run tests --manifest .testenix/collection.json</pre><p>The second command can bypass the collection-side import when the selected source state still matches exactly. Execution workers continue to import the code they execute. This optimization removes one import, not Python’s runtime import model.</p><h3>Why a test list is not enough</h3><p>Suppose a cache records these node IDs:</p><pre>tests/test_accounts.py::test_create_account<br>tests/test_accounts.py::test_delete_account</pre><p>That list becomes unsafe as soon as someone:</p><ul><li>adds or deletes a test file;</li><li>changes a decorator, fixture, parametrization, or skip condition;</li><li>edits a project-local dependency imported during collection;</li><li>changes the selected root;</li><li>relies on environment data that alters collection.</li></ul><p>Executing an old list can silently omit new tests. A fast run with incomplete inventory is not a performance win.</p><p>Testenix therefore treats its manifest as a versioned, trusted input whose current source boundary must be proven before reuse.</p><h3>What the manifest records</h3><p>The generated JSON contains:</p><ul><li>exact collection roots;</li><li>every selected test file;</li><li>statically discoverable project-local Python import dependencies;</li><li>SHA-256 source digests;</li><li>collected test metadata;</li><li>collection issues;</li><li>module-sharding decisions.</li></ul><p>Parameter names are retained, but parameter values are redacted. Collection-time case data can come from credentials, environment variables, or other sensitive inputs. Persisting those values inside an optimization artifact would expand the secret boundary for little benefit.</p><p>The output path must be new. The command does not overwrite an existing manifest:</p><pre>testenix manifest tests --output .testenix/collection-2026-07-21.json</pre><p>This create-only behavior makes replacement a deliberate producer action rather than a side effect of every test run.</p><h3>Verification happens before trust</h3><p>When testenix run receives a valid manifest, it compares:</p><ol><li>the requested roots;</li><li>the exact current test-file inventory;</li><li>every recorded source digest;</li><li>the manifest’s internal schema and invariants.</li></ol><p>If a file was added, removed, changed, unreadable, or no longer matches its fingerprint, the manifest is stale. Testenix falls back to normal supervised collection. It does not execute the stale inventory.</p><p>Malformed JSON is different from a stale but structurally valid manifest. Malformed input is rejected as a command/configuration error rather than treated as a trustworthy optimization.</p><p>In the included demo, Testenix writes the manifest, verifies it against four tests in one module, and runs the unchanged suite successfully.</p><h3>The boundary is source-aware, not world-aware</h3><p>Source fingerprints do not capture every input that can influence collection. A test module may read:</p><ul><li>environment variables;</li><li>generated files outside the selected roots;</li><li>a feature-flag service;</li><li>database state;</li><li>installed package metadata;</li><li>network responses;</li><li>the current date or machine configuration.</li></ul><p>If one of those inputs changes collected tests without changing fingerprinted Python sources, the manifest producer must regenerate the artifact. Testenix cannot infer an external dependency that the source boundary does not describe.</p><p>This is why the feature is called a trusted manifest rather than an automatic cache. The project owner chooses when that trust boundary is appropriate.</p><h3>Configure only after the producer is clear</h3><p>For a stable CI job, configuration can reference the artifact:</p><pre>[tool.testenix]<br>paths = [&quot;tests&quot;]<br>manifest = &quot;.testenix/collection.json&quot;<br>workers = &quot;auto&quot;</pre><p>The operational question is then: who regenerates the manifest, and when?</p><p>A reasonable workflow is:</p><ol><li>Build or restore the exact source checkout.</li><li>Generate a new manifest as an explicit build artifact.</li><li>Run the suite with that manifest in the same source state.</li><li>Regenerate whenever collection-affecting external inputs change.</li><li>Keep normal supervised collection as the safe fallback.</li></ol><p>Do not copy a manifest across branches merely because the filename is the same.</p><h3>Measure the same profile you intend to keep</h3><p>Collection strategy affects wall-clock time, so worker tuning must include it:</p><pre>testenix tune tests --manifest .testenix/collection.json</pre><p>If --write is requested, Testenix refuses to persist only a worker count when the transient manifest setting differs from the loaded project configuration. A recommendation measured with one collection import is not automatically valid for the two-import profile.</p><p>The tuner fingerprints the trusted manifest alongside project sources and rejects drift observed during measurement.</p><h3>When a manifest is likely to help</h3><p>Evaluate it when:</p><ul><li>imports are a visible portion of test time;</li><li>the suite’s selected source inventory is stable during a run;</li><li>project-local dependencies are statically discoverable;</li><li>the manifest can be regenerated in a controlled build step;</li><li>collection does not depend heavily on untracked external state.</li></ul><p>It will not matter much when tests dominate runtime, imports are cheap, or the artifact-management cost exceeds the removed collection work.</p><p>Most importantly, do not quote a faster manifest run without saying that it used a verified single-import collection profile. Performance evidence is only useful when another engineer knows which work was removed.</p><p>Install Testenix 0.3.0 with:</p><pre>python -m pip install --upgrade testenix==0.3.0</pre><p>Then read the <a href="https://polishdataengineer.github.io/testenix/guides/parallelism/">parallelism guide</a> and generate a manifest for a non-critical, source-stable suite before configuring it globally.</p><figure><img alt="A Testenix collection manifest verifies exact roots, test inventory, dependencies, and SHA-256 fingerprints before trust." src="https://cdn-images-1.medium.com/max/1024/1*AzJ0Op98Iobs_SRekvsTRA.png" /></figure><figure><img alt="Animated Testenix terminal creates and verifies a trusted Python test collection manifest before reusing the collected inventory." src="https://cdn-images-1.medium.com/max/1024/1*gdMDeEM3MSZvpTpFDtnVGA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01a8c8dba3c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When One Python Test Module Blocks Parallelism]]></title>
            <link>https://medium.com/@franczykdominik/when-one-python-test-module-blocks-parallelism-aeaff4a30732?source=rss-3d2a1d8d511d------2</link>
            <guid isPermaLink="false">https://medium.com/p/aeaff4a30732</guid>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Dominik Franczyk]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 13:01:06 GMT</pubDate>
            <atom:updated>2026-07-28T13:01:06.570Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Testenix can split eligible modules across workers, but only as an explicit trust decision guarded by conservative static checks.</em></p><p>Four workers do not guarantee four-way parallelism. If a runner treats one test module as one affinity unit, a file containing hundreds of tests can still occupy one worker while the other processes wait.</p><p><em>Disclosure: I developed this story with AI assistance, then ran the examples and verified the sharding contract against the Testenix 0.3.0 source, tests, and documentation.</em></p><p>Testenix keeps module affinity as its safe default. Tests from one normal module execute inside the same persistent worker, preserving module-fixture reuse and avoiding accidental copies of visible module state. Version 0.3.0 adds an opt-in escape hatch for modules whose tests are known to be independent:</p><pre>testenix run tests --shard-modules</pre><p>The interesting feature is not that Testenix can split a file. It is that it refuses to split many files.</p><h3>Why module affinity exists</h3><p>Python modules can carry lifecycle and state that is not visible in a test signature:</p><pre>client = build_shared_client()<br>cache: dict[str, object] = {}<br><br>def test_first() -&gt; None:<br>    cache[&quot;ready&quot;] = True<br><br>def test_second() -&gt; None:<br>    assert cache[&quot;ready&quot;] is True</pre><p>Splitting those tests into different processes changes their meaning. The same risk exists with module- or session-scoped fixtures, mutable class state, import-time registration, decorators that execute code, and function defaults built eagerly at import.</p><p>Keeping one module in one worker is conservative, but coherent. The downside is visible when the suite has one dominant file and many small files. The scheduler cannot invent independence that the execution model does not expose.</p><h3>What opt-in sharding changes</h3><p>Consider four independent tests in one file:</p><pre>import time<br><br>def test_alpha() -&gt; None:<br>    time.sleep(0.05)<br><br>def test_beta() -&gt; None:<br>    time.sleep(0.05)<br><br>def test_gamma() -&gt; None:<br>    time.sleep(0.05)<br><br>def test_delta() -&gt; None:<br>    time.sleep(0.05)</pre><p>Run with four requested workers and default affinity:</p><pre>testenix run tests/test_independent.py --workers 4 -vv --no-history</pre><p>The real demo reports one effective worker because the module is one execution unit. Add the explicit sharding decision:</p><pre>testenix run tests/test_independent.py \<br>  --workers 4 \<br>  --shard-modules \<br>  -vv \<br>  --no-history</pre><p>The same file exposes four units, and the verbose report records four distinct workers.</p><p>In this tiny example, process startup dominates enough that wall-clock timings are not useful performance evidence. The point is structural: default affinity exposed one schedulable unit; approved sharding exposed four.</p><h3>The static analysis fails closed</h3><p>Before splitting a module, Testenix scans for visible hazards. It retains module affinity when it finds:</p><ul><li>module- or session-scoped fixtures;</li><li>imported fixture providers;</li><li>direct writes to module globals;</li><li>nested mutable containers;</li><li>mutable class state;</li><li>eager calls in module assignments or annotations;</li><li>executable decorators;</li><li>calls in function defaults;</li><li>lifecycle behavior in class bases, keywords, or construction expressions.</li></ul><p>Function-scoped fixtures defined in the collected module, including autouse fixtures, may be recreated per test and do not block sharding by themselves.</p><p>The “fail closed” rule matters. A suspicious module does not abort the whole run; it keeps its normal affinity while eligible modules can still become finer units.</p><h3>Static safety is not runtime proof</h3><p>No Python AST analysis can prove that an arbitrary function call is free of shared effects. Independent-looking tests may still communicate through:</p><ul><li>an imported library with process-external state;</li><li>environment variables;</li><li>a shared database or message broker;</li><li>filesystem paths outside per-test temporary directories;</li><li>network services;</li><li>order-dependent data created by another test.</li></ul><p>--shard-modules is therefore an explicit project trust decision, not an automatic optimizer.</p><p>Validate both profiles before adopting it:</p><pre>testenix run tests --workers 1<br>testenix run tests --workers 4<br>testenix run tests --workers 4 --shard-modules</pre><p>Compare test inventory, outcomes, flaky behavior, external side effects, and fixture ownership. Then measure the intended profile:</p><pre>testenix tune tests --shard-modules</pre><p>If sharding is the profile CI will keep, configure it before using testenix tune --write:</p><pre>[tool.testenix]<br>shard_modules = true<br>workers = &quot;auto&quot;</pre><p>The tuner refuses to persist a workers-only recommendation when a transient sharding override differs from the loaded configuration. A worker count measured for sharded units is not automatically valid for module affinity.</p><h3>Sharding does not change fixture scope definitions</h3><p>Without sharding, a module-scoped fixture can serve all normal tests in the module inside one worker. That fixture is one reason Testenix keeps the module intact.</p><p>Timed tests already use isolated processes and cannot share module/session fixture instances with neighboring tests. Session scope remains worker-local rather than globally singleton across the run. Sharding does not turn either scope into a coordinator-owned resource.</p><p>If a module genuinely depends on shared module lifecycle, retain affinity. Reorganizing independent tests into several files may be clearer than overriding the execution model.</p><h3>When sharding is worth evaluating</h3><p>Good candidates have:</p><ul><li>one or several dominant modules;</li><li>function-scoped or no fixtures;</li><li>isolated test data;</li><li>no meaningful import-time lifecycle;</li><li>test bodies long enough to amortize extra process work;</li><li>a CI environment where additional workers have real CPU and memory capacity.</li></ul><p>Poor candidates have hidden shared state, expensive per-process setup, globally constrained external services, or only a few milliseconds of total work.</p><p>The right question is not “Can this file be split?” It is “Can this file be split without changing what the suite proves?”</p><p>Install the released alpha with:</p><pre>python -m pip install --upgrade testenix==0.3.0</pre><p>Then inspect the <a href="https://polishdataengineer.github.io/testenix/guides/parallelism/">parallelism guide</a> and test sharding on a non-gating CI job before changing the default profile.</p><figure><img alt="Testenix preserves Python test module affinity by default and enables conservative intra-module sharding only with explicit opt-in." src="https://cdn-images-1.medium.com/max/1024/1*YjcVsJToXuDKcOSaf8gcpA.png" /></figure><figure><img alt="Animated Testenix terminal shows one large Python test module being split into safe intra-module shards across workers." src="https://cdn-images-1.medium.com/max/1024/1*sDlBOvzRpXAW0z_rK1mGuQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aeaff4a30732" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Guessing Your Python Test Worker Count]]></title>
            <link>https://medium.com/@franczykdominik/stop-guessing-your-python-test-worker-count-f4d7cfc9c14b?source=rss-3d2a1d8d511d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4d7cfc9c14b</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Dominik Franczyk]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 13:01:03 GMT</pubDate>
            <atom:updated>2026-07-23T13:01:03.829Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Testenix 0.3.0 measures fresh processes, validates outcomes, and recommends the smallest worker count close to the best median.</em></p><p>“Use every CPU” sounds like an obvious parallel-testing strategy. It stops being obvious when a suite has three schedulable modules, each process has a measurable startup cost, and most tests finish before the extra workers have paid for themselves.</p><p><em>Disclosure: I developed this story with AI assistance, then verified every product claim against the Testenix 0.3.0 release, source, tests, and current documentation.</em></p><p><a href="https://github.com/polishdataengineer/testenix/releases/tag/v0.3.0">Testenix 0.3.0</a> changes the meaning of workers = &quot;auto&quot;. It is no longer shorthand for the logical CPU count. It is an adaptive decision based on the work the runner can actually schedule, the available machine capacity, duration-history coverage, predicted process-start cost, and makespan.</p><p>When a fixed CI limit is required, Testenix also provides a slower, measured path:</p><pre>testenix tune tests --warmups 1 --repeats 5</pre><p>The testenix benchmark command is an exact alias. The important result is not a new public speed ratio. It is a worker recommendation for this project, suite shape, execution profile, and machine.</p><h3>Why CPU count is the wrong first question</h3><p>A test runner cannot schedule more independent work than the suite exposes. In Testenix, normal modules are affinity units. Isolated timeout tests and eligible opt-in module shards can add more units, but a file containing 3,000 ordinary tests is still one unit by default.</p><p>That gives worker selection two separate ceilings:</p><pre>useful workers &lt;= independently schedulable units<br>useful workers &lt;= process-visible CPU capacity</pre><p>Neither ceiling says where the best runtime lies. A short suite may run fastest with one worker because process startup dominates. A longer, uneven suite may benefit from several. A fixed worker count also interacts with history, sharding, collection manifests, imports, fixtures, and the resource limits imposed by CI.</p><p>The correct number is therefore a measurement result — not a property of the laptop model.</p><h3>What adaptive auto does</h3><p>workers = &quot;auto&quot; makes a quick runtime decision after test selection. It first counts the units it can schedule and caps the choice by those units and available CPUs.</p><p>When duration history covers enough of the suite, Testenix uses a startup-cost and predicted-makespan model. It chooses the smallest worker count within a narrow tolerance of the predicted best. Without reliable history, a cold run uses a conservative cap instead of launching a process for every logical CPU.</p><p>Configure it with:</p><pre>[tool.testenix]<br>workers = &quot;auto&quot;<br>paths = [&quot;tests&quot;]</pre><p>auto never edits configuration. It decides for the current run.</p><h3>What testenix tune measures</h3><p>The tuner is deliberately more expensive and more skeptical. It runs complete suites in fresh CLI processes:</p><pre>testenix tune tests \<br>  --candidates 1,2,4,8 \<br>  --warmups 1 \<br>  --repeats 5 \<br>  --json reports/tuning.json</pre><p>Before comparing candidates, a green one-worker probe establishes the exact inventory and outcome signature. Every candidate must match it. A worker count that changes collected tests or outcomes is not a faster candidate; it is rejected evidence.</p><p>History is disabled for timing samples so a previous run does not make one candidate incomparable with another. Candidate order alternates between rounds instead of always giving the same setting the warmest machine state. The recommendation is the smallest worker count within a narrow tolerance of the best median, avoiding a larger setting for measurement noise.</p><p>The automatic sweep stays within resource-aware candidates of 1, 2, and 4 workers. Counts above four must be explicitly requested.</p><p>That small example is a useful warning: asking for candidates 1,2 does not create parallel work. The suite exposed one module-affinity unit, so the tuner measured one effective candidate and recommended one worker.</p><h3>Measurement must stop when the project changes</h3><p>A long tuning run is vulnerable to a subtle failure: a developer edits the project while samples are being collected, then the tool compares timings from different source states.</p><p>Testenix fingerprints project Python and TOML sources, explicit suite files, linked source directories, and the trusted collection manifest before the probe. It rechecks content and file identity after every sample. If those inputs drift, the tuning result is discarded.</p><p>Installed packages, non-source data, environment state, remote services, and other runtime inputs remain outside that fingerprint boundary. Use an immutable checkout for measurements intended to drive shared CI configuration.</p><p>Every complete suite run also receives a 300-second deadline by default:</p><pre>testenix tune tests --run-timeout 120</pre><p>Timeout cleanup uses Windows Job Objects or a POSIX root session plus identity-tracked descendants. The documentation retains one narrow POSIX caveat: a child that creates a new session and exits between process creation and the first OS snapshot cannot receive an absolute kernel-containment guarantee. Hostile suites belong in a container.</p><h3>Configuration changes require an explicit verb</h3><p>Normal tuning only reports. To persist the measured integer:</p><pre>testenix tune --write</pre><p>That is the only tuning mode that changes pyproject.toml. The writer rechecks the original file bytes immediately before an atomic replacement and refuses to write if configuration changed during measurement.</p><p>It also refuses a misleading partial update. If the measurement used a transient --shard-modules, --no-shard-modules, or --manifest profile that differs from the loaded project configuration, Testenix will not write only the workers value. Configure the intended execution profile first, then tune it.</p><h3>Why this is not a benchmark headline</h3><p>Testenix retains a historical result in which version 0.1.0 completed a generated 100,000-test workload faster than pytest and pytest-xdist on one M4 Pro machine. That evidence used four workers, disabled history, 16 modules, one warm-up, and five measured rounds.</p><p>It is not a Testenix 0.3.0 measurement. No clean 0.3.0 scaling matrix was published with the release, and the project does not claim a universal current-version speedup.</p><p>The tuner can optionally measure a corresponding pytest source path:</p><pre>testenix tune tests_testenix --pytest-source tests</pre><p>That ratio is orientation for the exact local source/native pair. Publishing a comparative claim requires the fuller benchmark contract, provenance, repeated samples, and a workload another person can interpret.</p><h3>A safer evaluation sequence</h3><ol><li>Install and pin the released alpha with python -m pip install --upgrade testenix==0.3.0.</li><li>Keep workers = &quot;auto&quot; for an adaptive baseline.</li><li>Run testenix tune without --write in an unchanged checkout.</li><li>Inspect the inventory, execution-unit count, samples, and recommended worker count.</li><li>Persist only after the execution profile matches the one CI will use.</li><li>Re-measure when module layout, fixtures, hardware, or CI resource limits materially change.</li></ol><p>The useful outcome is not “more workers.” It is knowing why this suite should use this worker count.</p><p>Read the <a href="https://polishdataengineer.github.io/testenix/guides/parallelism/">parallelism guide</a>, the <a href="https://polishdataengineer.github.io/testenix/reference/cli/">CLI reference</a>, or install <a href="https://pypi.org/project/testenix/0.3.0/">Testenix 0.3.0 from PyPI</a>.</p><figure><img alt="Testenix evaluates one, two, and four Python test workers before recommending a project-local worker count." src="https://cdn-images-1.medium.com/max/1024/1*hq9nHeI6T8imTf-VUXK9eQ.png" /></figure><figure><img alt="Animated Testenix terminal compares Python test worker candidates and recommends one worker for a single schedulable module." src="https://cdn-images-1.medium.com/max/1024/1*CM_dMIbFeezim_fOfplZMA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4d7cfc9c14b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The cognitive cost of non-determinism: Why AI engineering burns out differently]]></title>
            <link>https://medium.com/@franczykdominik/the-cognitive-cost-of-non-determinism-why-ai-engineering-burns-out-differently-e658bff41ac8?source=rss-3d2a1d8d511d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e658bff41ac8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mental-health]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[leadership]]></category>
            <dc:creator><![CDATA[Dominik Franczyk]]></dc:creator>
            <pubDate>Sat, 17 Jan 2026 14:22:26 GMT</pubDate>
            <atom:updated>2026-01-17T14:22:26.280Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ecYPhoI2PYx-H4Csc9sQUA.png" /><figcaption>Entropy vs. Order</figcaption></figure><p>There is a distinct texture to the fatigue experienced by machine learning engineers that differs from the exhaustion found in traditional software development. While a backend engineer battling race conditions in a distributed system faces immense cognitive load, the feedback loop is generally explicit: the test fails, the stack trace points to a line number, and the logic is corrected.</p><p>For the AI engineer, the feedback loop is often opaque, delayed, and probabilistic. This article examines the psychological impact of this workflow, grounding the analysis in the concept of “Hidden Technical Debt” (as defined by Sculley et al. in their seminal NeurIPS 2015 paper) and the operational reality of stochastic systems. We explore how the specific nature of ML work — fighting entropy rather than logic — affects the individual engineer’s sense of agency.</p><h4>The psychological weight of CACE (Changing Anything Changes Everything)</h4><p>In traditional software engineering, encapsulation allows developers to reason about modules in isolation. If you change a function in the billing module, it rarely breaks the rendering logic in the frontend.</p><p>In machine learning, this isolation does not exist. Sculley et al. describe this as the <strong>CACE principle</strong>: Changing Anything Changes Everything. A slight shift in the input data distribution (drift) or a minor tweak to a hyperparameter can degrade the entire system’s performance.</p><p>For the individual engineer, this creates a state of <strong>hyper-vigilance</strong>. You cannot “trust” the code in the same way a Java developer trusts a compiled class. The engineer at the keyboard is not just building a structure; they are actively maintaining a precarious equilibrium. This constant state of alert — waiting for the model to collapse due to a silent upstream data change — is a known driver of chronic cortisol elevation, distinct from the episodic stress of a “crunch time” release.</p><h4>The dopamine gap in long-training loops</h4><p>Human motivation relies heavily on feedback loops. In standard development (TDD), the cycle is tight: write test -&gt; fail -&gt; write code -&gt; pass. This provides frequent micro-doses of dopamine (satisfaction/completion).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KAHR4HSSh1oGnu4kn05XQw.png" /><figcaption>The Broken Feedback Loop</figcaption></figure><p>In Deep Learning, this loop is broken. An engineer might launch a training run that takes 72 hours. During this interval, they exist in a state of suspended agency.</p><ul><li><strong>The Experience:</strong> You are effectively “working” by monitoring a TensorBoard loss curve, but you are not <em>acting</em>.</li><li><strong>The Outcome:</strong> If the run fails after three days due to a NaN (Not a Number) error or poor convergence, the psychological toll is heavy. There is no “quick fix.” The effort-to-reward ratio is skewed. This creates a psychological pattern similar to <strong>intermittent reinforcement</strong> — a powerful but exhausting schedule where rewards (successful models) are unpredictable, leading to obsessive checking behaviors and rapid burnout.</li></ul><h4>The “Daily Stand-up” anxiety</h4><p>The Agile ritual of the “daily stand-up” was designed for deterministic tasks (“I built the login form”). For an ML engineer, this meeting often induces a specific type of shame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pbA7G5JYPVIZgOMLPxNLQ.png" /><figcaption>Reality vs. Agile</figcaption></figure><p>When a researcher spends three days testing hypotheses that all fail (a scientifically valid process), their update is: “I tried X, Y, and Z, and none worked.” To a Product Manager or a classic Software Engineer, this sounds like three days of zero productivity.</p><ul><li><strong>The Conflict:</strong> The engineer feels pressure to “cherry-pick” results or overstate minor improvements to justify their salary.</li><li><strong>The Result:</strong> This leads to a disconnect between the engineer’s internal reality (rigorous scientific invalidation of hypotheses) and the external perception (stagnation). Over time, this lack of validation for “negative results” erodes professional self-esteem.</li></ul><h4>Cognitive overload from the arXiv flood</h4><p>While all tech sectors move fast, the velocity in AI is unique due to its academic roots. We are not just seeing new libraries (tools), but new fundamental theories (physics) every week.</p><p>A backend developer doesn’t need to read the latest whitepaper on database theory to build a CRUD app. An AI engineer often <em>must</em> read the latest paper on attention mechanisms to remain employable.</p><ul><li><strong>The Reality:</strong> It is not just about “staying outdated.” It is the distinct fear that the solution to your current agonizing problem was published 4 hours ago, and you are wasting company resources by not knowing it. This creates a “fear of missing out” (FOMO) that is not social, but professional and existential.</li></ul><h4>Path forward: Acknowledging the difference</h4><p>We cannot solve these issues with generic “wellness” programs. The solution requires acknowledging that AI engineering is a hybrid discipline — part software engineering, part experimental science.</p><ul><li><strong>Operational Safety:</strong> Teams need to treat “negative results” (knowing what <em>doesn’t</em> work) as a deliverable asset, recorded and celebrated, to restore the dopamine loop.</li><li><strong>Process Adjustment:</strong> We must move away from velocity-based metrics for research tasks. You cannot estimate story points for an epiphany.</li></ul><p>The goal is not to lower standards, but to align our expectations with the stochastic reality of the work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e658bff41ac8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combining DataFrames with Pandas: Understanding pd.merge and df.join]]></title>
            <link>https://medium.com/@franczykdominik/combining-dataframes-with-pandas-understanding-pd-merge-and-df-join-df039c73a9a1?source=rss-3d2a1d8d511d------2</link>
            <guid isPermaLink="false">https://medium.com/p/df039c73a9a1</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[dataframes]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Dominik Franczyk]]></dc:creator>
            <pubDate>Sun, 30 Apr 2023 20:34:46 GMT</pubDate>
            <atom:updated>2023-04-30T20:34:46.641Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*f04tdfdFembTH31WKTIrew.png" /></figure><p>Pandas is an essential Python library for data manipulation and analysis. It provides powerful and flexible data structures such as DataFrames, which are designed to make working with structured data both easy and intuitive. In this article, we will discuss two important methods for combining DataFrames in Pandas: pd.merge() and df.join(). We will explore their use cases, syntax, and common options, as well as provide examples to demonstrate their practical applications.</p><h4>1. Overview of pd.merge() and df.join():</h4><p>Pandas offers several ways to combine DataFrames, with pd.merge() and df.join() being the most widely used. These methods merge DataFrames based on common columns or indexes. The main difference between them lies in their default behavior and flexibility:</p><ul><li>pd.merge(): This function is more flexible and powerful, allowing you to merge DataFrames using different types of joins (inner, outer, left, and right) based on one or more common columns. By default, pd.merge() performs an inner join.</li><li>df.join(): This method is a convenient way to combine DataFrames based on their index. It is less flexible than pd.merge() and, by default, performs a left join.</li></ul><h4>2. Merging DataFrames with pd.merge():</h4><p>The syntax for the pd.merge() function is as follows:</p><pre>pd.merge(left, right, on, how, suffixes)</pre><ul><li>left: The left DataFrame to be joined.</li><li>right: The right DataFrame to be joined.</li><li>on: The column(s) to join the DataFrames on. The column(s) should be present in the right DataFrame.</li><li>how: The type of join to perform (&#39;inner&#39;, &#39;outer&#39;, &#39;left&#39;, or &#39;right&#39;). Default is &#39;left&#39;.</li><li>suffixes: A tuple of strings to append to overlapping column names in the left and right DataFrames to make them unique.</li></ul><p>Example:</p><pre>import pandas as pd<br><br>df1 = pd.DataFrame({&#39;key&#39;: [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;], &#39;value&#39;: [1, 2, 3, 4]})<br>df2 = pd.DataFrame({&#39;key&#39;: [&#39;B&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;], &#39;value&#39;: [5, 6, 7, 8]})<br><br>merged_df = pd.merge(df1, df2, on=&#39;key&#39;, how=&#39;inner&#39;, suffixes=(&#39;_left&#39;, &#39;_right&#39;))<br>print(merged_df)</pre><h4>3. Joining DataFrames with df.join():</h4><p>The syntax for the pd.join() function is as follows:</p><pre>left.join(right, on, how, lsuffix, rsuffix)</pre><ul><li>left: The left DataFrame to be joined.</li><li>right: The right DataFrame to be joined.</li><li>on: The column(s) to join the DataFrames on. The column(s) should be present in the right DataFrame.</li><li>how: The type of join to perform (&#39;inner&#39;, &#39;outer&#39;, &#39;left&#39;, or &#39;right&#39;). Default is &#39;left&#39;.</li><li>lsuffix: A string to append to overlapping column names in the left DataFrame to make them unique.</li><li>rsuffix: A string to append to overlapping column names in the right DataFrame to make them unique.</li></ul><p>Example:</p><pre>import pandas as pd<br><br>df1 = pd.DataFrame({&#39;A&#39;: [1, 2, 3], &#39;B&#39;: [4, 5, 6]}, index=[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;])<br>df2 = pd.DataFrame({&#39;C&#39;: [7, 8, 9], &#39;D&#39;: [10, 11, 12]}, index=[&#39;b&#39;, &#39;c&#39;, &#39;d&#39;])<br><br>joined_df = df1.join(df2, how=&#39;left&#39;, lsuffix=&#39;_left&#39;, rsuffix=&#39;_right&#39;)<br>print(joined_df)</pre><h4>4. Choosing between pd.merge() and df.join():</h4><p>When deciding between pd.merge() and df.join(), consider the following:</p><ul><li>If you need to merge DataFrames based on a specific column, or if you require more flexibility in the type of join, use pd.merge().</li><li>If you need to merge DataFrames based on their index, and a left join is suitable for your use case, then df.join() is a convenient option.</li></ul><h4>5. Conclusion:</h4><p>In this article, we have explored the two main methods for merging and joining DataFrames in Pandas: pd.merge() and df.join(). Understanding these functions and their differences is essential for efficient data manipulation and analysis in Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*afsrdB_3vPWHihQOitbkyA.png" /></figure><p>Remember to choose the right function based on your specific use case, and don’t be afraid to experiment and explore the various options available in both functions. With practice, you’ll become proficient in merging and joining data using Pandas, making your data analysis tasks much easier and more efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df039c73a9a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering data pipelines with Apache Airflow: A mini guide]]></title>
            <link>https://medium.com/@franczykdominik/mastering-data-pipelines-with-apache-airflow-a-mini-guide-1141b52cffdc?source=rss-3d2a1d8d511d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1141b52cffdc</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[apache-airflow]]></category>
            <dc:creator><![CDATA[Dominik Franczyk]]></dc:creator>
            <pubDate>Sun, 30 Apr 2023 20:02:59 GMT</pubDate>
            <atom:updated>2023-04-30T20:02:59.495Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*uq46k8agfNqVV4YgQpzLcw.png" /></figure><p>Apache Airflow has become the ideal solution for managing complex data pipelines. In this mini-guide, we’ll cover everything you need to know about mastering data pipelines with Apache Airflow, from basic concepts to touching on advanced techniques.</p><h4>Introduction to Apache Airflow</h4><p>Apache Airflow is an open-source platform for orchestrating workflows and data pipelines. Developed by Airbnb in 2014, it has since gained wide adoption among data engineering teams for its flexibility, extensibility, and scalability.</p><h4>Key Components</h4><ul><li><strong>DAG (Directed Acyclic Graph)</strong>: A DAG is a collection of tasks and their dependencies. It defines the order in which tasks are executed and ensures that tasks are run in the correct sequence.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*hAaSg8NwE8NRQSnuqZ4oiw.png" /></figure><ul><li><strong>Task</strong>: A task represents a single unit of work in a pipeline, such as loading data, transforming data, or running a script.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*5tc__EBDZzgFjW5fO7yppw.png" /></figure><ul><li><strong>Operator</strong>: Operators are the building blocks of Airflow tasks. They define what work needs to be done and how it should be executed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*a-37cpYwO5Yk8HTZ85dV0w.png" /></figure><h4>Setting up Apache Airflow</h4><p>To set up Apache Airflow, follow these steps:</p><ol><li>Install Airflow using pip: <strong>pip install apache-airflow</strong></li><li>Initialize the Airflow database: <strong>airflow db init</strong></li><li>Start the Airflow webserver: <strong>airflow webserver -p 8080</strong></li><li>Start the Airflow scheduler: <strong>airflow scheduler</strong></li></ol><p>Now you can access the Airflow web UI at <a href="http://localhost:8080."><strong>http://localhost:8080</strong>.</a></p><h4>Building a Data Pipeline with Apache Airflow</h4><p>Here’s a step-by-step guide to building a simple data pipeline using Apache Airflow:</p><ol><li><strong>Define a DAG</strong>: Create a new Python file in the <strong>dags</strong> folder, e.g., <strong>my_data_pipeline.py</strong>. Define a DAG by instantiating a <strong>DAG</strong> object and specifying its parameters, such as <strong>dag_id</strong>, <strong>schedule_interval</strong>, and <strong>default_args</strong>.</li></ol><pre>from datetime import timedelta<br>from airflow import DAG<br>from airflow.utils.dates import days_ago<br><br>default_args = {<br>&#39;owner&#39;: &#39;airflow&#39;,<br>&#39;retries&#39;: 3,<br>&#39;retry_delay&#39;: timedelta(minutes=5),<br>}<br><br>dag = DAG(<br>&#39;my_data_pipeline&#39;,<br>default_args=default_args,<br>description=&#39;A simple data pipeline example&#39;,<br>schedule_interval=timedelta(days=1),<br>start_date=days_ago(1),<br>)</pre><p>2. <strong>Create Tasks</strong>: Define tasks using Airflow operators, such as <strong>PythonOperator</strong>, <strong>BashOperator</strong>, or custom operators. For each task, specify its parameters, such as <strong>task_id</strong>, <strong>python_callable</strong>, or <strong>bash_command</strong>.</p><pre>from airflow.operators.python_operator import PythonOperator<br>from airflow.operators.bash_operator import BashOperator<br><br>def extract_data():<br>	# Your data extraction logic here<br>	pass<br><br>def transform_data():<br>	# Your data transformation logic here<br>	pass<br><br>def load_data():<br>	# Your data loading logic here<br>	pass<br><br>extract_task = PythonOperator(<br>	task_id=&#39;extract_data&#39;,<br>	python_callable=extract_data,<br>	dag=dag,<br>)<br><br>transform_task = PythonOperator(<br>	task_id=&#39;transform_data&#39;,<br>	python_callable=transform_data,<br>	dag=dag,<br>)<br><br>load_task = PythonOperator(<br>	task_id=&#39;load_data&#39;,<br>	python_callable=load_data,<br>	dag=dag,<br>)</pre><ol><li><strong>Set Task Dependencies</strong>: Define the order in which tasks should be executed using the <strong>set_upstream</strong> and <strong>set_downstream</strong> methods, or the <strong>&gt;&gt;</strong> and <strong>&lt;&lt;</strong> bitshift operators.</li></ol><pre># Using set_upstream and set_downstream methods<br>extract_task.set_downstream(transform_task)<br>transform_task.set_downstream(load_task)<br><br># Alternatively, using bitshift operators<br>extract_task &gt;&gt; transform_task &gt;&gt; load_task</pre><p>Now your data pipeline is defined, and Apache Airflow will execute the tasks in the specified order.</p><h4>Monitoring and Debugging Data Pipelines</h4><p>The Airflow web UI provides a visual interface for monitoring and managing your data pipelines. You can view the status of your DAGs, task instances, and task logs for troubleshooting.</p><p>Some useful features include:</p><ul><li><strong>DAG Graph View</strong>: Displays the structure of your DAG, with task dependencies and the current state of each task instance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*FU_MeRwpKwEpoVYjnHy_Ig.png" /></figure><ul><li><strong>DAG Grid View</strong>: A bar chart and grid representation of the DAG that spans across time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*xVoapC-KIn38lhflM_iFRQ.png" /></figure><ul><li><strong>Task Duration</strong>: Helps you identify performance bottlenecks by visualising the duration of each task over time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*4TmIkEZQY3K-nb01YNSuzQ.png" /></figure><p>To debug issues, you can also use Airflow’s built-in logging functionality. Task logs can be accessed via the web UI or directly from the log files stored on disk.</p><h4>Advanced Techniques and Best Practices</h4><ul><li><strong>Dynamic Pipeline Generation</strong>: Use Python code to dynamically generate pipelines based on external inputs, such as configuration files or database records.</li><li><strong>Task Retries and Error Handling</strong>: Configure your tasks to automatically retry in case of failures, and use custom error handling logic to gracefully handle exceptions.</li><li><strong>Scaling Out with Executors</strong>: Improve the performance and scalability of your pipelines by using different Airflow executors, such as the CeleryExecutor or KubernetesExecutor.</li><li><strong>Securing Your Pipelines</strong>: Implement authentication and authorisation to secure your Airflow instance, and use encryption to protect sensitive data in transit and at rest.</li><li><strong>Testing and CI/CD</strong>: Write unit tests for your DAGs and tasks, and integrate Airflow into your CI/CD pipeline for automated testing and deployment.</li></ul><p>By mastering these techniques, you’ll be well-equipped to build, monitor, and optimize data pipelines with Apache Airflow.</p><p>In this comprehensive guide, we covered the essential aspects of mastering data pipelines with Apache Airflow, from basic concepts to advanced techniques. By following these best practices, you’ll be able to develop robust and efficient data pipelines that meet your organization’s needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1141b52cffdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write a Chart API using FastAPI for our business applications]]></title>
            <link>https://medium.com/@franczykdominik/how-to-write-a-chart-api-using-fastapi-for-our-business-applications-563fd0306a07?source=rss-3d2a1d8d511d------2</link>
            <guid isPermaLink="false">https://medium.com/p/563fd0306a07</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[plotly]]></category>
            <dc:creator><![CDATA[Dominik Franczyk]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 20:06:25 GMT</pubDate>
            <atom:updated>2022-12-06T20:08:46.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SimegCeHFgEX31o_cmIuCA.png" /></figure><h4>Why we should use Charts in web apps?</h4><p>Charts are a useful tool for visualising and interpreting data in web applications. They can help users quickly and easily understand complex data sets by presenting the data in a visual format, such as a line graph, bar chart, or pie chart.</p><p>Charts can also provide a more engaging and interactive way to present data to users. For example, users can hover over or click on chart elements to see more detailed information, or use chart controls to filter or manipulate the data.</p><p>In addition, charts can be used to highlight important trends or patterns in the data that may not be immediately apparent from looking at raw data values. This can help users make more informed decisions or draw conclusions from the data.</p><p>Overall, charts can provide valuable insights into data and improve the user experience of web applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W37nCVOAdCj1GuGxoJeqbQ.png" /></figure><h4>Why FastAPI?</h4><p>FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.6+ based on standard Python type hints. It is built on top of Starlette for the web parts and Pydantic for the data parts.</p><p>FastAPI is heavily inspired by and borrows a lot from Flask and Apistar, but is designed to be even faster, simpler, and more flexible. It has a very simple and intuitive interface that is easy to learn and use.</p><p>Some of the key features of FastAPI include:</p><ul><li>Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python web frameworks available.</li><li>Fast to code: Increase the speed to develop features by about 200% to 300%. *</li><li>Fewer bugs: Reduce about 40% of human (developer) induced errors. *</li><li>Intuitive: Great editor support. Completion everywhere. Less time debugging.</li><li>Easy: Designed to be easy to use and learn. Less time reading docs.</li><li>Short: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.</li><li>Robust: Get production-ready code. With automatic interactive documentation.</li><li>Standard: Based on (and fully compatible with) the open standards for APIs: OpenAPI and JSON Schema.</li><li>As measured by independent third-party studies.</li></ul><p>FastAPI is an open-source project and is released under the MIT license. It is actively maintained and has a growing community of contributors and users. You can learn more about FastAPI and get started using it on the official website: <a href="https://fastapi.tiangolo.com/">https://fastapi.tiangolo.com/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ELhPAy3g7k3zkRjje8iVQ.png" /></figure><h4>To the point — how we can write a simple API using FastAPI to achieve our goal?</h4><p>Our API will allow us to create two chart types, bar and chart, based on the Payload (JSON) data in the POST method.</p><p>First of all, you need to install the FastAPI and the HTTP server. I recommend to do that on a local virtual environment via PIP.</p><pre>pip install fastapi<br>pip install &quot;uvicorn[standard]&quot;</pre><p>Imports:</p><pre>import plotly.graph_objects as go<br>from fastapi import FastAPI<br>from fastapi import HTTPException<br>from fastapi.responses import FileResponse<br>from plotly.offline import plot</pre><p>App initialisation:</p><pre>app = FastAPI()</pre><p>Pie chart function:</p><pre>async def pie_chart_generation(data: dict):<br>  &quot;&quot;&quot;Pie chart generation&quot;&quot;&quot;<br>  try:<br>    # We want to read x, y or labels, values from the JSON payload<br>    data[&quot;data&quot;][0][&quot;labels&quot;] = data[&quot;data&quot;][0][&quot;x&quot;]<br>    data[&quot;data&quot;][0][&quot;values&quot;] = data[&quot;data&quot;][0][&quot;y&quot;]<br>    [data[&quot;data&quot;][0].pop(element, None) for element in [&quot;x&quot;, &quot;y&quot;]]<br>    fig = go.Figure(data=data[&quot;data&quot;])<br><br>  except BaseException:<br>    fig = go.Figure(<br>      data=[<br>        go.Pie(<br>          labels=data[&quot;data&quot;][0][&quot;labels&quot;],<br>          values=data[&quot;data&quot;][0][&quot;values&quot;],<br>        )<br>      ]<br>    )<br>  return fig</pre><p>Bar chart function:</p><pre>async def bar_chart_generation(data: dict):<br>  &quot;&quot;&quot;Bar chart generation&quot;&quot;&quot;<br>  try:<br>    # We want to read x, y or labels, values from the JSON payload<br>    data[&quot;data&quot;][0][&quot;x&quot;] = data[&quot;data&quot;][0][&quot;labels&quot;]<br>    data[&quot;data&quot;][0][&quot;y&quot;] = data[&quot;data&quot;][0][&quot;values&quot;]<br>    [data[&quot;data&quot;][0].pop(element, None) for element in [&quot;values&quot;, &quot;labels&quot;]]<br>    return go.Figure(data=data[&quot;data&quot;])<br>  except BaseException:<br>    fig = go.Figure(data=data[&quot;data&quot;])<br>  return fig</pre><p>Our POST method:</p><pre>@app.post(&quot;/chart&quot;)<br>async def create_chart(data: dict):<br>  &quot;&quot;&quot;This method will print the generated chart&quot;&quot;&quot;<br>  try:<br>    # Checking of the passed type<br>    chart_type = data[&quot;data&quot;][0][&quot;type&quot;]<br>    if chart_type == &quot;pie&quot;:<br>      fig = await pie_chart_generation(data)<br>    elif chart_type == &quot;bar&quot;:<br>      fig = await bar_chart_generation(data)<br>  except Exception as e:<br>    raise HTTPException(<br>      status_code=501, detail=&quot;Chart type is not implemented&quot;<br>    ) from e<br><br>  try:<br>    # Apply the title<br>    fig.update_layout(title=data[&quot;title&quot;])<br><br>    # Save the chart to a file<br>    chart = plot(fig, output_type=&quot;file&quot;)<br><br>    # Return the chart file as the response<br>    return FileResponse(chart, media_type=&quot;image/png&quot;)<br>  except Exception as e:<br>    raise HTTPException(status_code=503,<br>                        detail=&quot;Unable to generate media&quot;) from e</pre><p>The full <strong>main.py</strong> file:</p><pre>import plotly.graph_objects as go<br>from fastapi import FastAPI<br>from fastapi import HTTPException<br>from fastapi.responses import FileResponse<br>from plotly.offline import plot<br><br>app = FastAPI()<br><br><br>async def pie_chart_generation(data: dict):<br>  &quot;&quot;&quot;Pie chart generation&quot;&quot;&quot;<br>  try:<br>    # We want to read x, y or labels, values from the JSON payload<br>    data[&quot;data&quot;][0][&quot;labels&quot;] = data[&quot;data&quot;][0][&quot;x&quot;]<br>    data[&quot;data&quot;][0][&quot;values&quot;] = data[&quot;data&quot;][0][&quot;y&quot;]<br>    [data[&quot;data&quot;][0].pop(element, None) for element in [&quot;x&quot;, &quot;y&quot;]]<br>    fig = go.Figure(data=data[&quot;data&quot;])<br><br>  except BaseException:<br>    fig = go.Figure(<br>      data=[<br>        go.Pie(<br>          labels=data[&quot;data&quot;][0][&quot;labels&quot;],<br>          values=data[&quot;data&quot;][0][&quot;values&quot;],<br>        )<br>      ]<br>    )<br>  return fig<br><br><br>async def bar_chart_generation(data: dict):<br>  &quot;&quot;&quot;Bar chart generation&quot;&quot;&quot;<br>  try:<br>    # We want to read x, y or labels, values from the JSON payload<br>    data[&quot;data&quot;][0][&quot;x&quot;] = data[&quot;data&quot;][0][&quot;labels&quot;]<br>    data[&quot;data&quot;][0][&quot;y&quot;] = data[&quot;data&quot;][0][&quot;values&quot;]<br>    [data[&quot;data&quot;][0].pop(element, None) for element in [&quot;values&quot;, &quot;labels&quot;]]<br>    return go.Figure(data=data[&quot;data&quot;])<br>  except BaseException:<br>    fig = go.Figure(data=data[&quot;data&quot;])<br>  return fig<br><br><br>@app.post(&quot;/chart&quot;)<br>async def create_chart(data: dict):<br>  &quot;&quot;&quot;This method will print the generated chart&quot;&quot;&quot;<br>  try:<br>    # Checking of the passed type<br>    chart_type = data[&quot;data&quot;][0][&quot;type&quot;]<br>    if chart_type == &quot;pie&quot;:<br>      fig = await pie_chart_generation(data)<br>    elif chart_type == &quot;bar&quot;:<br>      fig = await bar_chart_generation(data)<br>  except Exception as e:<br>    raise HTTPException(<br>      status_code=501, detail=&quot;Chart type is not implemented&quot;<br>    ) from e<br><br>  try:<br>    # Apply the title<br>    fig.update_layout(title=data[&quot;title&quot;])<br><br>    # Save the chart to a file<br>    chart = plot(fig, output_type=&quot;file&quot;)<br><br>    # Return the chart file as the response<br>    return FileResponse(chart, media_type=&quot;image/png&quot;)<br>  except Exception as e:<br>    raise HTTPException(status_code=503,<br>                        detail=&quot;Unable to generate media&quot;) from e<br><br></pre><p>If you are ready to go, simply open the terminal and run:</p><pre> uvicorn main:app --reload</pre><p>The terminal output will look as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*GtY0sgX6yoFcs-BRm1fNsw.png" /></figure><p>When you followed my steps, go to the browser and type:</p><pre>http://127.0.0.1:8000/docs</pre><p>You will see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xcRFr1hn5EwzyhRuvUaOgg.png" /></figure><p>Go to the chart and choose toTry it out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*aL0vCBYiZ4lJpy3JKytj-A.png" /></figure><p>The POST method you will use:</p><pre>POST /chart<br>{<br>    &quot;title&quot;: &quot;My Chart&quot;,<br>    &quot;data&quot;: [<br>        {<br>            &quot;type&quot;: &quot;bar&quot;,               &lt;- instead of &quot;bar&quot; you can pass &quot;pie&quot;<br>            &quot;x&quot;: [&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;],  &lt;- instead of x you can pass &quot;labels&quot;<br>            &quot;y&quot;: [1, 2, 3].              &lt;- instead of x you can pass &quot;values&quot;<br>        }<br>    ]<br>}</pre><p>Insert it in the <strong>Request body</strong> and Execute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*k2hCLTZGU1kq67pA4NDzVw.png" /></figure><p>A new window will appear with our pretty bar chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvNdPNFZ3fUXQYhQKeIU6Q.png" /></figure><p>We can do it as well for a Pie chart by changing the type in the payload and Execute it:</p><pre>POST /chart<br>{<br>    &quot;title&quot;: &quot;My Chart&quot;,<br>    &quot;data&quot;: [<br>        {<br>            &quot;type&quot;: &quot;pie&quot;,               &lt;- instead of &quot;bar&quot; you can pass &quot;pie&quot;<br>            &quot;x&quot;: [&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;],  &lt;- instead of x you can pass &quot;labels&quot;<br>            &quot;y&quot;: [1, 2, 3].              &lt;- instead of x you can pass &quot;values&quot;<br>        }<br>    ]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*9ladjZV0ri0epGACEGrDbA.png" /></figure><p>Our new chart will appear in a new browser tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2wD2Z-QNCWQ90t85AN71aA.png" /></figure><h4>In general</h4><p>To use this API, you would need to send a POST request to the /chart endpoint with a JSON body containing the data and title for the chart. The API will generate a chart using the provided data and return it as a file response.</p><p>For example, to create a pie chart with the title “My Chart” and data <br>[1, 2, 3], you could send the following request:</p><pre>POST /chart<br><br>{<br>    &quot;title&quot;: &quot;My Chart&quot;,<br>    &quot;data&quot;: [<br>        {<br>            &quot;type&quot;: &quot;pie&quot;,               &lt;- instead of &quot;bar&quot; you can pass &quot;pie&quot;<br>            &quot;x&quot;: [&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;],  &lt;- instead of x you can pass &quot;labels&quot;<br>            &quot;y&quot;: [1, 2, 3].              &lt;- instead of x you can pass &quot;values&quot;<br>        }<br>    ]<br>}</pre><p>The API will return the chart file in the response. You can then save the file and display it in your application.</p><p>Thank you for reading and have a great day!</p><blockquote><em>If you like my content, you can support me here:</em></blockquote><blockquote><a href="https://www.buymeacoffee.com/dominikengineer"><strong><em>https://www.buymeacoffee.com/dominikengineer</em></strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=563fd0306a07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I would like to say hello!]]></title>
            <link>https://medium.com/@franczykdominik/i-would-like-to-say-hello-90e619fb156a?source=rss-3d2a1d8d511d------2</link>
            <guid isPermaLink="false">https://medium.com/p/90e619fb156a</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[introduction]]></category>
            <dc:creator><![CDATA[Dominik Franczyk]]></dc:creator>
            <pubDate>Sun, 09 Oct 2022 18:38:25 GMT</pubDate>
            <atom:updated>2022-10-09T18:45:02.836Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello Medium family. I was thinking about my first post — how to introduce myself and not be seen as a boring person. My name is Dominik and I’m working as a Data Engineer in one of the biggest tour companies in middle and Eastern Europe for 3 years. So, therefore — I love to travel to discover new cultures and meet new people.</p><p><em>(I have been associated with the IT industry since 2013)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gP8EkhEq_QGOSaqvHveC3w.jpeg" /><figcaption>Marsa Alam (Egypt) — me on my way to becoming a part of the Medium community</figcaption></figure><p>In my current position, I&#39;m responsible for the core analytical system, where since this, the company is placed in the top of the organisations in my country, making thousands of $ thanks to the good analytical approach.</p><p><em>(This is one of the reasons for their success)</em></p><p>Of course, the Data Engineer was not all the time my main position, <br>I started in 2014 as a <strong>Helpdesk Specialist</strong>, trying to find my way. After a few years, I was promoted to <strong>Senior Support Specialist</strong>, but it was not enough for me. So I’ve tried to find a solution for my current situation (personal and professional). I had made a list — a list for success, where I believed, that accomplishing all the points will give me freedom and new opportunities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MIAYsCLcs6oxTleFBNGsnw.jpeg" /><figcaption>The list that I’ve made in 2019</figcaption></figure><p>As you can see, only one thing is set as DONE. Point number 7 was my beginning of working with the<em> Easy to learn, HARD to master </em>language — Python. It&#39;s funny but true — not every time your plans will be so as you plan them. This thing has pushed me into the Data world and I think it will be mastered in the next few years.</p><p>The closest points to accomplish for now are 1, 2, 3, and 8. <br>Let&#39;s explain them:</p><blockquote>1.<strong> </strong>The university — I have only a few months to be official an “Engineer”</blockquote><blockquote>2. It will take up to two years to be on 0 — the process of training my financial intelligence gives to me the first results. I generate around 5$/daily passively — so I’m on the right way to becoming financially independent in a few years. I use mostly cryptocurrencies for that.</blockquote><blockquote>3. I’m taking some English lessons with a native speaker. Hopefully, it will give good results and I will try to present them here to the Medium community. For now, I feel more confident while speaking and writing. Also, my pronunciation becomes better :)</blockquote><blockquote>8. I’m 31 and I was close to go there this year, but I forgot about the wet season before planning the trip… 😠. Tanzania — next year we will meet!</blockquote><p>After finishing these closest points, I will make a new list to find out in a few years, how the new points will be done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZcMC5TjtQOvhVb334pFXHg.jpeg" /><figcaption>Port Ghalib (Egypt)</figcaption></figure><p>Finally and in summary — I will try to share with you all my interests related to Data Engineering, Cryptocurrencies, and Travel. Feel free to ask questions and I hope that a few of you will find something for yourself in my content.</p><p>Peace and till the next time!</p><p><strong><em>Feel free to follow me for more content!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90e619fb156a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>